### Install Globalping TypeScript Client Source: https://github.com/jsdelivr/globalping-typescript/blob/master/README.md Installs the globalping npm package. This package can be used in both client-side applications via CDN or server-side applications using Node.js. ```sh npm i globalping ``` -------------------------------- ### TypeScript End-to-End Globalping Measurement Workflow Source: https://context7.com/jsdelivr/globalping-typescript/llms.txt An example demonstrating a complete workflow using the Globalping TypeScript SDK. It covers checking rate limits, creating a ping measurement with specified options, waiting for the results, and processing them, including probe details and statistics. ```typescript import { Globalping } from 'globalping'; async function performGlobalPing(target: string) { const globalping = new Globalping({ auth: 'your-api-token', throwApiErrors: false }); // Check rate limits first const limits = await globalping.getLimits(); if (limits.ok) { console.log('Remaining requests:', limits.data.rateLimit.measurements.create.remaining); if (limits.data.rateLimit.measurements.create.remaining === 0) { console.error('Rate limit exceeded'); return; } } // Create measurement const createResult = await globalping.createMeasurement({ type: 'ping', target: target, limit: 5, locations: [ { continent: 'EU' }, { continent: 'NA' }, { continent: 'AS' }, { continent: 'OC' }, { continent: 'SA' } ], measurementOptions: { packets: 5, ipVersion: 4 } }); if (!createResult.ok) { console.error('Failed to create measurement:', createResult.data.error.message); return; } console.log('Measurement created:', createResult.data.id); console.log('Using probes:', createResult.data.probesCount); // Wait for completion console.log('Waiting for results...'); const result = await globalping.awaitMeasurement(createResult.data.id); if (!result.ok) { console.error('Failed to get results:', result.data.error.message); return; } // Process results console.log(' Results from', result.data.results.length, 'probes:'); Globalping.assertMeasurementType('ping', result.data); result.data.results.forEach((probeResult, index) => { console.log(` Probe ${index + 1}:`); console.log(' Location:', probeResult.probe.location.city, ',', probeResult.probe.location.country); console.log(' Network:', probeResult.probe.location.network); if ('stats' in probeResult.result) { console.log(' Packets sent:', probeResult.result.stats.sent); console.log(' Packets received:', probeResult.result.stats.rcv); console.log(' Packet loss:', probeResult.result.stats.loss + '%'); console.log(' Min RTT:', probeResult.result.stats.min, 'ms'); console.log(' Avg RTT:', probeResult.result.stats.avg, 'ms'); console.log(' Max RTT:', probeResult.result.stats.max, 'ms'); } else { console.log(' Status:', probeResult.result.status); } }); return result.data; } // Execute performGlobalPing('example.com') .then(() => console.log(' Measurement complete')) .catch(error => console.error('Unexpected error:', error)); ``` -------------------------------- ### Get API Rate Limits with TypeScript Source: https://context7.com/jsdelivr/globalping-typescript/llms.txt Fetches and displays current API rate limit details, including limit, remaining quota, and reset time. This function requires an authenticated API token or IP address to check user-specific limits. It outputs the type of limit, the absolute limit, remaining quota, and the time in seconds until the limit resets, along with a calculated reset date and a warning if usage is high. ```typescript const limitsResult = await globalping.getLimits(); if (limitsResult.ok) { const limits = limitsResult.data.rateLimit; console.log('Rate limit type:', limits.measurements.create.type); // Type: 'ip' (unauthenticated) or 'user' (authenticated) console.log('Limit:', limits.measurements.create.limit); console.log('Remaining:', limits.measurements.create.remaining); console.log('Reset in seconds:', limits.measurements.create.reset); // Calculate when limits reset const resetDate = new Date(Date.now() + limits.measurements.create.reset * 1000); console.log('Limits reset at:', resetDate.toISOString()); // Check if near limit const percentUsed = (1 - limits.measurements.create.remaining / limits.measurements.create.limit) * 100; if (percentUsed > 80) { console.warn('Rate limit usage high:', percentUsed.toFixed(1) + '%'); } } ``` -------------------------------- ### Get Rate Limits with Globalping API Source: https://github.com/jsdelivr/globalping-typescript/blob/master/README.md Retrieves the current rate limit status for the authenticated user or IP address using the Globalping API client. The response details the available rate limits. ```ts const result = await globalping.getLimits(); console.log(result); // => { data: { rateLimit: { ... }, ... }, ... } ``` -------------------------------- ### Get Measurement Status with Globalping API Source: https://github.com/jsdelivr/globalping-typescript/blob/master/README.md Retrieves the current status of an existing measurement by its ID using the Globalping API client. The returned object contains the measurement's current state. ```ts const result = await globalping.getMeasurement(id); console.log(result); // => { data: { id: string, status: string, ... }, ... } ``` -------------------------------- ### Get Measurement Status in TypeScript Source: https://context7.com/jsdelivr/globalping-typescript/llms.txt Retrieves the status of a specific measurement, including partial results if in progress. Requires the globalping library and a measurement ID. Outputs status, type, target, probe count, and results; handles errors like not found or rate limited. Type-safe access is provided for different measurement types. ```typescript const measurementId = 'abc123xyz'; const result = await globalping.getMeasurement(measurementId); if (result.ok) { console.log('Measurement status:', result.data.status); // Status can be: 'in-progress', 'finished', 'failed' console.log('Type:', result.data.type); console.log('Target:', result.data.target); console.log('Probes count:', result.data.probesCount); console.log('Results:', result.data.results); // Type-safe access to measurement-specific data if (Globalping.isMeasurementType('ping', result.data)) { console.log('Ping options:', result.data.measurementOptions); } } else { if (Globalping.isHttpStatus(404, result)) { console.error('Measurement not found'); } else if (Globalping.isHttpStatus(429, result)) { console.error('Rate limited:', result.data.error.message); } } ``` -------------------------------- ### Initialize Globalping Client in TypeScript Source: https://context7.com/jsdelivr/globalping-typescript/llms.txt Creates instances of the Globalping client with authentication, custom user agents, error handling modes, and timeouts. Requires the 'globalping' package import and an API token for authenticated use. Outputs a client instance for subsequent API interactions; defaults to non-throwing errors for known API issues. ```typescript import { Globalping } from 'globalping'; // Basic initialization without authentication const globalping = new Globalping(); // With authentication token const authenticatedClient = new Globalping({ auth: 'your-api-token-from-dash.globalping.io' }); // With custom configuration const customClient = new Globalping({ auth: 'your-api-token', userAgent: 'MyApp/1.0.0', throwApiErrors: false, // Default: known API errors return as data timeout: 30000 // Request timeout in milliseconds (default: 30000) }); // For throwApiErrors mode, errors are thrown as exceptions const throwingClient = new Globalping({ throwApiErrors: true }); ``` -------------------------------- ### Initialize Globalping Client with UMD Build Source: https://github.com/jsdelivr/globalping-typescript/blob/master/README.md Initializes the Globalping client when using the UMD build, typically in a browser environment via a CDN. The Globalping object is expected to be available globally. ```ts const { Globalping } = window.globalping; const globalping = new Globalping(/* options */); ``` -------------------------------- ### List Available Probes in TypeScript Source: https://context7.com/jsdelivr/globalping-typescript/llms.txt Fetches a list of currently online probes with metadata and locations. Depends on the globalping library. Outputs probe count and details like location, network, ASN, tags. Allows filtering, e.g., by continent. No inputs required beyond API access. ```typescript const probesResult = await globalping.listProbes(); if (probesResult.ok) { console.log('Total probes online:', probesResult.data.length); probesResult.data.forEach(probe => { console.log('Probe version:', probe.version); console.log('Location:', probe.location); console.log(' Continent:', probe.location.continent); console.log(' Country:', probe.location.country); console.log(' City:', probe.location.city); console.log(' Latitude:', probe.location.latitude); console.log(' Longitude:', probe.location.longitude); console.log('Network:', probe.location.network); console.log('ASN:', probe.location.asn); console.log('Tags:', probe.tags); }); // Filter probes by location const europeanProbes = probesResult.data.filter( probe => probe.location.continent === 'EU' ); console.log('European probes:', europeanProbes.length); } ``` -------------------------------- ### Create MTR Measurement in TypeScript Source: https://context7.com/jsdelivr/globalping-typescript/llms.txt This code shows how to run an MTR (My Traceroute) measurement combining traceroute and ping. It depends on the globalping library and API access. Inputs are target, limit, locations, and options; outputs the measurement ID. Note that it supports protocols like ICMP, TCP, UDP with specific port requirements. ```typescript const mtrResult = await globalping.createMeasurement({ type: 'mtr', target: 'github.com', limit: 2, locations: [ { city: 'London' }, { city: 'Singapore' } ], measurementOptions: { protocol: 'ICMP', // ICMP, TCP, UDP port: 443, packets: 10, ipVersion: 4 } }); if (mtrResult.ok) { console.log('MTR measurement ID:', mtrResult.data.id); } ``` -------------------------------- ### Initialize Globalping Client in TypeScript (ESM/CJS) Source: https://github.com/jsdelivr/globalping-typescript/blob/master/README.md Initializes the Globalping client in an ESM/CJS application. An optional authentication token can be provided during initialization for authenticated API requests. More advanced configuration options are available. ```ts import { Globalping } from 'globalping'; const globalping = new Globalping({ auth: 'your-globalping-api-token', // Optional. // See the Advanced configuration section below for more options. }); ``` -------------------------------- ### List Probes with Globalping API Source: https://github.com/jsdelivr/globalping-typescript/blob/master/README.md Fetches a list of all currently online probes and their associated metadata, including location and tags, using the Globalping API client. The response contains an array of probe objects. ```ts const result = await globalping.listProbes(); console.log(result); // => { data: [ { version: string, ... }, ... ], ... } ``` -------------------------------- ### Create a Measurement with Globalping API Source: https://github.com/jsdelivr/globalping-typescript/blob/master/README.md Creates a new measurement using the Globalping API client. The measurement runs asynchronously. The result object should be checked for success ('ok' property) before accessing its data. Handles potential API errors. ```ts const result = await globalping.createMeasurement({ type: 'ping', target: 'example.com', }); if (!result.ok) { // See the Error handling section below. } console.log(result); // => { data: { id: string, probesCount: number }, ... } ``` -------------------------------- ### Create Traceroute Measurement in TypeScript Source: https://context7.com/jsdelivr/globalping-typescript/llms.txt This snippet demonstrates how to create a traceroute measurement using the globalping library. It requires the globalping package and API authentication. Input includes target domain, limit, locations, and measurement options; output is the measurement ID if successful. Limitations include rate limiting and valid location options. ```typescript const tracerouteResult = await globalping.createMeasurement({ type: 'traceroute', target: 'cloudflare.com', limit: 3, locations: [ { country: 'US' }, { country: 'JP' }, { country: 'BR' } ], measurementOptions: { protocol: 'ICMP', // ICMP, TCP, UDP port: 443, // Required for TCP/UDP ipVersion: 4 } }); if (tracerouteResult.ok) { console.log('Traceroute measurement:', tracerouteResult.data.id); } ``` -------------------------------- ### Create HTTP Measurement in TypeScript Source: https://context7.com/jsdelivr/globalping-typescript/llms.txt Performs HTTP requests from global probes to measure web service availability and performance. Supports method specification (GET/POST etc.), custom headers, protocols (HTTP/HTTPS/HTTP2/HTTP3), and IP versions. Returns measurement details or errors, with specific handling for rate limits (429 status); location filtering by region. ```typescript const httpResult = await globalping.createMeasurement({ type: 'http', target: 'https://api.example.com/health', limit: 10, locations: [ { region: 'Northern Europe' }, { region: 'Northern America' } ], measurementOptions: { request: { method: 'GET', // GET, POST, HEAD, OPTIONS, etc. headers: { 'Accept': 'application/json', 'User-Agent': 'MyApp/1.0' } }, protocol: 'HTTPS', // HTTP, HTTPS, HTTP2, HTTP3 ipVersion: 4 } }); if (!httpResult.ok) { if (Globalping.isHttpStatus(429, httpResult)) { console.error('Rate limited:', httpResult.data.error.message); } } else { console.log('HTTP measurement created:', httpResult.data.id); } ``` -------------------------------- ### Create DNS Measurement in TypeScript Source: https://context7.com/jsdelivr/globalping-typescript/llms.txt Executes DNS lookups from specified locations to evaluate resolution behavior and geographical variations. Configurable with query types (A, AAAA, etc.), custom resolvers, protocols (UDP/TCP), and tracing. Returns success status, measurement ID, and probe count; requires authentication for API access. ```typescript const dnsResult = await globalping.createMeasurement({ type: 'dns', target: 'example.com', limit: 3, locations: [ { continent: 'EU' }, { continent: 'AS' } ], measurementOptions: { query: { type: 'A' // A, AAAA, CNAME, MX, TXT, etc. }, resolver: '8.8.8.8', // Optional custom resolver protocol: 'UDP', // UDP or TCP trace: true // Enable DNS trace } }); if (dnsResult.ok) { console.log('DNS measurement ID:', dnsResult.data.id); console.log('Probes count:', dnsResult.data.probesCount); } ``` -------------------------------- ### TypeScript Type Guards and Assertions for Globalping Responses Source: https://context7.com/jsdelivr/globalping-typescript/llms.txt Demonstrates how to use built-in type guards and assertions from the Globalping SDK to ensure type-safe access to measurement data. This includes checking measurement types, HTTP status codes, and asserting specific types to narrow down TypeScript's understanding of response objects. ```typescript const measurementId = 'abc123xyz'; const result = await globalping.getMeasurement(measurementId); if (!result.ok) { console.error('Failed to get measurement'); return; } // Type guard: check measurement type if (Globalping.isMeasurementType('ping', result.data)) { // TypeScript knows this is a ping measurement console.log('Ping packets:', result.data.measurementOptions?.packets); result.data.results.forEach(probeResult => { if ('stats' in probeResult.result) { console.log('RTT average:', probeResult.result.stats.avg); } }); } // Type assertion: throws if type doesn't match try { Globalping.assertMeasurementType('dns', result.data); // Now TypeScript knows this is definitely a DNS measurement console.log('DNS resolver:', result.data.measurementOptions?.resolver); } catch (error) { console.error('Not a DNS measurement:', error); } // HTTP status type guard if (Globalping.isHttpStatus(200, result)) { // TypeScript knows the response is successful console.log('Success response:', result.data); } // HTTP status assertion const createResult = await globalping.createMeasurement({ type: 'ping', target: 'example.com' }); try { Globalping.assertHttpStatus(202, createResult); // Guaranteed to be 202 response console.log('Created:', createResult.data.id); } catch (error) { console.error('Expected 202 status:', error); } ``` -------------------------------- ### Handle API Errors with Try-Catch in TypeScript Source: https://context7.com/jsdelivr/globalping-typescript/llms.txt Illustrates error handling using traditional try-catch blocks by setting `throwApiErrors: true` in the Globalping client configuration. This approach automatically throws errors for API or HTTP failures, allowing for centralized error management within catch blocks. It differentiates between `ApiError` (for known API errors with JSON responses) and `HttpError` (for general HTTP errors) and includes a fallback for unexpected network or other errors. ```typescript import { Globalping, ApiError, HttpError } from 'globalping'; const globalping = new Globalping({ throwApiErrors: true }); try { const result = await globalping.createMeasurement({ type: 'ping', target: 'example.com', limit: 1000 }); // No need to check result.ok - data is always available here console.log('Measurement ID:', result.data.id); console.log('Probes count:', result.data.probesCount); } catch (error) { if (error instanceof ApiError) { // Known API error with JSON response console.error('API Error:', error.data.error.type); console.error('Message:', error.data.error.message); console.error('Status:', error.response.status); } else if (error instanceof HttpError) { // HTTP error without valid JSON response console.error('HTTP Error:', error.message); console.error('Status:', error.response.status); } else { // Network error, timeout, or other unexpected error console.error('Unexpected error:', error); } } ``` -------------------------------- ### Create Ping Measurement in TypeScript Source: https://context7.com/jsdelivr/globalping-typescript/llms.txt Initiates a ping measurement to assess network latency and connectivity to a target host using distributed probes. Supports limits on probe count, location filters by continent/country/city, and options like packet size and IP version. Returns an object with success status, measurement ID, and probe count; handles errors via result checking. ```typescript import { Globalping } from 'globalping'; const globalping = new Globalping({ auth: 'your-api-token' }); // Basic ping measurement const pingResult = await globalping.createMeasurement({ type: 'ping', target: 'example.com' }); if (!pingResult.ok) { console.error('Failed to create measurement:', pingResult.data.error); } else { console.log('Measurement created:', pingResult.data); // Output: { id: 'abc123', probesCount: 1 } } // Advanced ping with options and location filters const advancedPing = await globalping.createMeasurement({ type: 'ping', target: 'google.com', limit: 5, // Number of probes to use locations: [ { continent: 'NA' }, { country: 'DE' }, { city: 'Tokyo' } ], measurementOptions: { packets: 10, // Number of ping packets ipVersion: 4 // 4 or 6 } }); if (advancedPing.ok) { console.log('Created measurement:', advancedPing.data.id); console.log('Using probes:', advancedPing.data.probesCount); } ``` -------------------------------- ### Handle API Errors with throwApiErrors: true Source: https://github.com/jsdelivr/globalping-typescript/blob/master/README.md Illustrates error handling when `throwApiErrors` is set to true. All errors, including known API errors, are thrown as exceptions. This simplifies success data access but requires try-catch blocks for error management. ```ts import { ApiError, HttpError } from 'globalping'; try { const result = await globalping.createMeasurement(); console.log(result.data) // => { id: string, probesCount: number } } catch (e) { if (e instanceof ApiError) { // Any error with a valid JSON response body. } else if (e instanceof HttpError) { // Any HTTP error with an invalid response body. } else { // Any other error. } } ``` -------------------------------- ### Handle API Errors with throwApiErrors: false (Default) Source: https://github.com/jsdelivr/globalping-typescript/blob/master/README.md Demonstrates error handling when `throwApiErrors` is set to false (the default). Known API errors are returned as part of the result object, requiring explicit checks using `result.ok`. Unexpected errors are still thrown as exceptions. ```ts const result = await globalping.createMeasurement(); // This is sufficient if you only care about success/failure. if (result.ok) { // result.data is the success response, e.g., { id: string, probesCount: number } } else { // result.data can be any of the possible error responses if (Globalping.isHttpStatus(400, result)) { // You can also access result.data.error.params here which is specific to this status code. } } ``` -------------------------------- ### Handle API Errors Explicitly with TypeScript Source: https://context7.com/jsdelivr/globalping-typescript/llms.txt Demonstrates explicit error handling by configuring the Globalping client with `throwApiErrors: false`. This method allows for checking the `ok` status of each API call and accessing detailed error information from the response data. It includes specific checks for HTTP status codes like 400 (validation errors), 422 (no probes found), and 429 (rate limiting). ```typescript const globalping = new Globalping({ throwApiErrors: false }); const result = await globalping.createMeasurement({ type: 'ping', target: 'example.com', limit: 1000 // Invalid: exceeds maximum }); // Check if operation succeeded if (result.ok) { console.log('Measurement ID:', result.data.id); } else { // Access error details with full type safety console.error('Error:', result.data.error.type); console.error('Message:', result.data.error.message); // Check specific HTTP status codes if (Globalping.isHttpStatus(400, result)) { // Validation error - access parameter details console.error('Validation errors:', result.data.error.params); if (result.data.error.params) { Object.entries(result.data.error.params).forEach(([param, error]) => { console.error(` ${param}: ${error}`); }); } } else if (Globalping.isHttpStatus(422, result)) { // No probes found error console.error('No probes available for the specified criteria'); } else if (Globalping.isHttpStatus(429, result)) { // Rate limit error console.error('Rate limited - retry later'); } } ``` -------------------------------- ### Await Measurement Completion in TypeScript Source: https://context7.com/jsdelivr/globalping-typescript/llms.txt Polls the API until a measurement completes and returns final results. Uses the globalping library and needs a measurement ID. Outputs completed status and per-probe results with type-safe access. Throws a timeout error if it exceeds 60 seconds. ```typescript const measurementId = 'abc123xyz'; try { const result = await globalping.awaitMeasurement(measurementId); if (result.ok) { console.log('Measurement completed:', result.data.status); // result.data.status is guaranteed to be 'finished' // Process results from all probes for (const probeResult of result.data.results) { console.log('Probe location:', probeResult.probe.location); console.log('Probe result:', probeResult.result); // Type-safe result access if (Globalping.isMeasurementType('ping', result.data)) { const pingResult = probeResult.result; if ('stats' in pingResult) { console.log('Ping stats:', pingResult.stats); console.log('Min RTT:', pingResult.stats.min); console.log('Avg RTT:', pingResult.stats.avg); console.log('Max RTT:', pingResult.stats.max); } } } } else { console.error('Failed to retrieve measurement:', result.data.error); } } catch (error) { // Thrown if measurement takes more than 60 seconds console.error('Timeout waiting for measurement:', error); } ``` -------------------------------- ### Await Measurement Completion with Globalping API Source: https://github.com/jsdelivr/globalping-typescript/blob/master/README.md Waits for a measurement to complete and returns its final state. This method repeatedly polls the API until the measurement status is 'finished'. Useful for synchronous retrieval of measurement results. ```ts const result = await globalping.awaitMeasurement(id); console.log(result); // => { data: { id: string, status: 'finished', ... }, ... } ``` -------------------------------- ### Check HTTP Status Code with Globalping TypeScript Source: https://github.com/jsdelivr/globalping-typescript/blob/master/README.md Provides utility methods `assertHttpStatus` and `isHttpStatus` for checking the HTTP status code of an API response. This is useful for validating responses, especially when handling errors. ```ts const result = await globalping.createMeasurement(id); if (Globalping.isHttpStatus(400, result)) { // You can now access parameter validation error details. } ``` -------------------------------- ### Assert Measurement Type with Globalping TypeScript Source: https://github.com/jsdelivr/globalping-typescript/blob/master/README.md Offers utility methods `assertMeasurementType` and `isMeasurementType` to verify the type of a measurement result. This allows for type-safe access to measurement-specific properties after validation. ```ts const result = await globalping.awaitMeasurement(id); Globalping.assertMeasurementType('ping', result); // You can now access ping-specific properties on result.data ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.