@zharp/cloudflare 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +88 -3
- package/dist/index.d.mts +163 -0
- package/dist/index.d.ts +163 -0
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +9 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +70 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../internal/src/debug-ids.ts","../../browser/src/util.ts","../../browser/src/instrument/errors.ts","../../../internal/src/bodies.ts","../../../internal/src/headers.ts","../../browser/src/transport.ts","../src/version.ts","../src/settings.ts","../src/tracing.ts","../src/d1.ts","../../browser/src/instrument/http.ts","../src/fetch.ts","../src/state.ts","../src/bindings.ts","../src/hono.ts","../src/handlers.ts","../src/index.ts"],"names":["DEBUG_IDS_ATTRIBUTE","files","parsed","registry","g","value","frameFile","line","text","match","clean","raw","file","stackFiles","stack","out","refresh","entries","id","debugIdsFor","debugIdAttributes","ids","randomHex","bytes","buf","c","i","newTraceId","newSpanId","now","perf","toNanos","ms","whole","fraction","anyValue","depth","v","keyValues","safeString","attributes","key","json","safely","fn","byteLength","asError","error","exceptionAttributes","handled","type","message","head","CONSOLE_LEVELS","watchConsole","methods","log","originals","inside","method","original","patched","args","arg","FILTERED","CONTAINS","EXACT","URL_EXACT","normalize","isSecretKey","extra","k","p","redactUrl","url","q","hash","query","redacted","redactQuery","pair","eq","SECRET","MAX_HEADERS","MAX_VALUE","headerSettings","option","env","shown","name","settings","headerAttributes","side","headers","count","rawName","BATCH_SIZE","FLUSH_MS","MAX_QUEUE","MAX_BACKOFF_MS","MAX_BODY_BYTES","MAX_KEEPALIVE_BYTES","keyRejected","post","endpoint","signal","body","keepalive","payload","response","keepaliveInFlight","sendOnHide","size","retryable","status","split","items","limit","wrap","overhead","group","item","itemSize","Exporter","timers","record","records","batches","unsent","b","VERSION","DEFAULT_ENDPOINT","flag","versionMetadata","named","resolveSettings","envInput","config","defaults","options","version","release","rate","headersEnv","AlsContextManager","AsyncLocalStorage","ROOT_CONTEXT","ctx","thisArg","target","manager","contextManager","REQUEST","createContextKey","activeContext","requestOf","withRequest","state","activeSpan","span","trace","ZharpSpan","sink","setSpanSink","otlpKind","kind","MAX_EVENTS","parent","request","startTime","links","valid","TraceFlags","timeOf","SpanStatusCode","attributesOrTime","time","isTime","link","exception","onRecordedException","endTime","context","event","setRecordedExceptionHandler","handler","input","startSpan","SpanKind","withSpan","ZharpTracer","parentCtx","tracer","provider","TRACEPARENT","parseTraceparent","header","formatTraceparent","propagator","carrier","setter","getter","registered","registerOpenTelemetry","otelContext","propagation","failures","claimQueryFailure","failure","unclaimedQueryFailures","callSite","boundary","holder","sqliteCode","operationOf","sql","MAX_SQL","queryFailure","database","frames","code","traced","run","result","meta","rows","sqlOf","RUNS","wrapStatement","statement","captureErrors","proxy","prop","wrapD1","db","batch","statements","list","s","real","exec","base","matches","patterns","pattern","installed","instrumentGlobalFetch","runtime","init","tracedFetch","send","binding","SEVERITY","globalTags","globalUser","Runtime","resource","scope","contextAttributes","level","attrs","seen","user","setTag","setUser","warnedNoKey","lastConfig","runtimeFor","disabled","currentRuntime","CLASSES","names","bindingKind","MARK","cache","instrumentEnv","receiver","wrapBinding","byName","cached","wrapped","marked","build","fetcher","member","describe","call","isHono","app","honoRoute","path","matched","routes","entry","route","WRAPPED","hookHonoErrors","current","WORKER","PAGES","ID_SEGMENT","routeFromPath","segment","invoke","invocation","waiter","after","done","watchWaitUntil","promise","watched","requestInvocation","mechanism","cf","responseDone","workerMethod","self","wrappedEnv","controller","HANDLERS","withZharp","configOrHandler","maybeHandler","instrumentClass","WEBSOCKET","NOT_RPC","instrumentDurableObject","cls","newTarget","instance","className","callArgs","obj","zharpPagesPlugin","settingsFrom","noopSpan","Zharp","fail","src_default"],"mappings":"6KAeO,IAAMA,EAAAA,CAAsB,iBAAA,C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kB,OAAOjO,CAAAA,CAAGmS,EAAQ,CAAA,CACzC,IAAMhL,CAAAA,CAAO4B,EAAelG,CAAAA,CAAM,CAAE,UAAA,CAAYjD,CAAkB,CAAC,CAAA,CAC7DyS,EAAQlS,CAAAA,EAAmB,CAC/BgH,CAAAA,CAAK,SAAA,CAAU,CAAE,IAAA,CAAMe,eAAe,KAAA,CAAO,OAAA,CAAShI,CAAAA,CAAQC,CAAK,CAAA,CAAE,OAAQ,CAAC,CAAA,CAC9EgH,CAAAA,CAAK,GAAA,GACP,CAAA,CACA,GAAI,CACF,IAAMgE,CAAAA,CAASlC,CAAAA,CAAS9B,CAAAA,CAAM,IAAMnH,CAAAA,CAAGmH,CAAI,CAAC,CAAA,CAC5C,OAAIgE,CAAAA,EAAU,OAAQA,CAAAA,CAAe,IAAA,EAAS,WACpCA,CAAAA,CAAe,IAAA,CACpB1N,CAAAA,GACC0J,CAAAA,CAAK,GAAA,EAAI,CACF1J,GAER0C,CAAAA,EAAmB,CAClB,MAAAkS,CAAAA,CAAKlS,CAAK,CAAA,CACJA,CACR,CACF,CAAA,EAEFgH,CAAAA,CAAK,GAAA,EAAI,CACFgE,CAAAA,CACT,CAAA,MAAShL,EAAO,CACd,MAAAkS,CAAAA,CAAKlS,CAAK,CAAA,CACJA,CACR,CACF,CAAA,CAGA,IAAI,OAAA,EAA8B,CAChC,OAAO+G,CAAAA,IAAc,OACvB,CAAA,CAGA,MAAM,KAAA,EAAuB,CAC3B,MAAM+G,CAAAA,EAAe,EAAG,KAAA,GAC1B,CACF,CAAA,CAEOqE,EAAAA,CAAQF","file":"index.mjs","sourcesContent":["/**\r\n * Debug IDs: which build of a file a stack frame came from, so Zharp can find its source map.\r\n *\r\n * `zharp sourcemaps inject` (and the bundler plugins) add a line to every emitted JS file that\r\n * registers it at load time:\r\n *\r\n * (globalThis.__zharpDebugIds ||= {})[new Error().stack] = \"<uuid>\"\r\n *\r\n * The key is a stack captured inside the file, so its top frame names the file exactly as this\r\n * runtime sees it — whatever the CDN, URL or path. Parsing those stacks gives file → debug ID;\r\n * an error then carries the IDs of the files in its own stack as `zharp.debug_ids`, a JSON\r\n * object `{ \"<file as it appears in the stack>\": \"<uuid>\" }`.\r\n */\r\n\r\n/** The attribute an error carries its files' debug IDs in. */\r\nexport const DEBUG_IDS_ATTRIBUTE = 'zharp.debug_ids';\r\n\r\n/** File → debug ID, from the registry entries parsed so far. */\r\nconst files = new Map<string, string>();\r\n/** Registry keys already parsed. The registry only grows, so each stack is parsed once. */\r\nconst parsed = new Set<string>();\r\n\r\nfunction registry(): Record<string, unknown> | undefined {\r\n const g = typeof globalThis !== 'undefined' ? (globalThis as any) : undefined;\r\n const value = g && g.__zharpDebugIds;\r\n return value && typeof value === 'object' ? value : undefined;\r\n}\r\n\r\n/**\r\n * The file a stack frame line points at, as written in the line: V8 (`at fn (file:1:2)`,\r\n * `at file:1:2`), and Gecko/WebKit (`fn@file:1:2`, `@file:1:2`). Undefined for anything else.\r\n */\r\nexport function frameFile(line: string): string | undefined {\r\n const text = line.trim();\r\n if (!text) return undefined;\r\n let match = /^at (?:async )?(?:.*? \\()?(.+?):\\d+:\\d+\\)?$/.exec(text);\r\n if (match) return clean(match[1]);\r\n if (text.startsWith('at ')) return undefined;\r\n match = /^(?:[^@]*@)?(.+?):\\d+:\\d+$/.exec(text);\r\n return match ? clean(match[1]) : undefined;\r\n}\r\n\r\nfunction clean(raw: string): string | undefined {\r\n // Hermes release builds (React Native) write \"address at index.android.bundle\": the file is the bundle.\r\n const file = raw.replace(/^address at /, '');\r\n // `eval at fn (file:1:2), <anonymous>` and friends name no file of their own.\r\n if (!file || file.includes('eval at ') || file === '<anonymous>' || file === 'native') return undefined;\r\n return file;\r\n}\r\n\r\n/** Every file in a stack, in order, each once. */\r\nexport function stackFiles(stack: string): string[] {\r\n const out: string[] = [];\r\n for (const line of stack.split('\\n')) {\r\n const file = frameFile(line);\r\n if (file && !out.includes(file)) out.push(file);\r\n }\r\n return out;\r\n}\r\n\r\n/** Parse the registry entries not seen yet: each one's top frame is the file that registered it. */\r\nfunction refresh(): void {\r\n const entries = registry();\r\n if (!entries) return;\r\n for (const stack in entries) {\r\n if (parsed.has(stack)) continue;\r\n parsed.add(stack);\r\n const id = entries[stack];\r\n if (typeof id !== 'string') continue;\r\n for (const line of stack.split('\\n')) {\r\n const file = frameFile(line);\r\n if (file) {\r\n files.set(file, id);\r\n break;\r\n }\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * The debug IDs of the files in `stack` that registered one, or undefined when none did (no\r\n * injected build, or only third-party frames).\r\n */\r\nexport function debugIdsFor(stack: string | undefined): Record<string, string> | undefined {\r\n if (!stack) return undefined;\r\n try {\r\n refresh();\r\n if (files.size === 0) return undefined;\r\n let out: Record<string, string> | undefined;\r\n for (const file of stackFiles(stack)) {\r\n const id = files.get(file);\r\n if (id) (out ??= {})[file] = id;\r\n }\r\n return out;\r\n } catch {\r\n return undefined;\r\n }\r\n}\r\n\r\n/** `{ 'zharp.debug_ids': '<json>' }` for `stack`, or an empty object. Spread it into an error's attributes. */\r\nexport function debugIdAttributes(stack: string | undefined): Record<string, string> {\r\n const ids = debugIdsFor(stack);\r\n return ids ? { [DEBUG_IDS_ATTRIBUTE]: JSON.stringify(ids) } : {};\r\n}\r\n\r\n/** For tests: forget everything parsed. */\r\nexport function resetDebugIdCache(): void {\r\n files.clear();\r\n parsed.clear();\r\n}\r\n","/**\r\n * Small pieces everything else uses: IDs, clocks, and OTLP/JSON values.\r\n */\r\n\r\n/** Random bytes as lowercase hex. `crypto.getRandomValues` everywhere it exists; the fallback is about collisions, not secrecy. */\r\nexport function randomHex(bytes: number): string {\r\n const buf = new Uint8Array(bytes);\r\n const c = typeof crypto !== 'undefined' ? crypto : undefined;\r\n if (c && c.getRandomValues) c.getRandomValues(buf);\r\n else for (let i = 0; i < bytes; i++) buf[i] = (Math.random() * 256) | 0;\r\n let out = '';\r\n for (let i = 0; i < bytes; i++) out += (buf[i] < 16 ? '0' : '') + buf[i].toString(16);\r\n // All zeros means \"absent\" in W3C Trace Context; astronomically unlikely, but free to rule out.\r\n return /^0+$/.test(out) ? randomHex(bytes) : out;\r\n}\r\n\r\nexport const newTraceId = () => randomHex(16);\r\nexport const newSpanId = () => randomHex(8);\r\n\r\n/** Milliseconds since the epoch, with the sub-millisecond precision `performance` gives. */\r\nexport function now(): number {\r\n const perf = typeof performance !== 'undefined' ? performance : undefined;\r\n return perf && perf.timeOrigin ? perf.timeOrigin + perf.now() : Date.now();\r\n}\r\n\r\n/**\r\n * Epoch milliseconds as the decimal nanosecond string OTLP wants. Built as text: nanoseconds\r\n * since 1970 are past what a double holds exactly.\r\n */\r\nexport function toNanos(ms: number): string {\r\n const whole = Math.floor(ms);\r\n const fraction = Math.round((ms - whole) * 1e6);\r\n return fraction >= 1e6 ? `${whole + 1}000000` : `${whole}${String(fraction).padStart(6, '0')}`;\r\n}\r\n\r\n/** One OTLP AnyValue. */\r\nexport function anyValue(value: unknown, depth = 0): Record<string, unknown> {\r\n if (typeof value === 'string') return { stringValue: value };\r\n if (typeof value === 'boolean') return { boolValue: value };\r\n if (typeof value === 'number') return Number.isInteger(value) ? { intValue: value } : { doubleValue: value };\r\n if (value instanceof Error) return { stringValue: `${value.name}: ${value.message}` };\r\n if (value === null || value === undefined) return { stringValue: '' };\r\n if (depth < 4 && Array.isArray(value)) return { arrayValue: { values: value.map((v) => anyValue(v, depth + 1)) } };\r\n if (depth < 4 && typeof value === 'object') return { kvlistValue: { values: keyValues(value as Record<string, unknown>, depth + 1) } };\r\n return { stringValue: safeString(value) };\r\n}\r\n\r\n/** An attribute map as an OTLP KeyValue list. `undefined` values are left out. */\r\nexport function keyValues(attributes: Record<string, unknown>, depth = 0): Array<{ key: string; value: unknown }> {\r\n const out: Array<{ key: string; value: unknown }> = [];\r\n for (const key in attributes) {\r\n const value = attributes[key];\r\n if (value !== undefined) out.push({ key, value: anyValue(value, depth) });\r\n }\r\n return out;\r\n}\r\n\r\nexport function safeString(value: unknown): string {\r\n if (typeof value === 'string') return value;\r\n if (value instanceof Error) return `${value.name}: ${value.message}`;\r\n try {\r\n const json = JSON.stringify(value);\r\n return json === undefined ? String(value) : json;\r\n } catch {\r\n return String(value);\r\n }\r\n}\r\n\r\n/** Run `fn`, swallowing anything it throws: the SDK must never break the page it is on. */\r\nexport function safely<T>(fn: () => T): T | undefined {\r\n try {\r\n return fn();\r\n } catch {\r\n return undefined;\r\n }\r\n}\r\n\r\nexport const isBrowser = () => typeof window !== 'undefined' && typeof document !== 'undefined';\r\n\r\n/** UTF-8 byte length. */\r\nexport function byteLength(text: string): number {\r\n return typeof TextEncoder !== 'undefined' ? new TextEncoder().encode(text).length : text.length * 2;\r\n}\r\n","/**\r\n * Uncaught errors, unhandled rejections and (when asked for) the console.\r\n */\r\nimport { debugIdAttributes } from '@zharp/internal/debug-ids';\r\nimport { safeString, safely } from '../util';\r\n\r\n/** Whatever was thrown, as an Error. */\r\nexport function asError(value: unknown): Error {\r\n if (value instanceof Error) return value;\r\n if (value && typeof value === 'object' && typeof (value as any).message === 'string') {\r\n const error = new Error((value as any).message);\r\n error.name = typeof (value as any).name === 'string' ? (value as any).name : 'Error';\r\n if (typeof (value as any).stack === 'string') error.stack = (value as any).stack;\r\n return error;\r\n }\r\n return new Error(typeof value === 'string' ? value : `Non-Error thrown: ${safeString(value)}`);\r\n}\r\n\r\n/**\r\n * The `exception.*` attributes Zharp groups errors by. The stack keeps a `Type: message` first\r\n * line: Chrome's stacks have one, Firefox's and Safari's do not. When the page's scripts were\r\n * built with Zharp's source map tooling, `zharp.debug_ids` names the build of each file in the\r\n * stack, so the server can map it back to the original source.\r\n */\r\nexport function exceptionAttributes(error: Error, handled: boolean): Record<string, string> {\r\n const type = (error.name && error.name !== 'Error' ? error.name : error.constructor?.name) || 'Error';\r\n const message = error.message || '';\r\n const head = `${type}: ${message}`;\r\n let stack = typeof error.stack === 'string' ? error.stack : '';\r\n if (!stack.startsWith(error.name || type)) stack = stack ? `${head}\\n${stack}` : head;\r\n return {\r\n 'exception.type': type,\r\n 'exception.message': message,\r\n 'exception.stacktrace': stack,\r\n 'zharp.handled': handled ? 'true' : 'false',\r\n ...debugIdAttributes(stack),\r\n };\r\n}\r\n\r\nexport function watchErrors(report: (error: unknown, mechanism: string) => void): () => void {\r\n const onError = (event: ErrorEvent) =>\r\n safely(() => {\r\n // A failed <img> or <script> load also fires 'error' (on the element, captured here only\r\n // with capture listeners, which this is not) — only script errors reach this listener.\r\n if (event.error !== undefined && event.error !== null) report(event.error, 'onerror');\r\n else if (event.message) {\r\n // \"Script error.\" from a cross-origin script without CORS: no stack, but still an error.\r\n const error = new Error(event.message);\r\n error.stack = `Error: ${event.message}\\n at ${event.filename || '<anonymous>'}:${event.lineno || 0}:${event.colno || 0}`;\r\n report(error, 'onerror');\r\n }\r\n });\r\n const onRejection = (event: PromiseRejectionEvent) => safely(() => report(event.reason, 'onunhandledrejection'));\r\n window.addEventListener('error', onError);\r\n window.addEventListener('unhandledrejection', onRejection);\r\n return () => {\r\n window.removeEventListener('error', onError);\r\n window.removeEventListener('unhandledrejection', onRejection);\r\n };\r\n}\r\n\r\nconst CONSOLE_LEVELS = { debug: 'debug', log: 'info', info: 'info', warn: 'warn', error: 'error' } as const;\r\nexport type ConsoleMethod = keyof typeof CONSOLE_LEVELS;\r\n\r\n/** Copy console calls into logs. The console still prints as before. */\r\nexport function watchConsole(methods: ConsoleMethod[], log: (level: 'debug' | 'info' | 'warn' | 'error', message: string) => void): () => void {\r\n const originals: Partial<Record<ConsoleMethod, any>> = {};\r\n let inside = false;\r\n for (const method of methods) {\r\n const original = (console as any)[method];\r\n if (typeof original !== 'function' || original.__zharp) continue;\r\n originals[method] = original;\r\n const patched = function (this: unknown, ...args: unknown[]) {\r\n original.apply(this ?? console, args);\r\n if (inside) return;\r\n inside = true;\r\n safely(() => {\r\n const message = args.map((arg) => (arg instanceof Error ? arg.stack || String(arg) : safeString(arg))).join(' ');\r\n if (!message.startsWith('[Zharp]')) log(CONSOLE_LEVELS[method], message);\r\n });\r\n inside = false;\r\n };\r\n (patched as any).__zharp = true;\r\n (console as any)[method] = patched;\r\n }\r\n return () => Object.assign(console, originals);\r\n}\r\n","/**\r\n * Request and response bodies on HTTP spans (`captureBodies`), shared by @zharp/browser and\r\n * @zharp/node, and secrets in URLs.\r\n *\r\n * Off unless the application turns it on. When it is on, bodies are:\r\n * - redacted before they leave the process: field names stay, values under keys that look secret\r\n * (`password`, `token`, `authorization`, `card`, …) become `[Filtered]`, plus any keys the app adds\r\n * - kept readable: an inline image or other long base64 value becomes `[image/png · 24 KB]`, a\r\n * file in a form upload `[file photo.png · image/png · 240 KB]`, and a body that is not text\r\n * at all (an image, a PDF, an event stream) a one-line description of it\r\n * - capped (32 KB by default), with `http.*.body.truncated` set when they were cut\r\n *\r\n * They travel as the span attributes `http.request.body` and `http.response.body`, which the\r\n * trace view shows as a formatted payload.\r\n */\r\n\r\nexport type BodyMode = 'errors' | 'all';\r\n\r\nexport interface CaptureBodiesOptions {\r\n /** `errors` (default): only requests that failed (status 400 and above, or no response). `all`: every request. */\r\n mode?: BodyMode;\r\n /** Characters kept per body. Default 32768 (32 KB), at most 131072 (128 KB). */\r\n maxSize?: number;\r\n /**\r\n * More keys whose values are replaced with `[Filtered]`, on top of the built-in ones. A string\r\n * matches a key ignoring case, `-` and `_` (`\"accountNumber\"` also covers `account_number`); a\r\n * RegExp is tested against the key as it is.\r\n */\r\n redactKeys?: Array<string | RegExp>;\r\n /**\r\n * Which requests have their bodies captured. A bare host (`api.example.com`) matches that\r\n * host; a string with a scheme matches URLs starting with it; a RegExp is tested against the\r\n * full URL. Browser default: same-origin requests and `tracingOrigins` — your own APIs, never\r\n * third parties. Node default: every request.\r\n */\r\n urls?: Array<string | RegExp>;\r\n}\r\n\r\n/** `true` is `'errors'`. */\r\nexport type CaptureBodies = boolean | BodyMode | CaptureBodiesOptions;\r\n\r\nexport interface BodySettings {\r\n mode: BodyMode;\r\n maxSize: number;\r\n extraKeys: Array<string | RegExp>;\r\n urls?: Array<string | RegExp>;\r\n}\r\n\r\nexport const DEFAULT_MAX_BODY = 32 * 1024;\r\nexport const MAX_BODY = 128 * 1024;\r\nexport const FILTERED = '[Filtered]';\r\n\r\n/** Raw text read before shortening and capping: inline images shrink to a few words, so more is read than is kept. */\r\nexport function rawLimit(settings: BodySettings): number {\r\n return Math.max(64 * 1024, settings.maxSize * 2);\r\n}\r\n\r\nexport const BODY_ATTRIBUTES = {\r\n request: 'http.request.body',\r\n requestTruncated: 'http.request.body.truncated',\r\n requestType: 'http.request.header.content-type',\r\n response: 'http.response.body',\r\n responseTruncated: 'http.response.body.truncated',\r\n responseType: 'http.response.header.content-type',\r\n} as const;\r\n\r\n/** The setting as one shape, or null when bodies are off. `env` is `ZHARP_CAPTURE_BODIES` (`errors`, `all`, `off`). */\r\nexport function bodySettings(option: CaptureBodies | undefined, env?: string): BodySettings | null {\r\n let value: CaptureBodies | undefined = option;\r\n if (value === undefined && env) {\r\n const e = env.trim().toLowerCase();\r\n if (e === 'errors' || e === 'all') value = e;\r\n else if (/^(true|1|yes|on)$/.test(e)) value = true;\r\n }\r\n if (!value) return null;\r\n const o: CaptureBodiesOptions = value === true ? {} : typeof value === 'string' ? { mode: value } : value;\r\n const size = typeof o.maxSize === 'number' && o.maxSize > 0 ? Math.min(Math.floor(o.maxSize), MAX_BODY) : DEFAULT_MAX_BODY;\r\n return { mode: o.mode === 'all' ? 'all' : 'errors', maxSize: size, extraKeys: o.redactKeys ?? [], urls: o.urls };\r\n}\r\n\r\n/** Whether a request with this outcome has its bodies kept. `status` 0 means no response. */\r\nexport function wanted(settings: BodySettings, status: number): boolean {\r\n return settings.mode === 'all' || !status || status >= 400;\r\n}\r\n\r\n// ── content types ─────────────────────────────────────────────────────────────\r\n\r\nconst mime = (contentType: string | null | undefined) => (contentType ?? '').split(';')[0].trim().toLowerCase();\r\n\r\nexport function isEventStream(contentType: string | null | undefined): boolean {\r\n return mime(contentType) === 'text/event-stream';\r\n}\r\n\r\nexport function isMultipart(contentType: string | null | undefined): boolean {\r\n return mime(contentType) === 'multipart/form-data';\r\n}\r\n\r\n/** Whether a body of this type is text worth showing. An unknown type is given the benefit of the doubt. */\r\nexport function isTextual(contentType: string | null | undefined): boolean {\r\n const type = mime(contentType);\r\n if (!type) return true;\r\n if (type === 'text/event-stream') return false;\r\n return (\r\n type.startsWith('text/') ||\r\n type.endsWith('+json') ||\r\n type.endsWith('+xml') ||\r\n /^application\\/(json|xml|x-www-form-urlencoded|graphql|javascript|x-ndjson|ld\\+json)$/.test(type)\r\n );\r\n}\r\n\r\nfunction isForm(contentType: string | null | undefined): boolean {\r\n return mime(contentType) === 'application/x-www-form-urlencoded';\r\n}\r\n\r\n/** `240 KB`, `1.4 MB`. */\r\nexport function formatSize(bytes: number): string {\r\n if (bytes < 1024) return `${bytes} B`;\r\n if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;\r\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\r\n}\r\n\r\n/** How a file in a form upload is shown: `[file photo.png · image/png · 240 KB]`. */\r\nexport function fileLabel(name: string | undefined, type: string | undefined, size: number | undefined, partial = false): string {\r\n const parts = [`file ${name || 'blob'}`];\r\n if (type) parts.push(type);\r\n if (size !== undefined) parts.push(formatSize(size) + (partial ? '+' : ''));\r\n return `[${parts.join(' · ')}]`;\r\n}\r\n\r\n/** What a body that is not text says instead: `[binary · image/png · 24 KB]`, `[event stream]`. */\r\nexport function describeBody(contentType: string | null | undefined, size?: number, partial = false): string {\r\n if (isEventStream(contentType)) return '[event stream]';\r\n const parts = ['binary'];\r\n const type = mime(contentType);\r\n if (type) parts.push(type);\r\n if (size !== undefined && size > 0) parts.push(formatSize(size) + (partial ? '+' : ''));\r\n return `[${parts.join(' · ')}]`;\r\n}\r\n\r\n// ── redaction ─────────────────────────────────────────────────────────────────\r\n\r\n/** Built-in keys whose values never leave the process, compared without case, `-` or `_`. */\r\nconst CONTAINS = [\r\n 'password', 'passwd', 'passphrase', 'secret', 'token', 'apikey', 'accesskey', 'privatekey',\r\n 'authorization', 'cookie', 'creditcard', 'cardnumber', 'cvv', 'cvc', 'ssn', 'iban', 'sessionid',\r\n 'signature', 'credential',\r\n];\r\nconst EXACT = ['auth', 'pin', 'pwd', 'otp', 'card', 'pan', 'jwt', 'sid', 'codeverifier'];\r\n/** Also secret in a query string, where they are API keys and signed-URL signatures. */\r\nconst URL_EXACT = ['key', 'sig', 'code', 'state', 'session'];\r\n\r\nconst normalize = (key: string) => key.toLowerCase().replace(/[^a-z0-9]/g, '');\r\n\r\nexport function isSecretKey(key: string, extra: Array<string | RegExp> = []): boolean {\r\n const k = normalize(key);\r\n if (!k) return false;\r\n if (EXACT.includes(k) || CONTAINS.some((c) => k.includes(c))) return true;\r\n return extra.some((p) => (p instanceof RegExp ? p.test(key) : normalize(p) === k));\r\n}\r\n\r\nconst DATA_URI = /^data:([\\w.+-]+\\/[\\w.+-]+)?(?:;[\\w=.+-]+)*;base64,([A-Za-z0-9+/=\\s]*)$/;\r\nconst BASE64 = /^[A-Za-z0-9+/_-]{256,}={0,2}$/;\r\n\r\n/** A long base64 value as a short description; other strings as they are. */\r\nfunction shorten(value: string): string {\r\n if (value.length < 256) return value;\r\n const uri = DATA_URI.exec(value);\r\n if (uri) return `[${uri[1] || 'data'} · ${formatSize(Math.floor((uri[2].length * 3) / 4))}]`;\r\n if (BASE64.test(value) && /[0-9+/]/.test(value)) return `[base64 · ${formatSize(Math.floor((value.length * 3) / 4))}]`;\r\n return value;\r\n}\r\n\r\n/** Every value under `value` filtered, its keys kept: `{ brand: \"[Filtered]\", last4: \"[Filtered]\" }`. */\r\nfunction filterAll(value: unknown, depth: number): unknown {\r\n if (depth > 20) return FILTERED;\r\n if (value === null || value === '') return value;\r\n if (Array.isArray(value)) return value.map((v) => filterAll(v, depth + 1));\r\n if (typeof value === 'object') {\r\n const out: Record<string, unknown> = {};\r\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) out[k] = filterAll(v, depth + 1);\r\n return out;\r\n }\r\n return FILTERED;\r\n}\r\n\r\nexport function redactValue(value: unknown, extra: Array<string | RegExp>, depth = 0): unknown {\r\n if (typeof value === 'string') return shorten(value);\r\n if (depth > 20 || value === null || typeof value !== 'object') return value;\r\n if (Array.isArray(value)) return value.map((v) => redactValue(v, extra, depth + 1));\r\n const out: Record<string, unknown> = {};\r\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\r\n out[k] = isSecretKey(k, extra) ? filterAll(v, depth + 1) : redactValue(v, extra, depth + 1);\r\n }\r\n return out;\r\n}\r\n\r\n/**\r\n * Text that did not parse (cut-off JSON, a body that only looks like JSON): `\"key\": value`\r\n * pairs under secret keys are filtered where they appear, and long base64 runs shortened.\r\n */\r\nfunction redactLoose(text: string, extra: Array<string | RegExp>): string {\r\n // A quoted run of base64 (an inline image), possibly cut off before its closing quote.\r\n const runs = /\"((?:data:[\\w.+-]+\\/[\\w.+-]+(?:;[\\w=.+-]+)*;base64,)?[A-Za-z0-9+/_=-]{256,})(\"?)/g;\r\n return text\r\n .replace(runs, (match, run: string, close: string) => {\r\n const short = shorten(run);\r\n if (short === run) return match;\r\n return close ? `\"${short}\"` : `\"${short.slice(0, -1)}+]\"`;\r\n })\r\n .replace(\r\n /(\"([^\"\\\\]{1,100})\"\\s*:\\s*)(\"(?:[^\"\\\\]|\\\\.)*\"?|-?\\d[\\d.eE+-]*|true|false)/g,\r\n (match, prefix: string, key: string) => (isSecretKey(key, extra) ? `${prefix}\"${FILTERED}\"` : match),\r\n );\r\n}\r\n\r\nfunction redactForm(text: string, extra: Array<string | RegExp>): string {\r\n return text\r\n .split('&')\r\n .map((pair) => {\r\n const eq = pair.indexOf('=');\r\n if (eq < 0) return pair;\r\n let key = pair.slice(0, eq);\r\n try {\r\n key = decodeURIComponent(key.replace(/\\+/g, ' '));\r\n } catch {}\r\n if (isSecretKey(key, extra)) return `${pair.slice(0, eq)}=${FILTERED}`;\r\n const value = pair.slice(eq + 1);\r\n return value.length >= 256 ? `${pair.slice(0, eq)}=${shortenEncoded(value)}` : pair;\r\n })\r\n .join('&');\r\n}\r\n\r\nfunction shortenEncoded(value: string): string {\r\n try {\r\n const decoded = decodeURIComponent(value.replace(/\\+/g, ' '));\r\n const short = shorten(decoded);\r\n return short === decoded ? value : short;\r\n } catch {\r\n return value;\r\n }\r\n}\r\n\r\n// ── the attribute value ───────────────────────────────────────────────────────\r\n\r\n/**\r\n * A body as it is sent: redacted, then cut to `maxSize`. `cut` says the text was already cut\r\n * short where it was read. Null for an empty body. A `multipart/form-data` body is passed as the\r\n * JSON of its fields (files already described).\r\n */\r\nexport function formatBody(\r\n text: string | null | undefined,\r\n contentType: string | null | undefined,\r\n settings: BodySettings,\r\n cut = false,\r\n): { value: string; truncated: boolean } | null {\r\n if (text == null) return null;\r\n let body = String(text);\r\n if (!body.trim()) return null;\r\n\r\n if (isForm(contentType)) body = redactForm(body, settings.extraKeys);\r\n else {\r\n let parsed: unknown;\r\n let ok = false;\r\n const trimmed = body.trim();\r\n if (!cut && (trimmed[0] === '{' || trimmed[0] === '[')) {\r\n try {\r\n parsed = JSON.parse(trimmed);\r\n ok = true;\r\n } catch {}\r\n }\r\n body = ok ? JSON.stringify(redactValue(parsed, settings.extraKeys)) : redactLoose(body, settings.extraKeys);\r\n }\r\n\r\n const truncated = cut || body.length > settings.maxSize;\r\n return { value: body.length > settings.maxSize ? body.slice(0, settings.maxSize) : body, truncated };\r\n}\r\n\r\nfunction typeKey(side: 'request' | 'response') {\r\n return side === 'request' ? BODY_ATTRIBUTES.requestType : BODY_ATTRIBUTES.responseType;\r\n}\r\n\r\n/**\r\n * The span attributes for one side of a request (`request` or `response`). A body that is not\r\n * text is described (`size` in bytes when known) instead of left out.\r\n */\r\nexport function bodyAttributes(\r\n side: 'request' | 'response',\r\n text: string | null | undefined,\r\n contentType: string | null | undefined,\r\n settings: BodySettings,\r\n cut = false,\r\n): Record<string, unknown> {\r\n if (!isTextual(contentType) && !isMultipart(contentType)) return {};\r\n const formatted = formatBody(text, contentType, settings, cut);\r\n if (!formatted) return {};\r\n const attributes: Record<string, unknown> = { [BODY_ATTRIBUTES[side]]: formatted.value };\r\n if (formatted.truncated) attributes[side === 'request' ? BODY_ATTRIBUTES.requestTruncated : BODY_ATTRIBUTES.responseTruncated] = true;\r\n if (contentType) attributes[typeKey(side)] = contentType;\r\n return attributes;\r\n}\r\n\r\n/** The attributes for a body that is not text: what it was, not what it said. */\r\nexport function describedAttributes(side: 'request' | 'response', contentType: string | null | undefined, size?: number, partial = false): Record<string, unknown> {\r\n const attributes: Record<string, unknown> = { [BODY_ATTRIBUTES[side]]: describeBody(contentType, size, partial) };\r\n if (contentType) attributes[typeKey(side)] = contentType;\r\n return attributes;\r\n}\r\n\r\n// ── URLs ──────────────────────────────────────────────────────────────────────\r\n\r\n/**\r\n * A URL as it is recorded: query values under secret-looking keys (`token`, `key`, `sig`,\r\n * `password`, …) become `[Filtered]`, and `user:password@` is dropped. Anything that is not\r\n * a URL is returned as it is.\r\n */\r\nexport function redactUrl(url: string, extra: Array<string | RegExp> = []): string {\r\n if (!url) return url;\r\n let out = url.replace(/^([a-z][a-z0-9+.-]*:\\/\\/)[^/?#@]*@/i, '$1');\r\n const q = out.indexOf('?');\r\n if (q < 0) return out;\r\n const hash = out.indexOf('#', q);\r\n const query = out.slice(q + 1, hash < 0 ? undefined : hash);\r\n const redacted = redactQuery(query, extra);\r\n if (redacted !== query) out = out.slice(0, q + 1) + redacted + (hash < 0 ? '' : out.slice(hash));\r\n return out;\r\n}\r\n\r\n/** A query string (without `?`) with secret-looking values filtered. */\r\nexport function redactQuery(query: string, extra: Array<string | RegExp> = []): string {\r\n if (!query) return query;\r\n return query\r\n .split('&')\r\n .map((pair) => {\r\n const eq = pair.indexOf('=');\r\n if (eq < 0) return pair;\r\n let key = pair.slice(0, eq);\r\n try {\r\n key = decodeURIComponent(key.replace(/\\+/g, ' '));\r\n } catch {}\r\n const secret = isSecretKey(key, extra) || URL_EXACT.includes(normalize(key));\r\n return secret && eq < pair.length - 1 ? `${pair.slice(0, eq)}=${FILTERED}` : pair;\r\n })\r\n .join('&');\r\n}\r\n\r\n/**\r\n * Whether `url` matches one of `patterns`: a bare host (with or without a port) matches that\r\n * host; a string with a scheme matches as a prefix; a RegExp is tested against the URL.\r\n */\r\nexport function urlMatches(url: string, patterns: Array<string | RegExp>): boolean {\r\n let host = '';\r\n let hostname = '';\r\n try {\r\n const parsed = new URL(url);\r\n host = parsed.host;\r\n hostname = parsed.hostname;\r\n } catch {}\r\n return patterns.some((p) => {\r\n if (p instanceof RegExp) return p.test(url);\r\n if (!p) return false;\r\n if (p.includes('://')) return url.startsWith(p);\r\n return host === p || hostname === p;\r\n });\r\n}\r\n","/**\r\n * Request and response headers on HTTP spans, as OpenTelemetry names them\r\n * (`http.request.header.user-agent`, `http.response.header.content-type`), so a failed request\r\n * shows what was sent and what came back — and, as importantly, what wasn't sent (a request\r\n * with no `authorization` header). Every secret header is recorded as `[Filtered]`: it was\r\n * sent, its value never leaves the app. Same key rules as request bodies. Shared by the Node and\r\n * browser SDKs.\r\n */\r\nimport { FILTERED, isSecretKey } from './bodies';\r\n\r\nexport interface HeaderSettings {\r\n /** More header names to treat as secret (names or patterns). */\r\n redact: Array<string | RegExp>;\r\n}\r\n\r\n/** `captureHeaders`: on (the default), off, or on with more names to filter. */\r\nexport type CaptureHeaders = boolean | { redact?: Array<string | RegExp> };\r\n\r\n/** Headers that are secret whatever the key rules say. */\r\nconst SECRET = new Set(['authorization', 'proxy-authorization', 'cookie', 'set-cookie', 'x-api-key', 'x-auth-token', 'x-csrf-token', 'x-xsrf-token']);\r\n/** Per side, so a request stuffed with headers can't fill the span. */\r\nconst MAX_HEADERS = 40;\r\nconst MAX_VALUE = 512;\r\n\r\n/** Header settings from the option (and ZHARP_CAPTURE_HEADERS where there is an environment); null when off. */\r\nexport function headerSettings(option: CaptureHeaders | undefined, env?: string): HeaderSettings | null {\r\n if (option === false || env === 'false' || env === '0') return null;\r\n return { redact: typeof option === 'object' && option?.redact ? option.redact : [] };\r\n}\r\n\r\n/** A header's value as it is recorded: secrets filtered, long values cut, repeats joined. */\r\nfunction shown(name: string, value: unknown, settings: HeaderSettings): string | null {\r\n if (value === undefined || value === null) return null;\r\n if (SECRET.has(name) || isSecretKey(name, settings.redact)) return FILTERED;\r\n const text = Array.isArray(value) ? value.join(', ') : String(value);\r\n return text.length > MAX_VALUE ? `${text.slice(0, MAX_VALUE)}…` : text;\r\n}\r\n\r\n/** `http.<side>.header.<name>` attributes for a set of headers (a record, or name/value pairs). */\r\nexport function headerAttributes(\r\n side: 'request' | 'response',\r\n headers: Record<string, unknown> | Iterable<[string, string]> | null | undefined,\r\n settings: HeaderSettings,\r\n): Record<string, string> {\r\n const out: Record<string, string> = {};\r\n if (!headers) return out;\r\n // A Headers object or a list of pairs is iterable; Node's header objects are plain records.\r\n const entries: Array<[string, unknown]> = typeof (headers as Iterable<unknown>)[Symbol.iterator] === 'function'\r\n ? [...(headers as Iterable<[string, string]>)]\r\n : Object.entries(headers as Record<string, unknown>);\r\n let count = 0;\r\n for (const [rawName, value] of entries) {\r\n if (count >= MAX_HEADERS) break;\r\n const name = rawName.toLowerCase();\r\n const text = shown(name, value, settings);\r\n if (text === null) continue;\r\n out[`http.${side}.header.${name}`] = text;\r\n count++;\r\n }\r\n return out;\r\n}\r\n\r\n/** XMLHttpRequest's getAllResponseHeaders() text as name/value pairs. */\r\nexport function parseHeaderBlock(text: string | null | undefined): Array<[string, string]> {\r\n const out: Array<[string, string]> = [];\r\n for (const line of (text ?? '').split(/\\r?\\n/)) {\r\n const at = line.indexOf(':');\r\n if (at > 0) out.push([line.slice(0, at).trim(), line.slice(at + 1).trim()]);\r\n }\r\n return out;\r\n}\r\n","/**\r\n * Getting telemetry to Zharp from a page.\r\n *\r\n * Records are queued and sent in batches every few seconds (sooner when a batch fills), gzipped\r\n * where the browser can, and retried with backoff when the server or the network asks for it.\r\n * The queue is capped — when it is full the oldest go — so a page that is offline for an hour\r\n * does not grow without bound.\r\n *\r\n * When the page is hidden or closed everything left goes out at once with `keepalive`, which\r\n * lets the request outlive the page. (`sendBeacon` would too, but cannot send the key header.)\r\n */\r\nimport { byteLength } from './util';\r\n\r\nexport type Signal = 'traces' | 'logs' | 'replays';\r\n\r\nconst BATCH_SIZE = 100;\r\nconst FLUSH_MS = 5_000;\r\nconst MAX_QUEUE = 1_000;\r\nconst MAX_BACKOFF_MS = 5 * 60_000;\r\n/** A normal request carries at most this much; the server takes 10 MB, but one huge upload holds everything behind it. */\r\nexport const MAX_BODY_BYTES = 1_000_000;\r\n/** Browsers allow 64 KB of keepalive bodies in flight per page. */\r\nexport const MAX_KEEPALIVE_BYTES = 60_000;\r\n\r\nexport interface Endpoint {\r\n url: string;\r\n key: string;\r\n /** The page's fetch as it was before instrumentation, so the SDK never traces itself. */\r\n fetch: typeof fetch;\r\n /** What the warning for a rejected key tells the developer to check. Default: the page's init call. */\r\n rejectedHint?: string;\r\n /**\r\n * False when the body doesn't leave the machine as it is (@zharp/electron hands it to the main\r\n * process, which compresses and sends it): no gzip here. Default true.\r\n */\r\n compress?: boolean;\r\n}\r\n\r\n/** Shared by every sender on a page: one rejected key stops all of them, with one warning. */\r\nlet keyRejected = false;\r\n\r\n/**\r\n * POST one body. Resolves to the HTTP status, or 0 when the request never completed.\r\n */\r\nexport async function post(endpoint: Endpoint, signal: Signal, body: string, keepalive = false): Promise<number> {\r\n if (keyRejected) return 401;\r\n const headers: Record<string, string> = {\r\n 'Content-Type': 'application/json',\r\n Authorization: `Bearer ${endpoint.key}`,\r\n };\r\n let payload: BodyInit = body;\r\n // gzip when it pays and the browser can; a keepalive request is sent as the page goes away,\r\n // with no time for an async compression step.\r\n if (!keepalive && endpoint.compress !== false && body.length > 2_048 && typeof CompressionStream !== 'undefined') {\r\n try {\r\n payload = await new Response(new Blob([body]).stream().pipeThrough(new CompressionStream('gzip'))).arrayBuffer();\r\n headers['Content-Encoding'] = 'gzip';\r\n } catch {\r\n payload = body;\r\n }\r\n }\r\n try {\r\n const response = await endpoint.fetch.call(globalThis, `${endpoint.url}/v1/${signal}`, {\r\n method: 'POST',\r\n headers,\r\n body: payload,\r\n keepalive,\r\n credentials: 'omit',\r\n });\r\n if (response.status === 401 || response.status === 403) {\r\n if (!keyRejected) {\r\n keyRejected = true;\r\n console.warn(`[Zharp] The key was rejected (HTTP ${response.status}); ${endpoint.rejectedHint ?? \"nothing more will be sent from this page. Check Zharp.init({ key }) and the app's allowed origins.\"}`);\r\n }\r\n }\r\n return response.status;\r\n } catch {\r\n return 0;\r\n }\r\n}\r\n\r\n/** Bytes of our keepalive requests still in flight: the browser refuses new ones past its budget. */\r\nlet keepaliveInFlight = 0;\r\n\r\n/**\r\n * Send one body as the page is hidden or closed, exactly once.\r\n *\r\n * Within the keepalive budget the request outlives the page — and is never sent again: when the\r\n * page goes, the browser still delivers it but tells the page it failed (`net::ERR_ABORTED`), so\r\n * resending on failure stored everything twice. Past the budget, an ordinary request may still\r\n * finish before the page is gone.\r\n */\r\nexport function sendOnHide(endpoint: Endpoint, signal: Signal, body: string): void {\r\n const size = byteLength(body);\r\n if (keepaliveInFlight + size <= MAX_KEEPALIVE_BYTES) {\r\n keepaliveInFlight += size;\r\n void post(endpoint, signal, body, true).finally(() => {\r\n keepaliveInFlight -= size;\r\n });\r\n } else {\r\n void post(endpoint, signal, body);\r\n }\r\n}\r\n\r\n/** 429, 5xx and network failures are worth another try; anything else will fail the same way again. */\r\nexport const retryable = (status: number) => status === 0 || status === 429 || status >= 500;\r\n\r\n/**\r\n * Cut `items` into JSON bodies of at most `limit` bytes. An item too large for any body still\r\n * gets one of its own: whether it goes through is for the network to decide.\r\n */\r\nexport function split<T>(items: T[], limit: number, wrap: (group: T[]) => unknown): Array<{ body: string; items: T[] }> {\r\n const overhead = byteLength(JSON.stringify(wrap([])));\r\n const out: Array<{ body: string; items: T[] }> = [];\r\n let group: T[] = [];\r\n let size = overhead;\r\n for (const item of items) {\r\n const itemSize = byteLength(JSON.stringify(item)) + 1;\r\n if (group.length && size + itemSize > limit) {\r\n out.push({ body: JSON.stringify(wrap(group)), items: group });\r\n group = [];\r\n size = overhead;\r\n }\r\n group.push(item);\r\n size += itemSize;\r\n }\r\n if (group.length) out.push({ body: JSON.stringify(wrap(group)), items: group });\r\n return out;\r\n}\r\n\r\n/** A queue of OTLP records of one signal, and the timer that sends them. */\r\nexport class Exporter<T> {\r\n private queue: T[] = [];\r\n private timer: ReturnType<typeof setTimeout> | null = null;\r\n private sending: Promise<void> | null = null;\r\n private failures = 0;\r\n\r\n constructor(\r\n private readonly endpoint: Endpoint,\r\n private readonly signal: 'traces' | 'logs',\r\n /** Wraps records in the export request: resource, scope, and the signal's envelope. */\r\n private readonly wrap: (records: T[]) => unknown,\r\n /**\r\n * Send on a timer. Where nothing runs between requests (a Cloudflare Worker) there are no\r\n * timers: the caller flushes at the end of each request, and what failed waits for the next.\r\n */\r\n private readonly timers = true,\r\n ) {}\r\n\r\n add(record: T): void {\r\n this.queue.push(record);\r\n if (this.queue.length > MAX_QUEUE) this.queue.splice(0, this.queue.length - MAX_QUEUE);\r\n if (this.queue.length >= BATCH_SIZE && !this.failures) this.flush();\r\n else this.schedule(FLUSH_MS);\r\n }\r\n\r\n /** Send everything queued. One send at a time; a call during one waits and then sends what is left. */\r\n async flush(): Promise<void> {\r\n while (this.sending) await this.sending;\r\n if (!this.queue.length) return;\r\n this.sending = this.send().finally(() => (this.sending = null));\r\n return this.sending;\r\n }\r\n\r\n /** The page is going away: everything left, now, with keepalive. Nothing to wait for. */\r\n flushOnHide(): void {\r\n if (!this.queue.length) return;\r\n const records = this.queue;\r\n this.queue = [];\r\n for (const { body } of split(records, MAX_KEEPALIVE_BYTES, this.wrap)) sendOnHide(this.endpoint, this.signal, body);\r\n }\r\n\r\n private schedule(ms: number): void {\r\n if (this.timer || !this.timers) return;\r\n this.timer = setTimeout(() => {\r\n this.timer = null;\r\n this.flush();\r\n }, ms);\r\n }\r\n\r\n private async send(): Promise<void> {\r\n if (this.timer) {\r\n clearTimeout(this.timer);\r\n this.timer = null;\r\n }\r\n const records = this.queue;\r\n this.queue = [];\r\n const batches = split(records, MAX_BODY_BYTES, this.wrap);\r\n for (let i = 0; i < batches.length; i++) {\r\n const status = await post(this.endpoint, this.signal, batches[i].body);\r\n if (retryable(status)) {\r\n // This batch and the ones after it go back to the front, oldest first, and wait.\r\n const unsent = batches.slice(i).flatMap((b) => b.items);\r\n this.queue = unsent.concat(this.queue).slice(-MAX_QUEUE);\r\n this.failures++;\r\n this.schedule(Math.min(FLUSH_MS * 2 ** this.failures, MAX_BACKOFF_MS));\r\n return;\r\n }\r\n // Delivered, or refused for good (400, 401/403): either way it is done.\r\n this.failures = 0;\r\n }\r\n if (this.queue.length) this.schedule(FLUSH_MS);\r\n }\r\n}\r\n","/** Sent as telemetry.sdk.version. Kept in step with package.json. */\r\nexport const VERSION = '0.1.0';\r\n","/**\r\n * Settings from code and from the Worker's environment. Code wins; then the `ZHARP_*` vars and\r\n * secrets; then what Cloudflare itself says about the deployment.\r\n */\r\nimport type { CaptureHeaders } from '@zharp/internal/headers';\r\nimport type { ZharpCloudflareOptions, ZharpConfig } from './types';\r\nimport { VERSION } from './version';\r\n\r\nexport const DEFAULT_ENDPOINT = 'https://api.zharp.io/api/v1/otlp';\r\n\r\nexport interface Settings {\r\n key: string;\r\n endpoint: string;\r\n sampleRate: number;\r\n tracing: boolean;\r\n logs: boolean;\r\n captureHeaders: CaptureHeaders | undefined;\r\n captureQueryErrors: boolean;\r\n ignoreUrls: Array<string | RegExp>;\r\n resource: Record<string, unknown>;\r\n}\r\n\r\nconst text = (value: unknown): string | undefined => (typeof value === 'string' && value.trim() ? value.trim() : undefined);\r\nconst flag = (value: unknown): boolean | undefined => {\r\n if (typeof value === 'boolean') return value;\r\n const t = text(value)?.toLowerCase();\r\n if (!t) return undefined;\r\n if (/^(true|1|yes|on)$/.test(t)) return true;\r\n if (/^(false|0|no|off)$/.test(t)) return false;\r\n return undefined;\r\n};\r\n\r\n/** `CF_VERSION_METADATA` (or any binding shaped like it): the deployed version's id and tag. */\r\nfunction versionMetadata(env: Record<string, unknown>): { id?: string; tag?: string } {\r\n const named = env.CF_VERSION_METADATA as { id?: unknown; tag?: unknown } | undefined;\r\n if (named && typeof named === 'object') return { id: text(named.id), tag: text(named.tag) };\r\n return {};\r\n}\r\n\r\n/**\r\n * The settings, or null when there is no key or `ZHARP_DISABLED` is set.\r\n * @param defaults - What the entry point stands for: a Worker or Pages.\r\n */\r\nexport function resolveSettings(envInput: unknown, config: ZharpConfig | undefined, defaults: { service: string; platform: string }): Settings | null {\r\n const env = (envInput && typeof envInput === 'object' ? envInput : {}) as Record<string, unknown>;\r\n const options: ZharpCloudflareOptions = (typeof config === 'function' ? config(env) : config) ?? {};\r\n if (flag(env.ZHARP_DISABLED)) return null;\r\n const key = text(options.key) ?? text(env.ZHARP_KEY) ?? text(env.ZHARP_API_KEY);\r\n if (!key) return null;\r\n\r\n const version = versionMetadata(env);\r\n const release = text(options.release) ?? text(env.ZHARP_RELEASE) ?? version.id;\r\n const rate = typeof options.sampleRate === 'number' ? options.sampleRate : Number(text(env.ZHARP_SAMPLE_RATE) ?? 1);\r\n const headersEnv = flag(env.ZHARP_CAPTURE_HEADERS);\r\n\r\n return {\r\n key,\r\n endpoint: (text(options.endpoint) ?? text(env.ZHARP_ENDPOINT) ?? DEFAULT_ENDPOINT).replace(/\\/+$/, ''),\r\n sampleRate: Number.isFinite(rate) ? Math.min(1, Math.max(0, rate)) : 1,\r\n tracing: options.tracing ?? flag(env.ZHARP_TRACING) ?? true,\r\n logs: options.logs ?? flag(env.ZHARP_LOGS) ?? false,\r\n captureHeaders: options.captureHeaders ?? (headersEnv === false ? false : undefined),\r\n captureQueryErrors: options.captureQueryErrors ?? true,\r\n ignoreUrls: options.ignoreUrls ?? [],\r\n resource: {\r\n 'service.name': text(options.service) ?? text(env.ZHARP_SERVICE) ?? defaults.service,\r\n 'service.version': release,\r\n 'deployment.environment.name': text(options.environment) ?? text(env.ZHARP_ENVIRONMENT) ?? text(env.ZHARP_ENV),\r\n 'telemetry.sdk.name': 'zharp',\r\n 'telemetry.sdk.language': 'webjs',\r\n 'telemetry.sdk.version': VERSION,\r\n 'cloud.provider': 'cloudflare',\r\n 'cloud.platform': defaults.platform,\r\n 'faas.version': version.id,\r\n 'cloudflare.version.tag': version.tag,\r\n },\r\n };\r\n}\r\n","/**\r\n * Spans in a Worker, on OpenTelemetry's API.\r\n *\r\n * A Worker serves many requests at once in one isolate, so \"the current span\" is carried by\r\n * AsyncLocalStorage (from `nodejs_compat`) across every await of the request that started it.\r\n * The context manager, tracer and `traceparent` propagator here are registered with\r\n * `@opentelemetry/api`, so a library that makes its own OpenTelemetry spans joins the request's\r\n * trace — without OpenTelemetry's SDK packages, which are too large for a Worker.\r\n */\r\nimport { AsyncLocalStorage } from 'node:async_hooks';\r\nimport {\r\n context as otelContext,\r\n createContextKey,\r\n propagation,\r\n ROOT_CONTEXT,\r\n SpanKind,\r\n SpanStatusCode,\r\n trace,\r\n TraceFlags,\r\n type Attributes as OtelAttributes,\r\n type Context,\r\n type ContextManager,\r\n type Exception,\r\n type Link,\r\n type Span as OtelSpan,\r\n type SpanContext,\r\n type SpanOptions,\r\n type SpanStatus,\r\n type TextMapPropagator,\r\n type TimeInput,\r\n type Tracer as OtelTracer,\r\n type TracerProvider,\r\n} from '@opentelemetry/api';\r\nimport { keyValues, newSpanId, newTraceId, now, toNanos } from '../../browser/src/util';\r\nimport type { RequestState } from './state';\r\n\r\nexport { SpanKind, SpanStatusCode };\r\n\r\n// ── context ─────────────────────────────────────────────────────────────\r\n\r\nclass AlsContextManager implements ContextManager {\r\n private readonly als = new AsyncLocalStorage<Context>();\r\n\r\n active(): Context {\r\n return this.als.getStore() ?? ROOT_CONTEXT;\r\n }\r\n\r\n with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(ctx: Context, fn: F, thisArg?: ThisParameterType<F>, ...args: A): ReturnType<F> {\r\n return this.als.run(ctx, () => fn.apply(thisArg, args));\r\n }\r\n\r\n bind<T>(ctx: Context, target: T): T {\r\n if (typeof target !== 'function') return target;\r\n const manager = this;\r\n return function (this: unknown, ...args: unknown[]) {\r\n return manager.with(ctx, () => (target as Function).apply(this, args));\r\n } as T;\r\n }\r\n\r\n enable(): this {\r\n return this;\r\n }\r\n\r\n disable(): this {\r\n return this;\r\n }\r\n}\r\n\r\nexport const contextManager = new AlsContextManager();\r\n\r\n/** The request a context belongs to: its tags, user and what is still to be reported. */\r\nconst REQUEST = createContextKey('zharp.cloudflare.request');\r\n\r\nexport const activeContext = (): Context => contextManager.active();\r\nexport const requestOf = (ctx: Context = activeContext()): RequestState | undefined => ctx.getValue(REQUEST) as RequestState | undefined;\r\nexport const withRequest = (ctx: Context, state: RequestState): Context => ctx.setValue(REQUEST, state);\r\nexport const activeSpan = (): ZharpSpan | undefined => {\r\n const span = trace.getSpan(activeContext());\r\n return span instanceof ZharpSpan ? span : undefined;\r\n};\r\n\r\n// ── spans ───────────────────────────────────────────────────────────────\r\n\r\n/** Where finished spans go. */\r\nexport interface SpanSink {\r\n sampleRate: number;\r\n export(span: ZharpSpan): void;\r\n}\r\n\r\nlet sink: SpanSink | null = null;\r\nexport const setSpanSink = (value: SpanSink) => {\r\n sink = value;\r\n};\r\n\r\n/** OpenTelemetry's span kinds as OTLP numbers them (one more than the API's enum). */\r\nconst otlpKind = (kind: SpanKind) => kind + 1;\r\n\r\nconst MAX_EVENTS = 64;\r\n\r\nexport class ZharpSpan implements OtelSpan {\r\n readonly traceId: string;\r\n readonly spanId = newSpanId();\r\n readonly parentSpanId?: string;\r\n readonly sampled: boolean;\r\n readonly attributes: Record<string, unknown> = {};\r\n readonly startTime: number;\r\n /** The request this span was started in, for its tags and user when it is sent. */\r\n readonly request: RequestState | undefined;\r\n private readonly events: Array<{ name: string; time: number; attributes?: OtelAttributes }> = [];\r\n private readonly links: Link[] = [];\r\n private status: SpanStatus = { code: SpanStatusCode.UNSET };\r\n private endTime = 0;\r\n\r\n constructor(\r\n public name: string,\r\n readonly kind: SpanKind,\r\n parent: SpanContext | undefined,\r\n request: RequestState | undefined,\r\n attributes?: OtelAttributes,\r\n startTime?: TimeInput,\r\n links?: Link[],\r\n ) {\r\n const valid = parent && trace.isSpanContextValid(parent);\r\n this.traceId = valid ? parent!.traceId : newTraceId();\r\n this.parentSpanId = valid ? parent!.spanId : undefined;\r\n this.sampled = valid ? (parent!.traceFlags & TraceFlags.SAMPLED) === TraceFlags.SAMPLED : Math.random() < (sink?.sampleRate ?? 1);\r\n this.startTime = startTime !== undefined ? timeOf(startTime) : now();\r\n this.request = request;\r\n if (attributes) Object.assign(this.attributes, attributes);\r\n if (links) this.links.push(...links);\r\n }\r\n\r\n get ended(): boolean {\r\n return this.endTime !== 0;\r\n }\r\n\r\n spanContext(): SpanContext {\r\n return { traceId: this.traceId, spanId: this.spanId, traceFlags: this.sampled ? TraceFlags.SAMPLED : TraceFlags.NONE };\r\n }\r\n\r\n setAttribute(key: string, value: unknown): this {\r\n if (!this.endTime && value !== undefined) this.attributes[key] = value;\r\n return this;\r\n }\r\n\r\n setAttributes(attributes: Record<string, unknown>): this {\r\n for (const key in attributes) this.setAttribute(key, attributes[key]);\r\n return this;\r\n }\r\n\r\n addEvent(name: string, attributesOrTime?: OtelAttributes | TimeInput, time?: TimeInput): this {\r\n if (this.endTime || this.events.length >= MAX_EVENTS) return this;\r\n // Exceptions are reported as errors of their own (one per error); an event would count it twice.\r\n if (name === 'exception') return this;\r\n const isTime = typeof attributesOrTime === 'number' || attributesOrTime instanceof Date || Array.isArray(attributesOrTime);\r\n this.events.push({\r\n name,\r\n time: timeOf(isTime ? (attributesOrTime as TimeInput) : time ?? now()),\r\n attributes: isTime ? undefined : (attributesOrTime as OtelAttributes | undefined),\r\n });\r\n return this;\r\n }\r\n\r\n addLink(link: Link): this {\r\n this.links.push(link);\r\n return this;\r\n }\r\n\r\n addLinks(links: Link[]): this {\r\n this.links.push(...links);\r\n return this;\r\n }\r\n\r\n setStatus(status: SpanStatus): this {\r\n if (!this.endTime) this.status = status;\r\n return this;\r\n }\r\n\r\n updateName(name: string): this {\r\n if (!this.endTime) this.name = name;\r\n return this;\r\n }\r\n\r\n isRecording(): boolean {\r\n return !this.endTime;\r\n }\r\n\r\n /**\r\n * Another library recorded an exception on its span. It becomes an error of its own, once —\r\n * the same way the wrapper reports what a handler threw.\r\n */\r\n recordException(exception: Exception): void {\r\n onRecordedException?.(exception, this);\r\n }\r\n\r\n end(endTime?: TimeInput): void {\r\n if (this.endTime) return;\r\n this.endTime = Math.max(endTime !== undefined ? timeOf(endTime) : now(), this.startTime);\r\n if (this.sampled) sink?.export(this);\r\n }\r\n\r\n /** As an OTLP/JSON span. `context` is the request's tags and user. */\r\n toOtlp(context: Record<string, unknown>): Record<string, unknown> {\r\n return {\r\n traceId: this.traceId,\r\n spanId: this.spanId,\r\n parentSpanId: this.parentSpanId,\r\n name: this.name,\r\n kind: otlpKind(this.kind),\r\n startTimeUnixNano: toNanos(this.startTime),\r\n endTimeUnixNano: toNanos(this.endTime),\r\n attributes: keyValues({ ...context, ...this.attributes }),\r\n events: this.events.length\r\n ? this.events.map((event) => ({ name: event.name, timeUnixNano: toNanos(event.time), attributes: keyValues(event.attributes ?? {}) }))\r\n : undefined,\r\n links: this.links.length\r\n ? this.links.map((link) => ({ traceId: link.context.traceId, spanId: link.context.spanId, attributes: keyValues(link.attributes ?? {}) }))\r\n : undefined,\r\n status: this.status.message ? { code: this.status.code, message: this.status.message } : { code: this.status.code },\r\n };\r\n }\r\n}\r\n\r\nlet onRecordedException: ((exception: Exception, span: ZharpSpan) => void) | null = null;\r\nexport const setRecordedExceptionHandler = (handler: (exception: Exception, span: ZharpSpan) => void) => {\r\n onRecordedException = handler;\r\n};\r\n\r\nfunction timeOf(input: TimeInput): number {\r\n if (typeof input === 'number') {\r\n // performance.now()-style values are small; epoch milliseconds are not.\r\n return input < 1e12 ? (typeof performance !== 'undefined' && performance.timeOrigin ? performance.timeOrigin + input : Date.now()) : input;\r\n }\r\n if (input instanceof Date) return input.getTime();\r\n if (Array.isArray(input)) return input[0] * 1e3 + input[1] / 1e6;\r\n return now();\r\n}\r\n\r\n/** Start a span under the active one (or `parent`), in the active request. */\r\nexport function startSpan(name: string, options: SpanOptions = {}, ctx: Context = activeContext()): ZharpSpan {\r\n const parent = options.root ? undefined : trace.getSpanContext(ctx);\r\n return new ZharpSpan(name, options.kind ?? SpanKind.INTERNAL, parent, requestOf(ctx), options.attributes, options.startTime, options.links);\r\n}\r\n\r\n/** Run `fn` with `span` active. */\r\nexport function withSpan<T>(span: OtelSpan, fn: () => T, ctx: Context = activeContext()): T {\r\n return contextManager.with(trace.setSpan(ctx, span), fn);\r\n}\r\n\r\nclass ZharpTracer implements OtelTracer {\r\n startSpan(name: string, options?: SpanOptions, ctx?: Context): OtelSpan {\r\n return startSpan(name, options, ctx ?? activeContext());\r\n }\r\n\r\n startActiveSpan<F extends (span: OtelSpan) => unknown>(name: string, ...args: unknown[]): ReturnType<F> {\r\n const fn = args[args.length - 1] as F;\r\n const options = (args.length > 1 ? args[0] : undefined) as SpanOptions | undefined;\r\n const ctx = (args.length > 2 ? args[1] : undefined) as Context | undefined;\r\n const parentCtx = ctx ?? activeContext();\r\n const span = startSpan(name, options, parentCtx);\r\n return contextManager.with(trace.setSpan(parentCtx, span), () => fn(span)) as ReturnType<F>;\r\n }\r\n}\r\n\r\nconst tracer = new ZharpTracer();\r\nconst provider: TracerProvider = { getTracer: () => tracer };\r\n\r\n// ── traceparent ─────────────────────────────────────────────────────────\r\n\r\nconst TRACEPARENT = /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;\r\n\r\n/** A W3C `traceparent` header as a remote span context, or undefined. */\r\nexport function parseTraceparent(header: string | null | undefined): SpanContext | undefined {\r\n const match = header ? TRACEPARENT.exec(header.trim().toLowerCase()) : null;\r\n if (!match || /^0+$/.test(match[1]) || /^0+$/.test(match[2])) return undefined;\r\n return { traceId: match[1], spanId: match[2], traceFlags: parseInt(match[3], 16) & 1, isRemote: true };\r\n}\r\n\r\nexport function formatTraceparent(span: SpanContext): string {\r\n return `00-${span.traceId}-${span.spanId}-${span.traceFlags & TraceFlags.SAMPLED ? '01' : '00'}`;\r\n}\r\n\r\nconst propagator: TextMapPropagator = {\r\n inject(ctx, carrier, setter) {\r\n const span = trace.getSpanContext(ctx);\r\n if (span && trace.isSpanContextValid(span)) setter.set(carrier, 'traceparent', formatTraceparent(span));\r\n },\r\n extract(ctx, carrier, getter) {\r\n const raw = getter.get(carrier, 'traceparent');\r\n const parent = parseTraceparent(Array.isArray(raw) ? raw[0] : raw);\r\n return parent ? trace.setSpanContext(ctx, parent) : ctx;\r\n },\r\n fields: () => ['traceparent'],\r\n};\r\n\r\nlet registered = false;\r\n\r\n/**\r\n * Make this tracer the one `@opentelemetry/api` hands out. If another provider is registered\r\n * already, it keeps its place: Zharp's own spans don't go through the API.\r\n */\r\nexport function registerOpenTelemetry(): void {\r\n if (registered) return;\r\n registered = true;\r\n try {\r\n otelContext.setGlobalContextManager(contextManager);\r\n trace.setGlobalTracerProvider(provider);\r\n propagation.setGlobalPropagator(propagator);\r\n } catch {\r\n // Another copy registered first; ours still works for Zharp's own spans.\r\n }\r\n}\r\n","/**\r\n * D1: a CLIENT span per query (`prepare().first()/all()/run()/raw()`, `batch()`, `exec()`), and\r\n * failed queries as errors that say where they came from.\r\n *\r\n * D1's error is made when the database's answer comes back, so its stack is D1's own code, not\r\n * the line of the app that ran the query. That line is taken when the query starts, and kept:\r\n * a failure is reported with it as its stack, the SQL, and SQLite's code — once. If the error\r\n * then reaches the handler (it threw it on), it is reported there as unhandled with these\r\n * details; if the app caught it, it is reported as handled when the request ends.\r\n */\r\nimport { debugIdAttributes } from '@zharp/internal/debug-ids';\r\nimport { safely } from '../../browser/src/util';\r\nimport { activeContext, requestOf, SpanKind, SpanStatusCode, startSpan, type ZharpSpan } from './tracing';\r\nimport type { RequestState } from './state';\r\n\r\nexport interface QueryFailure {\r\n error: unknown;\r\n span: ZharpSpan;\r\n claimed: boolean;\r\n attributes: Record<string, string>;\r\n exception(handled: boolean): Record<string, string>;\r\n}\r\n\r\nconst failures = new WeakMap<object, QueryFailure>();\r\n\r\n/** The failed query `value` came from, marked as reported. */\r\nexport function claimQueryFailure(value: unknown): QueryFailure | undefined {\r\n const failure = value && typeof value === 'object' ? failures.get(value) : undefined;\r\n if (failure) failure.claimed = true;\r\n return failure;\r\n}\r\n\r\nexport function unclaimedQueryFailures(state: RequestState): QueryFailure[] {\r\n return state.queryFailures.filter((failure) => !failure.claimed);\r\n}\r\n\r\n/** The frames of the app's call into `boundary`, innermost first. */\r\nfunction callSite(boundary: Function): string[] {\r\n const holder: { stack?: string } = {};\r\n const limit = Error.stackTraceLimit;\r\n try {\r\n Error.stackTraceLimit = 40;\r\n (Error as any).captureStackTrace?.(holder, boundary);\r\n } finally {\r\n Error.stackTraceLimit = limit;\r\n }\r\n return (holder.stack ?? '').split('\\n').slice(1).filter((line) => /^\\s+at /.test(line));\r\n}\r\n\r\n/** SQLite's result code at the end of a D1 message (\"…: SQLITE_CONSTRAINT\"), if any. */\r\nexport function sqliteCode(message: string): string | undefined {\r\n return /\\b(SQLITE_[A-Z_]+)\\b/.exec(message)?.[1];\r\n}\r\n\r\nconst operationOf = (sql: string) => /^\\s*(\\w+)/.exec(sql)?.[1]?.toUpperCase() ?? 'QUERY';\r\nconst MAX_SQL = 4000;\r\n\r\nfunction queryFailure(error: unknown, span: ZharpSpan, sql: string, database: string, frames: string[]): QueryFailure {\r\n const message = (error as Error)?.message ?? String(error);\r\n const code = sqliteCode(message);\r\n const type = 'D1Error';\r\n const attributes: Record<string, string> = {\r\n 'zharp.mechanism': 'db',\r\n 'db.system': 'sqlite',\r\n 'db.statement': sql.slice(0, MAX_SQL),\r\n 'db.name': database,\r\n ...(code ? { 'db.error.code': code } : {}),\r\n };\r\n return {\r\n error,\r\n span,\r\n claimed: false,\r\n attributes,\r\n exception(handled) {\r\n const stack = [`${type}: ${message}`, ...frames].join('\\n');\r\n return {\r\n 'exception.type': type,\r\n 'exception.message': message,\r\n 'exception.stacktrace': stack,\r\n 'zharp.handled': handled ? 'true' : 'false',\r\n ...debugIdAttributes(stack),\r\n };\r\n },\r\n };\r\n}\r\n\r\ninterface Query {\r\n database: string;\r\n sql: string;\r\n operation: string;\r\n frames: string[];\r\n captureErrors: boolean;\r\n}\r\n\r\n/** Run one query in its span. */\r\nasync function traced<T>(query: Query, run: () => Promise<T>): Promise<T> {\r\n const ctx = activeContext();\r\n const state = requestOf(ctx);\r\n if (!state) return run();\r\n const span = startSpan(`${query.operation} ${query.database}`, {\r\n kind: SpanKind.CLIENT,\r\n attributes: {\r\n 'db.system': 'sqlite',\r\n 'db.system.name': 'sqlite',\r\n 'db.namespace': query.database,\r\n 'db.operation.name': query.operation,\r\n 'db.statement': query.sql.slice(0, MAX_SQL),\r\n 'db.query.text': query.sql.slice(0, MAX_SQL),\r\n 'cloudflare.binding.type': 'd1',\r\n },\r\n }, ctx);\r\n try {\r\n const result = await run();\r\n safely(() => {\r\n const meta = (result as any)?.meta ?? (Array.isArray(result) ? (result as any)[0]?.meta : undefined);\r\n if (meta) {\r\n span.setAttributes({\r\n 'cloudflare.d1.rows_read': meta.rows_read,\r\n 'cloudflare.d1.rows_written': meta.rows_written,\r\n 'cloudflare.d1.served_by': meta.served_by,\r\n });\r\n }\r\n const rows = (result as any)?.results;\r\n if (Array.isArray(rows)) span.setAttribute('db.response.returned_rows', rows.length);\r\n });\r\n return result;\r\n } catch (error) {\r\n const message = (error as Error)?.message ?? String(error);\r\n span.setStatus({ code: SpanStatusCode.ERROR, message });\r\n const code = sqliteCode(message);\r\n if (code) span.setAttribute('db.response.status_code', code);\r\n if (query.captureErrors && error && typeof error === 'object' && !failures.has(error)) {\r\n const failure = queryFailure(error, span, query.sql, query.database, query.frames);\r\n failures.set(error, failure);\r\n state.queryFailures.push(failure);\r\n }\r\n throw error;\r\n } finally {\r\n span.end();\r\n }\r\n}\r\n\r\n/** Our statement proxy → D1's own statement, for `batch()`; and its SQL, for naming the batch. */\r\nconst originals = new WeakMap<object, object>();\r\nconst sqlOf = new WeakMap<object, string>();\r\nconst RUNS = new Set(['first', 'all', 'run', 'raw']);\r\n\r\nfunction wrapStatement(statement: any, sql: string, database: string, captureErrors: boolean): any {\r\n const proxy = new Proxy(statement, {\r\n get(target, prop) {\r\n const value = Reflect.get(target, prop, target);\r\n if (typeof value !== 'function') return value;\r\n if (prop === 'bind') {\r\n return (...args: unknown[]) => wrapStatement(value.apply(target, args), sql, database, captureErrors);\r\n }\r\n if (typeof prop === 'string' && RUNS.has(prop)) {\r\n const run = function (...args: unknown[]) {\r\n const frames = callSite(run);\r\n return traced({ database, sql, operation: operationOf(sql), frames, captureErrors }, () => value.apply(target, args));\r\n };\r\n return run;\r\n }\r\n return value.bind(target);\r\n },\r\n });\r\n originals.set(proxy, statement);\r\n sqlOf.set(proxy, sql);\r\n return proxy;\r\n}\r\n\r\n/** A D1 database (or one of its sessions) whose queries are traced. */\r\nexport function wrapD1(db: any, database: string, captureErrors: boolean): any {\r\n return new Proxy(db, {\r\n get(target, prop) {\r\n const value = Reflect.get(target, prop, target);\r\n if (typeof value !== 'function') return value;\r\n if (prop === 'prepare') {\r\n return (sql: string) => wrapStatement(value.call(target, sql), String(sql ?? ''), database, captureErrors);\r\n }\r\n if (prop === 'batch') {\r\n const batch = function (statements: unknown[]) {\r\n const frames = callSite(batch);\r\n const list = Array.isArray(statements) ? statements : [];\r\n const sql = list.map((s) => (s && typeof s === 'object' ? sqlOf.get(s) : undefined) ?? '?').join(';\\n');\r\n const real = list.map((s) => (s && typeof s === 'object' ? originals.get(s) ?? s : s));\r\n return traced({ database, sql, operation: 'BATCH', frames, captureErrors }, () => value.call(target, real));\r\n };\r\n return batch;\r\n }\r\n if (prop === 'exec') {\r\n const exec = function (sql: string) {\r\n const frames = callSite(exec);\r\n return traced({ database, sql: String(sql ?? ''), operation: operationOf(String(sql ?? '')), frames, captureErrors }, () => value.call(target, sql));\r\n };\r\n return exec;\r\n }\r\n if (prop === 'withSession') {\r\n return (...args: unknown[]) => wrapD1(value.apply(target, args), database, captureErrors);\r\n }\r\n return value.bind(target);\r\n },\r\n });\r\n}\r\n","/**\r\n * CLIENT spans for `fetch` and `XMLHttpRequest`, and the headers that carry the trace on.\r\n *\r\n * Only same-origin requests and those matching `tracingOrigins` get `traceparent` and\r\n * `baggage`: an unexpected header on a third-party request turns it into a CORS preflight the\r\n * third party may refuse. Every request still gets a span; the SDK's own requests get neither.\r\n */\r\nimport { bodyAttributes, describedAttributes, fileLabel, isTextual, rawLimit, redactUrl, wanted, type BodySettings } from '@zharp/internal/bodies';\r\nimport { headerAttributes, parseHeaderBlock, type HeaderSettings } from '@zharp/internal/headers';\r\nimport { Kind, Status, type Span, type Tracer } from '../tracing';\r\nimport { now, safely } from '../util';\r\n\r\nexport interface HttpHooks {\r\n tracer: Tracer;\r\n /** Whether a URL is traced at all (not the SDK's own endpoint, not ignored). */\r\n shouldTrace(url: string): boolean;\r\n /** Whether a URL gets the trace headers. */\r\n shouldPropagate(url: string): boolean;\r\n /** `baggage` entries: the session and user. */\r\n baggage(): string;\r\n /** `captureBodies`, or null when it is off. */\r\n bodies: BodySettings | null;\r\n /** `captureHeaders`, or null when it is off. */\r\n headers?: HeaderSettings | null;\r\n /** Whether a URL's bodies may be captured (the app's own APIs unless `captureBodies.urls` says otherwise). */\r\n shouldCaptureBodies(url: string): boolean;\r\n}\r\n\r\n/** How long a span waits for its response body to be read before it is sent without it. */\r\nconst BODY_WAIT_MS = 3000;\r\n\r\n/** Reads the request and response bodies, once the status says they are wanted. */\r\ntype BodyReader = (status: number) => Promise<Record<string, unknown>> | Record<string, unknown> | undefined;\r\n\r\n/** The span for one request, and the root spans waiting for it. */\r\nfunction begin(hooks: HttpHooks, method: string, url: string): { span: Span; done: (status: number, error?: unknown, bodies?: BodyReader) => void } {\r\n const { parent, waiters } = hooks.tracer.requestStarting();\r\n const full = absolute(url);\r\n const span = hooks.tracer.startSpan(`${method} ${pathOf(full)}`, Kind.Client, parent);\r\n span.setAttributes({ 'http.request.method': method, 'url.full': redactUrl(full), 'server.address': hostOf(full) });\r\n for (const waiter of waiters) waiter.begin();\r\n return {\r\n span,\r\n done(status, error, bodies) {\r\n const end = now();\r\n if (status) span.setAttribute('http.response.status_code', status);\r\n if (error !== undefined || !status) {\r\n span.setAttribute('error.type', error instanceof Error ? error.name : 'network');\r\n span.setStatus(Status.Error, error instanceof Error ? error.message : 'Request failed');\r\n } else if (status >= 400) {\r\n span.setAttribute('error.type', String(status));\r\n span.setStatus(Status.Error, `HTTP ${status}`);\r\n }\r\n for (const waiter of waiters) waiter.done();\r\n\r\n // The span keeps the time the response arrived; reading its body only delays sending it.\r\n const read = bodies && safely(() => bodies(status));\r\n if (!read || typeof (read as Promise<unknown>).then !== 'function') {\r\n if (read) span.setAttributes(read as Record<string, unknown>);\r\n span.end(end);\r\n return;\r\n }\r\n const timer = setTimeout(() => span.end(end), BODY_WAIT_MS);\r\n (read as Promise<Record<string, unknown>>).then(\r\n (attributes) => {\r\n clearTimeout(timer);\r\n if (!span.ended) span.setAttributes(attributes);\r\n span.end(end);\r\n },\r\n () => {\r\n clearTimeout(timer);\r\n span.end(end);\r\n },\r\n );\r\n },\r\n };\r\n}\r\n\r\n// ── bodies ────────────────────────────────────────────────────────────────────\r\n\r\ntype Attrs = Record<string, unknown>;\r\n\r\n/**\r\n * The request body's attributes. Text is kept (redacted); a form upload is shown as its fields\r\n * with each file described; anything else is described by type and size. Streams are never\r\n * read, and the caller's own body is never consumed.\r\n */\r\nfunction requestAttributes(body: unknown, contentType: string | null, settings: BodySettings): Attrs | Promise<Attrs> {\r\n if (body == null) return {};\r\n const text = (t: string, type: string | null, cut = false): Attrs =>\r\n isTextual(type) ? bodyAttributes('request', t, type, settings, cut) : describedAttributes('request', type, t.length);\r\n if (typeof body === 'string') return text(body, contentType);\r\n if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) return text(body.toString(), 'application/x-www-form-urlencoded');\r\n if (typeof FormData !== 'undefined' && body instanceof FormData) {\r\n const fields: Record<string, unknown> = {};\r\n body.forEach((value, key) => {\r\n const shown = typeof value === 'string' ? value : fileLabel((value as File).name, (value as File).type || undefined, (value as File).size);\r\n const existing = fields[key];\r\n fields[key] = existing === undefined ? shown : Array.isArray(existing) ? [...existing, shown] : [existing, shown];\r\n });\r\n return bodyAttributes('request', JSON.stringify(fields), 'multipart/form-data', settings);\r\n }\r\n if (typeof Blob !== 'undefined' && body instanceof Blob) {\r\n const type = body.type || contentType;\r\n if (!isTextual(type)) return describedAttributes('request', type, body.size);\r\n const limit = rawLimit(settings);\r\n return body.slice(0, limit).text().then((t) => text(t, type, body.size > limit), () => ({}));\r\n }\r\n if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) {\r\n const size = (body as ArrayBuffer).byteLength;\r\n if (!contentType || !isTextual(contentType)) return describedAttributes('request', contentType, size);\r\n return text(new TextDecoder().decode(body as ArrayBuffer), contentType);\r\n }\r\n if (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) return describedAttributes('request', contentType);\r\n return {};\r\n}\r\n\r\n/** Up to `limit` characters of a response copy; the rest is cancelled, never downloaded twice. */\r\nasync function readLimited(response: Response, limit: number): Promise<{ text: string; cut: boolean }> {\r\n const reader = response.body?.getReader();\r\n if (!reader) {\r\n const text = await response.text();\r\n return { text: text.slice(0, limit), cut: text.length > limit };\r\n }\r\n const decoder = new TextDecoder();\r\n let text = '';\r\n for (;;) {\r\n const { done, value } = await reader.read();\r\n if (done) break;\r\n text += decoder.decode(value, { stream: true });\r\n if (text.length > limit) {\r\n reader.cancel().catch(() => {});\r\n return { text: text.slice(0, limit), cut: true };\r\n }\r\n }\r\n return { text: text + decoder.decode(), cut: false };\r\n}\r\n\r\n/** The content type the browser gives a body the caller sent without one. */\r\nfunction implicitType(body: unknown): string | null {\r\n if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) return 'application/x-www-form-urlencoded';\r\n if (typeof FormData !== 'undefined' && body instanceof FormData) return 'multipart/form-data';\r\n if (typeof Blob !== 'undefined' && body instanceof Blob) return body.type || null;\r\n return null;\r\n}\r\n\r\nconst contentLength = (headers: Headers | undefined): number | undefined => {\r\n const n = Number(headers?.get('content-length'));\r\n return Number.isFinite(n) && n > 0 ? n : undefined;\r\n};\r\n\r\nfunction headerOf(headers: HeadersInit | undefined, name: string): string | null {\r\n if (!headers) return null;\r\n return safely(() => new Headers(headers).get(name)) ?? null;\r\n}\r\n\r\n/** `baggage` merged with any the caller already set. */\r\nfunction mergeBaggage(existing: string | null | undefined, ours: string): string {\r\n return existing ? `${existing},${ours}` : ours;\r\n}\r\n\r\nexport function instrumentFetch(hooks: HttpHooks): () => void {\r\n const g = globalThis as any;\r\n const original = g.fetch;\r\n if (typeof original !== 'function' || original.__zharp) return () => {};\r\n\r\n const patched = function (this: unknown, input: RequestInfo | URL, init?: RequestInit): Promise<Response> {\r\n const url = typeof input === 'string' ? input : input instanceof URL ? input.href : (input as Request)?.url;\r\n if (!url || !hooks.shouldTrace(url)) return original.call(this, input, init);\r\n\r\n const method = String(init?.method ?? (input as Request)?.method ?? 'GET').toUpperCase();\r\n const request = safely(() => begin(hooks, method, url));\r\n if (!request) return original.call(this, input, init);\r\n\r\n // Bodies: what is needed to read them later is set aside now, before fetch consumes anything.\r\n const bodies = hooks.bodies && hooks.shouldCaptureBodies(url) ? hooks.bodies : null;\r\n let sent: (() => Attrs | Promise<Attrs>) | undefined;\r\n let sentType: string | null = null;\r\n if (bodies) {\r\n safely(() => {\r\n const isRequest = typeof Request !== 'undefined' && input instanceof Request;\r\n sentType = headerOf(init?.headers, 'content-type') ?? (isRequest ? (input as Request).headers.get('content-type') : null);\r\n if (init?.body != null) {\r\n const body = init.body;\r\n sentType = (body instanceof FormData ? null : sentType) ?? implicitType(body);\r\n sent = () => requestAttributes(body, sentType, bodies);\r\n } else if (isRequest && (input as Request).body) {\r\n const type = sentType;\r\n if (isTextual(type)) {\r\n const copy = (input as Request).clone();\r\n sent = () => copy.text().then((t) => requestAttributes(t, type, bodies));\r\n } else {\r\n sent = () => describedAttributes('request', type, contentLength((input as Request).headers));\r\n }\r\n }\r\n });\r\n }\r\n\r\n let nextInit = init;\r\n if (hooks.shouldPropagate(url)) {\r\n nextInit = safely(() => {\r\n const headers = new Headers(init?.headers ?? (typeof Request !== 'undefined' && input instanceof Request ? input.headers : undefined));\r\n // A traceparent the caller set is a trace they are deliberately continuing.\r\n if (!headers.has('traceparent')) headers.set('traceparent', request.span.traceparent);\r\n const baggage = hooks.baggage();\r\n if (baggage) headers.set('baggage', mergeBaggage(headers.get('baggage'), baggage));\r\n return { ...init, headers };\r\n }) ?? init;\r\n }\r\n\r\n // Headers as they go out (the trace headers included) and as they come back.\r\n const headers = hooks.headers;\r\n if (headers) {\r\n safely(() => {\r\n const sentHeaders = new Headers(nextInit?.headers ?? (typeof Request !== 'undefined' && input instanceof Request ? input.headers : undefined));\r\n request.span.setAttributes(headerAttributes('request', sentHeaders, headers));\r\n });\r\n }\r\n\r\n const readBodies = (response?: Response): BodyReader | undefined =>\r\n bodies\r\n ? (status) => {\r\n if (!wanted(bodies, status)) return undefined;\r\n const responseType = response?.headers.get('content-type') ?? null;\r\n const hasBody = !!response?.body && response.status !== 204 && response.status !== 304;\r\n // Copied now, before the caller reads it; text only. Anything else (an image, an event\r\n // stream) is described, never read.\r\n const copy = hasBody && isTextual(responseType) ? safely(() => response!.clone()) : undefined;\r\n return (async () => {\r\n const attributes: Attrs = {};\r\n Object.assign(attributes, (await Promise.resolve(sent?.()).catch(() => undefined)) ?? {});\r\n if (copy) {\r\n const read = await readLimited(copy, rawLimit(bodies)).catch(() => null);\r\n if (read) Object.assign(attributes, bodyAttributes('response', read.text, responseType, bodies, read.cut));\r\n } else if (hasBody && response) {\r\n Object.assign(attributes, describedAttributes('response', responseType, contentLength(response.headers)));\r\n }\r\n return attributes;\r\n })();\r\n }\r\n : undefined;\r\n\r\n return original.call(this, input, nextInit).then(\r\n (response: Response) => {\r\n if (headers) safely(() => request.span.setAttributes(headerAttributes('response', response.headers, headers)));\r\n safely(() => request.done(response.status, undefined, readBodies(response)));\r\n return response;\r\n },\r\n (error: unknown) => {\r\n safely(() => request.done(0, error, readBodies()));\r\n throw error;\r\n },\r\n );\r\n };\r\n patched.__zharp = true;\r\n g.fetch = patched;\r\n return () => {\r\n if (g.fetch === patched) g.fetch = original;\r\n };\r\n}\r\n\r\nexport function instrumentXhr(hooks: HttpHooks): () => void {\r\n if (typeof XMLHttpRequest === 'undefined') return () => {};\r\n const proto = XMLHttpRequest.prototype as any;\r\n if (proto.__zharp) return () => {};\r\n const { open, send, setRequestHeader } = proto;\r\n\r\n proto.open = function (method: string, url: string | URL, ...rest: unknown[]) {\r\n this.__zharp = { method: String(method || 'GET').toUpperCase(), url: String(url), traceparent: false, baggage: null, headers: [] };\r\n return open.call(this, method, url, ...rest);\r\n };\r\n\r\n proto.setRequestHeader = function (name: string, value: string) {\r\n const state = this.__zharp;\r\n const lower = String(name).toLowerCase();\r\n // XHR headers cannot be read back, so what the caller sets is noted as it is set.\r\n if (state && lower === 'traceparent') state.traceparent = true;\r\n if (state && lower === 'content-type') state.contentType = String(value);\r\n if (state && !state.own) state.headers.push([String(name), String(value)]);\r\n if (state && lower === 'baggage' && !state.own) {\r\n state.baggage = value;\r\n return; // sent merged with ours in send()\r\n }\r\n return setRequestHeader.call(this, name, value);\r\n };\r\n\r\n proto.send = function (body?: unknown) {\r\n const state = this.__zharp;\r\n if (!state || !hooks.shouldTrace(state.url)) return send.call(this, body);\r\n const request = safely(() => begin(hooks, state.method, state.url));\r\n if (request) {\r\n safely(() => {\r\n if (hooks.shouldPropagate(state.url)) {\r\n state.own = true;\r\n if (!state.traceparent) setRequestHeader.call(this, 'traceparent', request.span.traceparent);\r\n const baggage = hooks.baggage();\r\n if (baggage || state.baggage) setRequestHeader.call(this, 'baggage', baggage ? mergeBaggage(state.baggage, baggage) : state.baggage);\r\n } else if (state.baggage) {\r\n setRequestHeader.call(this, 'baggage', state.baggage);\r\n }\r\n });\r\n const bodies = hooks.bodies && hooks.shouldCaptureBodies(state.url) ? hooks.bodies : null;\r\n const xhr = this as XMLHttpRequest;\r\n const headers = hooks.headers;\r\n if (headers) {\r\n safely(() => {\r\n // What the caller set (baggage merged with ours), and the trace headers sent with it.\r\n const sent: Array<[string, string]> = state.headers.filter(([n]: [string, string]) => n.toLowerCase() !== 'baggage');\r\n if (state.own && !state.traceparent) sent.push(['traceparent', request.span.traceparent]);\r\n const baggage = state.own ? (hooks.baggage() ? mergeBaggage(state.baggage, hooks.baggage()) : state.baggage) : state.baggage;\r\n if (baggage) sent.push(['baggage', baggage]);\r\n request.span.setAttributes(headerAttributes('request', sent, headers));\r\n });\r\n }\r\n const reader: BodyReader | undefined = bodies\r\n ? (status) => {\r\n if (!wanted(bodies, status)) return undefined;\r\n const sentType: string | null = (body instanceof FormData ? null : state.contentType) ?? implicitType(body);\r\n const responseType = safely(() => xhr.getResponseHeader('content-type')) ?? null;\r\n const attributes: Attrs =\r\n safely(() => {\r\n const kind = xhr.responseType;\r\n const response = xhr.response;\r\n if (response == null || response === '') return {};\r\n if (kind === 'blob') return describedAttributes('response', responseType, (response as Blob).size);\r\n if (kind === 'arraybuffer') return describedAttributes('response', responseType, (response as ArrayBuffer).byteLength);\r\n if (kind === 'document') return {};\r\n const text = kind === 'json' ? JSON.stringify(response) : xhr.responseText;\r\n const limit = rawLimit(bodies);\r\n if (!isTextual(responseType)) return describedAttributes('response', responseType, text.length);\r\n return bodyAttributes('response', text.slice(0, limit), responseType, bodies, text.length > limit);\r\n }) ?? {};\r\n const sentAttributes = requestAttributes(body, sentType, bodies);\r\n if (sentAttributes && typeof (sentAttributes as Promise<Attrs>).then === 'function') {\r\n return (sentAttributes as Promise<Attrs>).then((a) => ({ ...attributes, ...a }), () => attributes);\r\n }\r\n return { ...attributes, ...(sentAttributes as Attrs) };\r\n }\r\n : undefined;\r\n this.addEventListener('loadend', () => {\r\n if (headers) safely(() => request.span.setAttributes(headerAttributes('response', parseHeaderBlock(xhr.getAllResponseHeaders()), headers)));\r\n safely(() => request.done(this.status, undefined, reader));\r\n });\r\n } else if (state.baggage) {\r\n safely(() => setRequestHeader.call(this, 'baggage', state.baggage));\r\n }\r\n return send.call(this, body);\r\n };\r\n proto.__zharp = true;\r\n\r\n return () => {\r\n Object.assign(proto, { open, send, setRequestHeader });\r\n delete proto.__zharp;\r\n };\r\n}\r\n\r\n// ── URLs ──────────────────────────────────────────────────────────────────────\r\n\r\nconst base = () => (typeof location !== 'undefined' ? location.href : 'http://localhost/');\r\n\r\nexport function absolute(url: string): string {\r\n return safely(() => new URL(url, base()).href) ?? url;\r\n}\r\n\r\nfunction pathOf(url: string): string {\r\n return safely(() => new URL(url).pathname) ?? url.split('?')[0];\r\n}\r\n\r\nfunction hostOf(url: string): string {\r\n return safely(() => new URL(url).hostname) ?? '';\r\n}\r\n\r\n/**\r\n * Whether `url` matches one of `patterns`: a bare host (`api.example.com`, with or without a\r\n * port) matches that host; a string with a scheme matches as a prefix; a RegExp is tested.\r\n */\r\nexport function matches(url: string, patterns: Array<string | RegExp>): boolean {\r\n const parsed = safely(() => new URL(url, base()));\r\n if (!parsed) return false;\r\n return patterns.some((pattern) => {\r\n if (pattern instanceof RegExp) return pattern.test(parsed.href);\r\n if (!pattern) return false;\r\n if (pattern.includes('://')) return parsed.href.startsWith(pattern);\r\n return parsed.host === pattern || parsed.hostname === pattern;\r\n });\r\n}\r\n\r\nexport function sameOrigin(url: string): boolean {\r\n return safely(() => typeof location !== 'undefined' && new URL(url, base()).origin === location.origin) ?? false;\r\n}\r\n","/**\r\n * Outgoing requests: a CLIENT span per `fetch`, with `traceparent` added so the next service\r\n * continues the trace — the browser → Worker → origin API reads as one. The same for service\r\n * bindings and Durable Object stubs (`env.API.fetch(…)`, `stub.fetch(…)`), which carry it to the\r\n * next Worker. Only inside a request: `fetch` at startup is left alone, and Zharp's own requests\r\n * use the fetch from before this ran.\r\n */\r\nimport { headerAttributes } from '@zharp/internal/headers';\r\nimport { redactUrl } from '@zharp/internal/bodies';\r\nimport { matches } from '../../browser/src/instrument/http';\r\nimport { safely } from '../../browser/src/util';\r\nimport { activeContext, formatTraceparent, requestOf, SpanKind, SpanStatusCode, startSpan, withSpan } from './tracing';\r\nimport type { Runtime } from './state';\r\n\r\nlet installed = false;\r\n\r\nexport function instrumentGlobalFetch(runtime: Runtime): void {\r\n if (installed || typeof globalThis.fetch !== 'function') return;\r\n installed = true;\r\n const original = globalThis.fetch;\r\n const patched = function fetch(input: RequestInfo | URL, init?: RequestInit) {\r\n return tracedFetch(runtime, original, globalThis, input, init, undefined);\r\n };\r\n (patched as any).__zharp = true;\r\n globalThis.fetch = patched as typeof fetch;\r\n}\r\n\r\n/**\r\n * Send a request through `send` in a CLIENT span. `binding` names a service binding or Durable\r\n * Object the request goes to instead of the network.\r\n */\r\nexport function tracedFetch(\r\n runtime: Runtime,\r\n send: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,\r\n thisArg: unknown,\r\n input: RequestInfo | URL,\r\n init: RequestInit | undefined,\r\n binding: { name: string; type: string } | undefined,\r\n): Promise<Response> {\r\n const ctx = activeContext();\r\n if (!requestOf(ctx) || !runtime.settings.tracing) return send.call(thisArg, input, init);\r\n let request: Request;\r\n try {\r\n request = new Request(input as RequestInfo, init);\r\n } catch {\r\n return send.call(thisArg, input, init);\r\n }\r\n const url = safely(() => new URL(request.url));\r\n if (!binding && (!url || request.url.startsWith(runtime.settings.endpoint) || matches(request.url, runtime.settings.ignoreUrls))) {\r\n return send.call(thisArg, request);\r\n }\r\n\r\n const method = request.method.toUpperCase();\r\n const span = startSpan(binding ? `${method} ${binding.name}` : `${method} ${url?.host ?? ''}`.trim(), {\r\n kind: SpanKind.CLIENT,\r\n attributes: {\r\n 'http.request.method': method,\r\n 'url.full': redactUrl(request.url),\r\n 'server.address': binding ? undefined : url?.hostname,\r\n 'server.port': binding || !url?.port ? undefined : Number(url.port),\r\n ...(binding ? { 'cloudflare.binding.name': binding.name, 'cloudflare.binding.type': binding.type } : {}),\r\n },\r\n }, ctx);\r\n if (!request.headers.has('traceparent')) safely(() => request.headers.set('traceparent', formatTraceparent(span.spanContext())));\r\n if (runtime.headers) span.setAttributes(headerAttributes('request', request.headers, runtime.headers));\r\n\r\n return withSpan(span, () => send.call(thisArg, request), ctx).then(\r\n (response) => {\r\n safely(() => {\r\n span.setAttribute('http.response.status_code', response.status);\r\n if (runtime.headers) span.setAttributes(headerAttributes('response', response.headers, runtime.headers));\r\n if (response.status >= 400) span.setStatus({ code: SpanStatusCode.ERROR, message: `HTTP ${response.status}` });\r\n span.end();\r\n });\r\n return response;\r\n },\r\n (error) => {\r\n safely(() => {\r\n span.setStatus({ code: SpanStatusCode.ERROR, message: (error as Error)?.message ?? String(error) });\r\n span.setAttribute('error.type', (error as Error)?.name || 'Error');\r\n span.end();\r\n });\r\n throw error;\r\n },\r\n );\r\n}\r\n","/**\r\n * The SDK in one isolate: settings read from the first `env` it sees, the queues of spans and\r\n * logs, and how errors are reported. And the state of each request (or alarm, queue batch,\r\n * cron run) it handles: its tags, its user, and what it still has to send when it ends.\r\n *\r\n * An isolate lives across many requests, so nothing about a request is kept outside its state;\r\n * and there is no timer to send things later — each request flushes with `ctx.waitUntil`, so the\r\n * response is not held up and the work still finishes.\r\n */\r\nimport { headerSettings, type HeaderSettings } from '@zharp/internal/headers';\r\nimport { asError, exceptionAttributes, watchConsole } from '../../browser/src/instrument/errors';\r\nimport { Exporter, type Endpoint } from '../../browser/src/transport';\r\nimport { keyValues, now, safely, safeString, toNanos } from '../../browser/src/util';\r\nimport { DEFAULT_ENDPOINT, resolveSettings, type Settings } from './settings';\r\nimport { activeSpan, registerOpenTelemetry, requestOf, setRecordedExceptionHandler, setSpanSink, type ZharpSpan } from './tracing';\r\nimport type { Attributes, ZharpConfig, ZharpUser } from './types';\r\nimport { VERSION } from './version';\r\nimport { claimQueryFailure, unclaimedQueryFailures, type QueryFailure } from './d1';\r\nimport { instrumentGlobalFetch } from './fetch';\r\n\r\nexport const SEVERITY = { trace: 1, debug: 5, info: 9, warn: 13, error: 17, fatal: 21 } as const;\r\nexport type Level = keyof typeof SEVERITY;\r\n\r\nexport interface RequestState {\r\n runtime: Runtime;\r\n tags: Record<string, unknown>;\r\n user: ZharpUser | null;\r\n /** Failed queries not yet reported: reported as handled when the request ends, unless what it threw claims them first. */\r\n queryFailures: QueryFailure[];\r\n /** Work handed to `ctx.waitUntil`: the request is flushed once it has settled. */\r\n pending: Promise<unknown>[];\r\n}\r\n\r\n/** Tags and user set outside any request: on everything this isolate sends. */\r\nconst globalTags: Record<string, unknown> = {};\r\nlet globalUser: ZharpUser | null = null;\r\n\r\nexport class Runtime {\r\n readonly endpoint: Endpoint;\r\n readonly spans: Exporter<unknown>;\r\n readonly logs: Exporter<unknown>;\r\n readonly headers: HeaderSettings | null;\r\n /** Errors already reported, so one rethrown, caught again or logged is sent once. */\r\n private readonly reported = new WeakSet<object>();\r\n\r\n constructor(readonly settings: Settings) {\r\n const original = globalThis.fetch;\r\n this.endpoint = {\r\n url: settings.endpoint,\r\n key: settings.key,\r\n fetch: original,\r\n rejectedHint: 'nothing more will be sent from this isolate. Check the ZHARP_KEY secret (the app key from the Zharp dashboard).',\r\n };\r\n this.headers = headerSettings(settings.captureHeaders);\r\n const resource = keyValues(settings.resource);\r\n const scope = { name: '@zharp/cloudflare', version: VERSION };\r\n this.spans = new Exporter<unknown>(\r\n this.endpoint,\r\n 'traces',\r\n (records) => ({ resourceSpans: [{ resource: { attributes: resource }, scopeSpans: [{ scope, spans: records }] }] }),\r\n false,\r\n );\r\n this.logs = new Exporter<unknown>(\r\n this.endpoint,\r\n 'logs',\r\n (records) => ({ resourceLogs: [{ resource: { attributes: resource }, scopeLogs: [{ scope, logRecords: records }] }] }),\r\n false,\r\n );\r\n\r\n setSpanSink({\r\n sampleRate: settings.sampleRate,\r\n export: (span) => {\r\n if (settings.tracing) this.spans.add(span.toOtlp(contextAttributes(span.request)));\r\n },\r\n });\r\n setRecordedExceptionHandler((exception, span) => this.report(exception, true, { 'zharp.mechanism': 'opentelemetry' }, span));\r\n registerOpenTelemetry();\r\n if (settings.tracing) instrumentGlobalFetch(this);\r\n if (settings.logs) {\r\n watchConsole(['debug', 'log', 'info', 'warn', 'error'], (level, message) => this.emit(level, message, { 'log.source': 'console' }));\r\n }\r\n }\r\n\r\n newRequest(): RequestState {\r\n return { runtime: this, tags: {}, user: null, queryFailures: [], pending: [] };\r\n }\r\n\r\n /**\r\n * Report an error once: what a handler threw, what the app caught and passed to\r\n * `captureError`, a failed query. A failed D1 query that reaches here is reported with its SQL\r\n * and the line of the app that ran it.\r\n */\r\n report(value: unknown, handled: boolean, attributes: Attributes = {}, span: ZharpSpan | undefined = activeSpan()): void {\r\n safely(() => {\r\n if (value && typeof value === 'object') {\r\n if (this.reported.has(value)) return;\r\n this.reported.add(value);\r\n }\r\n const query = claimQueryFailure(value);\r\n const exception = query ? query.exception(handled) : exceptionAttributes(asError(value), handled);\r\n this.emit(\r\n 'error',\r\n `${exception['exception.type']}: ${exception['exception.message']}`,\r\n { ...(query?.attributes ?? {}), ...attributes },\r\n exception,\r\n span,\r\n );\r\n });\r\n }\r\n\r\n /** Whether `value` was reported already. */\r\n wasReported(value: unknown): boolean {\r\n return !!value && typeof value === 'object' && this.reported.has(value);\r\n }\r\n\r\n emit(level: Level, message: unknown, attributes?: Attributes, exception?: Record<string, string>, span: ZharpSpan | undefined = activeSpan()): void {\r\n safely(() => {\r\n const time = toNanos(now());\r\n const state = span?.request ?? requestOf();\r\n const attrs: Record<string, unknown> = { ...contextAttributes(state) };\r\n for (const key in attributes) {\r\n const value = attributes[key];\r\n // An Error passed with an error log is the reason for it: sent as the exception, with its stack.\r\n if (value instanceof Error && !exception && (level === 'error' || level === 'fatal')) {\r\n exception = exceptionAttributes(value, true);\r\n this.reported.add(value);\r\n } else attrs[key] = value;\r\n }\r\n this.logs.add({\r\n timeUnixNano: time,\r\n observedTimeUnixNano: time,\r\n severityNumber: SEVERITY[level],\r\n severityText: level.toUpperCase(),\r\n body: { stringValue: typeof message === 'string' ? message : message instanceof Error ? message.message : safeString(message) },\r\n attributes: keyValues({ ...attrs, ...exception }),\r\n traceId: span?.traceId,\r\n spanId: span?.spanId,\r\n });\r\n });\r\n }\r\n\r\n /**\r\n * The end of a request: once its `waitUntil` work has settled, report the failed queries\r\n * nothing claimed (as handled: the app caught them), then send everything queued.\r\n */\r\n async finish(state: RequestState): Promise<void> {\r\n try {\r\n // waitUntil work may hand more work to waitUntil.\r\n for (let seen = 0; seen < state.pending.length; ) {\r\n const batch = state.pending.slice(seen);\r\n seen = state.pending.length;\r\n await Promise.allSettled(batch);\r\n }\r\n for (const failure of unclaimedQueryFailures(state)) this.report(failure.error, true, {}, failure.span);\r\n } catch {\r\n // Never let telemetry fail the request's own work.\r\n }\r\n await this.flush();\r\n }\r\n\r\n async flush(): Promise<void> {\r\n await Promise.all([this.spans.flush(), this.logs.flush()]).catch(() => {});\r\n }\r\n}\r\n\r\n/** Tags and user, as they are on everything sent for a request. */\r\nexport function contextAttributes(state: RequestState | undefined): Record<string, unknown> {\r\n const user = state?.user ?? globalUser;\r\n return {\r\n ...globalTags,\r\n ...state?.tags,\r\n 'enduser.id': user ? String(user.id) : undefined,\r\n 'enduser.email': user?.email,\r\n 'enduser.name': user?.name,\r\n };\r\n}\r\n\r\nexport function setTag(key: string, value: string | number | boolean | null | undefined): void {\r\n const target = requestOf()?.tags ?? globalTags;\r\n if (value === null || value === undefined) delete target[key];\r\n else target[key] = value;\r\n}\r\n\r\nexport function setUser(user: ZharpUser | null): void {\r\n const clean = user && user.id !== undefined && user.id !== null && user.id !== '' ? { id: user.id, email: user.email, name: user.name } : null;\r\n const state = requestOf();\r\n if (state) state.user = clean;\r\n else globalUser = clean;\r\n}\r\n\r\n// ── the isolate's runtime ───────────────────────────────────────────────\r\n\r\nlet runtime: Runtime | null = null;\r\nlet warnedNoKey = false;\r\nlet lastConfig: ZharpConfig | undefined;\r\n\r\n/** The runtime, started from the first `env` with a key. Null when there is none: then nothing is sent. */\r\nexport function runtimeFor(env: unknown, config: ZharpConfig | undefined, defaults: { service: string; platform: string }): Runtime | null {\r\n if (runtime) return runtime;\r\n if (config !== undefined) lastConfig = config;\r\n const settings = safely(() => resolveSettings(env, config ?? lastConfig, defaults));\r\n if (!settings) {\r\n const disabled = /^(true|1|yes|on)$/i.test(String((env as Record<string, unknown> | undefined)?.ZHARP_DISABLED ?? ''));\r\n if (!warnedNoKey && !disabled) {\r\n warnedNoKey = true;\r\n console.warn('[Zharp] No key: set the ZHARP_KEY secret (wrangler secret put ZHARP_KEY) to the app key from the Zharp dashboard. Nothing will be sent.');\r\n }\r\n return null;\r\n }\r\n runtime = new Runtime(settings);\r\n return runtime;\r\n}\r\n\r\n/** The runtime, if one has started. */\r\nexport const currentRuntime = (): Runtime | null => runtime;\r\n\r\nexport { DEFAULT_ENDPOINT };\r\n","/**\r\n * The Worker's bindings, traced: D1 (see d1.ts), KV, R2, Queue producers, service bindings and\r\n * Durable Object stubs. The handler gets an `env` whose bindings are wrapped as they are used;\r\n * everything else in it (vars, secrets, bindings Zharp doesn't know) is handed over untouched.\r\n *\r\n * Bindings are told apart by their class (`D1Database`, `KvNamespace`, …). Not by their methods:\r\n * a service binding answers every method name (each is an RPC call), so it would look like all\r\n * of them.\r\n */\r\nimport { safely } from '../../browser/src/util';\r\nimport { wrapD1 } from './d1';\r\nimport { tracedFetch } from './fetch';\r\nimport { activeContext, requestOf, SpanKind, SpanStatusCode, startSpan } from './tracing';\r\nimport type { Runtime } from './state';\r\n\r\ntype Kind = 'd1' | 'kv' | 'r2' | 'queue' | 'service' | 'durable-object';\r\n\r\nconst CLASSES: Record<string, Kind> = {\r\n D1Database: 'd1',\r\n D1DatabaseSession: 'd1',\r\n KvNamespace: 'kv',\r\n R2Bucket: 'r2',\r\n WorkerQueue: 'queue',\r\n Fetcher: 'service',\r\n DurableObjectNamespace: 'durable-object',\r\n};\r\n\r\nconst fn = (value: any, ...names: string[]) => names.every((name) => typeof safely(() => value[name]) === 'function');\r\n\r\n/** What kind of binding `value` is, or undefined for anything Zharp leaves alone. */\r\nexport function bindingKind(value: unknown): Kind | undefined {\r\n if (!value || typeof value !== 'object') return undefined;\r\n const name = safely(() => Object.getPrototypeOf(value)?.constructor?.name) as string | undefined;\r\n if (name && CLASSES[name]) return CLASSES[name];\r\n // Plain objects only below this point: a class we don't know (an RPC stub above all) is left alone.\r\n if (name && name !== 'Object') return undefined;\r\n if (fn(value, 'prepare', 'batch', 'exec')) return 'd1';\r\n if (fn(value, 'head', 'get', 'put', 'list', 'delete', 'createMultipartUpload')) return 'r2';\r\n if (fn(value, 'get', 'put', 'list', 'delete', 'getWithMetadata')) return 'kv';\r\n if (fn(value, 'send', 'sendBatch')) return 'queue';\r\n if (fn(value, 'idFromName', 'get')) return 'durable-object';\r\n return undefined;\r\n}\r\n\r\nconst MARK = Symbol.for('zharp.cloudflare.wrapped');\r\nconst cache = new WeakMap<object, Map<string, object>>();\r\n\r\n/** `env` with its bindings traced. The same binding object gets the same wrapper every time. */\r\nexport function instrumentEnv<E>(env: E, runtime: Runtime): E {\r\n if (!env || typeof env !== 'object' || (env as any)[MARK]) return env;\r\n return new Proxy(env as object, {\r\n get(target, prop, receiver) {\r\n if (prop === MARK) return true;\r\n const value = Reflect.get(target, prop, receiver);\r\n if (typeof prop !== 'string') return value;\r\n return wrapBinding(value, prop, runtime) ?? value;\r\n },\r\n }) as E;\r\n}\r\n\r\n/** The traced form of one binding, or undefined when it is not one Zharp traces. */\r\nexport function wrapBinding(value: unknown, name: string, runtime: Runtime): object | undefined {\r\n if (!value || typeof value !== 'object' || (value as any)[MARK]) return undefined;\r\n const kind = bindingKind(value);\r\n if (!kind) return undefined;\r\n let byName = cache.get(value);\r\n if (!byName) cache.set(value, (byName = new Map()));\r\n const cached = byName.get(name);\r\n if (cached) return cached;\r\n const wrapped = marked(build(kind, value, name, runtime));\r\n byName.set(name, wrapped);\r\n return wrapped;\r\n}\r\n\r\nfunction build(kind: Kind, value: any, name: string, runtime: Runtime): object {\r\n switch (kind) {\r\n case 'd1':\r\n return wrapD1(value, name, runtime.settings.captureQueryErrors);\r\n case 'kv':\r\n return methods(value, ['get', 'getWithMetadata', 'put', 'list', 'delete'], (method, args) => ({\r\n name: `KV ${method} ${name}`,\r\n kind: SpanKind.CLIENT,\r\n attributes: {\r\n 'db.system': 'cloudflare_kv',\r\n 'db.namespace': name,\r\n 'db.operation.name': method,\r\n 'cloudflare.binding.type': 'kv',\r\n 'cloudflare.kv.key': typeof args[0] === 'string' ? args[0] : undefined,\r\n 'cloudflare.kv.keys': Array.isArray(args[0]) ? args[0].length : undefined,\r\n },\r\n result: method.startsWith('get') ? (result) => ({ 'cloudflare.kv.hit': method === 'get' ? result !== null : (result as any)?.value !== null }) : undefined,\r\n }));\r\n case 'r2':\r\n return methods(value, ['head', 'get', 'put', 'list', 'delete', 'createMultipartUpload', 'resumeMultipartUpload'], (method, args) => ({\r\n name: `R2 ${method} ${name}`,\r\n kind: SpanKind.CLIENT,\r\n attributes: {\r\n 'cloudflare.binding.type': 'r2',\r\n 'cloudflare.r2.bucket': name,\r\n 'cloudflare.r2.operation': method,\r\n 'cloudflare.r2.key': typeof args[0] === 'string' ? args[0] : undefined,\r\n },\r\n result: method === 'get' || method === 'head' ? (result) => ({ 'cloudflare.r2.hit': result !== null }) : undefined,\r\n }));\r\n case 'queue':\r\n return methods(value, ['send', 'sendBatch'], (method, args) => ({\r\n name: `${name} send`,\r\n kind: SpanKind.PRODUCER,\r\n attributes: {\r\n 'messaging.system': 'cloudflare_queues',\r\n 'messaging.operation.type': 'send',\r\n 'messaging.destination.name': name,\r\n 'messaging.batch.message_count': method === 'sendBatch' && Array.isArray(args[0]) ? args[0].length : undefined,\r\n },\r\n }));\r\n case 'service':\r\n return fetcher(value, { name, type: 'service' }, runtime);\r\n case 'durable-object':\r\n return new Proxy(value, {\r\n get(target, prop) {\r\n const member = Reflect.get(target, prop, target);\r\n if (typeof member !== 'function') return member;\r\n // get(id) and getByName(name) hand out stubs; their fetch carries the trace on.\r\n if (prop === 'get' || prop === 'getByName') {\r\n return (...args: unknown[]) => fetcher(member.apply(target, args), { name, type: 'durable-object' }, runtime);\r\n }\r\n return member.bind(target);\r\n },\r\n });\r\n }\r\n}\r\n\r\nfunction marked<T extends object>(value: T): T {\r\n return new Proxy(value, {\r\n get(target, prop, receiver) {\r\n if (prop === MARK) return true;\r\n return Reflect.get(target, prop, receiver);\r\n },\r\n });\r\n}\r\n\r\n/** A service binding or Durable Object stub whose `fetch` is traced; its RPC methods are left as they are. */\r\nfunction fetcher(value: any, binding: { name: string; type: string }, runtime: Runtime): any {\r\n if (!value || typeof value !== 'object') return value;\r\n return new Proxy(value, {\r\n get(target, prop) {\r\n const member = Reflect.get(target, prop, target);\r\n if (prop !== 'fetch' || typeof member !== 'function') return member;\r\n return (input: RequestInfo | URL, init?: RequestInit) => tracedFetch(runtime, member, target, input, init, binding);\r\n },\r\n });\r\n}\r\n\r\ninterface Call {\r\n name: string;\r\n kind: SpanKind;\r\n attributes: Record<string, unknown>;\r\n result?: (result: unknown) => Record<string, unknown>;\r\n}\r\n\r\n/** Each of `names` in a span of its own, while a request is running. */\r\nfunction methods(value: any, names: string[], describe: (method: string, args: unknown[]) => Call): any {\r\n const traced = new Set(names);\r\n return new Proxy(value, {\r\n get(target, prop) {\r\n const member = Reflect.get(target, prop, target);\r\n if (typeof member !== 'function') return member;\r\n if (typeof prop !== 'string' || !traced.has(prop)) return member.bind(target);\r\n return (...args: unknown[]) => {\r\n const ctx = activeContext();\r\n if (!requestOf(ctx)) return member.apply(target, args);\r\n const call = describe(prop, args);\r\n const span = startSpan(call.name, { kind: call.kind, attributes: call.attributes as any }, ctx);\r\n let result: unknown;\r\n try {\r\n result = member.apply(target, args);\r\n } catch (error) {\r\n span.setStatus({ code: SpanStatusCode.ERROR, message: (error as Error)?.message });\r\n span.end();\r\n throw error;\r\n }\r\n return Promise.resolve(result).then(\r\n (value) => {\r\n if (call.result) safely(() => span.setAttributes(call.result!(value)));\r\n span.end();\r\n return value;\r\n },\r\n (error) => {\r\n span.setStatus({ code: SpanStatusCode.ERROR, message: (error as Error)?.message ?? String(error) });\r\n span.end();\r\n throw error;\r\n },\r\n );\r\n };\r\n },\r\n });\r\n}\r\n","/**\r\n * Hono, through the Worker wrapper: the matched route names the span (`GET /users/:id`), and\r\n * errors Hono catches itself — it turns them into a 500 before the wrapper could see them — are\r\n * reported from its error handler. HTTPExceptions under 500 are answers, not errors.\r\n */\r\nimport { safely } from '../../browser/src/util';\r\nimport type { Runtime } from './state';\r\nimport { activeSpan } from './tracing';\r\n\r\n/** Whether `app` is a Hono app (or one built the same way). */\r\nexport function isHono(app: any): boolean {\r\n return !!app && typeof app === 'object' && typeof app.fetch === 'function' && typeof app.router?.match === 'function' && Array.isArray(app.routes);\r\n}\r\n\r\n/** The route Hono matched for a request: the last handler's path that isn't a `use` middleware. */\r\nexport function honoRoute(app: any, request: Request): string | undefined {\r\n return safely(() => {\r\n const path = typeof app.getPath === 'function' ? app.getPath(request) : new URL(request.url).pathname;\r\n const method = request.method === 'HEAD' ? 'GET' : request.method;\r\n const [matched] = app.router.match(method, path) ?? [];\r\n if (!Array.isArray(matched) || !matched.length) return undefined;\r\n const routes = matched.map((entry: any) => entry?.[0]?.[1]).filter((route: any) => route && typeof route.path === 'string');\r\n const handler = [...routes].reverse().find((route: any) => route.method !== 'ALL') ?? routes[routes.length - 1];\r\n const route = handler?.path;\r\n return route && route !== '/*' && route !== '*' ? route : undefined;\r\n });\r\n}\r\n\r\nconst WRAPPED = Symbol.for('zharp.cloudflare.honoErrorHandler');\r\n\r\n/** Report what reaches the app's error handler (its own or Hono's default), then let it answer. */\r\nexport function hookHonoErrors(app: any, runtime: Runtime): void {\r\n safely(() => {\r\n const current = app.errorHandler;\r\n if (typeof current !== 'function' || current[WRAPPED]) return;\r\n const wrapped = function (this: unknown, error: unknown, c: unknown) {\r\n const status = (error as any)?.status;\r\n const answer = typeof (error as any)?.getResponse === 'function' && typeof status === 'number' && status < 500;\r\n if (!answer) runtime.report(error, false, { 'zharp.mechanism': 'hono' }, activeSpan());\r\n return current.call(this, error, c);\r\n };\r\n (wrapped as any)[WRAPPED] = true;\r\n app.errorHandler = wrapped;\r\n });\r\n}\r\n","/**\r\n * The entry points: Workers (`withZharp`), Durable Objects (`instrumentDurableObject`) and Pages\r\n * Functions (`zharpPagesPlugin`).\r\n *\r\n * Each invocation — a request, a cron run, a queue batch, an alarm, an RPC call — is one span\r\n * (SERVER, or CONSUMER for a queue) that continues the caller's `traceparent`. What it throws is\r\n * reported, as unhandled, and thrown on, so Cloudflare answers as it would have. Everything is\r\n * sent with `waitUntil` once the invocation's own `waitUntil` work has settled: the response\r\n * isn't held up.\r\n */\r\nimport { headerAttributes } from '@zharp/internal/headers';\r\nimport { redactUrl } from '@zharp/internal/bodies';\r\nimport { ROOT_CONTEXT, trace, type Context } from '@opentelemetry/api';\r\nimport { safely } from '../../browser/src/util';\r\nimport { instrumentEnv, wrapBinding } from './bindings';\r\nimport { hookHonoErrors, honoRoute, isHono } from './hono';\r\nimport { runtimeFor, type RequestState, type Runtime } from './state';\r\nimport { contextManager, parseTraceparent, SpanKind, SpanStatusCode, withRequest, ZharpSpan } from './tracing';\r\nimport type { ZharpConfig } from './types';\r\n\r\nconst WORKER = { service: 'worker', platform: 'cloudflare.workers' };\r\nconst PAGES = { service: 'pages', platform: 'cloudflare.pages' };\r\n\r\n/** A path as a route when nothing better is known: identifiers as `:id`, the way the dashboard groups them. */\r\nconst ID_SEGMENT = /^(\\d+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{16,}|[A-Za-z0-9_-]{24,})$/i;\r\nexport const routeFromPath = (path: string) => path.split('/').map((segment) => (ID_SEGMENT.test(segment) ? ':id' : segment)).join('/') || '/';\r\n\r\ninterface Invocation {\r\n name: string;\r\n kind: SpanKind;\r\n attributes: Record<string, unknown>;\r\n /** The caller's trace, from a `traceparent` header. */\r\n traceparent?: string | null;\r\n mechanism: string;\r\n}\r\n\r\ninterface Waiter {\r\n waitUntil(promise: Promise<unknown>): void;\r\n}\r\n\r\n/**\r\n * Run one invocation in its span and request state. `after` sees the result (a Response) before\r\n * the span ends.\r\n */\r\nasync function invoke<T>(\r\n runtime: Runtime,\r\n invocation: Invocation,\r\n waiter: Waiter | undefined,\r\n run: (state: RequestState, span: ZharpSpan) => Promise<T> | T,\r\n after?: (result: T, span: ZharpSpan) => void,\r\n): Promise<T> {\r\n const state = runtime.newRequest();\r\n const parent = parseTraceparent(invocation.traceparent);\r\n const span = new ZharpSpan(invocation.name, invocation.kind, parent, state, invocation.attributes as any);\r\n const ctx: Context = trace.setSpan(withRequest(ROOT_CONTEXT, state), span);\r\n try {\r\n const result = await contextManager.with(ctx, () => run(state, span));\r\n if (after) safely(() => after(result, span));\r\n return result;\r\n } catch (error) {\r\n runtime.report(error, false, { 'zharp.mechanism': invocation.mechanism }, span);\r\n span.setStatus({ code: SpanStatusCode.ERROR, message: (error as Error)?.message ?? String(error) });\r\n if (invocation.attributes['http.request.method'] && !span.attributes['http.response.status_code']) {\r\n span.setAttribute('http.response.status_code', 500);\r\n }\r\n throw error;\r\n } finally {\r\n span.end();\r\n const done = runtime.finish(state);\r\n if (waiter) safely(() => waiter.waitUntil(done));\r\n }\r\n}\r\n\r\n/** `ctx` whose `waitUntil` work is watched: what it rejects with is reported, and the flush waits for it. */\r\nfunction watchWaitUntil<C extends object>(ctx: C, state: RequestState, runtime: Runtime): C {\r\n if (!ctx || typeof (ctx as any).waitUntil !== 'function') return ctx;\r\n return new Proxy(ctx, {\r\n get(target, prop) {\r\n const member = Reflect.get(target, prop, target);\r\n if (prop === 'waitUntil' && typeof member === 'function') {\r\n return (promise: Promise<unknown>) => {\r\n const watched = Promise.resolve(promise).catch((error) => {\r\n runtime.report(error, false, { 'zharp.mechanism': 'waitUntil' });\r\n throw error;\r\n });\r\n state.pending.push(watched);\r\n return member.call(target, watched);\r\n };\r\n }\r\n return typeof member === 'function' ? member.bind(target) : member;\r\n },\r\n });\r\n}\r\n\r\n/** The span for an incoming request. */\r\nfunction requestInvocation(request: Request, runtime: Runtime, mechanism: string, extra: Record<string, unknown> = {}): Invocation {\r\n const url = safely(() => new URL(request.url));\r\n const method = request.method.toUpperCase();\r\n const cf = (request as any).cf as Record<string, unknown> | undefined;\r\n const headers = request.headers;\r\n return {\r\n name: `${method} ${routeFromPath(url?.pathname ?? '/')}`,\r\n kind: SpanKind.SERVER,\r\n traceparent: headers.get('traceparent'),\r\n mechanism,\r\n attributes: {\r\n 'faas.trigger': 'http',\r\n 'http.request.method': method,\r\n 'url.full': redactUrl(request.url),\r\n 'url.path': url?.pathname,\r\n 'url.scheme': url?.protocol.replace(':', ''),\r\n 'server.address': url?.hostname,\r\n 'user_agent.original': headers.get('user-agent') ?? undefined,\r\n 'client.address': headers.get('cf-connecting-ip') ?? undefined,\r\n 'cloudflare.ray_id': headers.get('cf-ray') ?? undefined,\r\n 'cloudflare.colo': typeof cf?.colo === 'string' ? cf.colo : undefined,\r\n 'geo.country.iso_code': typeof cf?.country === 'string' ? cf.country : undefined,\r\n ...(runtime.headers ? headerAttributes('request', headers, runtime.headers) : {}),\r\n ...extra,\r\n },\r\n };\r\n}\r\n\r\nfunction responseDone(runtime: Runtime) {\r\n return (response: unknown, span: ZharpSpan) => {\r\n if (!(response instanceof Response)) return;\r\n span.setAttribute('http.response.status_code', response.status);\r\n if (runtime.headers) span.setAttributes(headerAttributes('response', response.headers, runtime.headers));\r\n if (response.status >= 500) span.setStatus({ code: SpanStatusCode.ERROR, message: `HTTP ${response.status}` });\r\n };\r\n}\r\n\r\n// ── Workers ─────────────────────────────────────────────────────────────\r\n\r\ntype AnyHandler = Record<string, any>;\r\n\r\n/** Each handler of a Worker's default export, traced. */\r\nfunction workerMethod(name: string, original: Function, thisArg: unknown, config: ZharpConfig | undefined, app: unknown) {\r\n return function (this: unknown, ...args: any[]) {\r\n const self = thisArg ?? this;\r\n const env = name === 'fetch' || name === 'scheduled' || name === 'queue' || name === 'email' || name === 'tail' || name === 'trace' ? args[1] : undefined;\r\n const ctx = args[2];\r\n const runtime = env !== undefined ? runtimeFor(env, config, WORKER) : null;\r\n if (!runtime) return original.apply(self, args);\r\n const wrappedEnv = instrumentEnv(env, runtime);\r\n\r\n if (name === 'fetch') {\r\n const request = args[0] as Request;\r\n if (isHono(app)) hookHonoErrors(app, runtime);\r\n const invocation = requestInvocation(request, runtime, 'cloudflare.fetch');\r\n return invoke(runtime, invocation, ctx, (state) => original.call(self, request, wrappedEnv, watchWaitUntil(ctx, state, runtime), ...args.slice(3)), (response, span) => {\r\n responseDone(runtime)(response, span);\r\n const route = isHono(app) ? honoRoute(app, request) : undefined;\r\n if (route) {\r\n span.setAttribute('http.route', route);\r\n span.updateName(`${request.method.toUpperCase()} ${route}`);\r\n }\r\n });\r\n }\r\n\r\n if (name === 'scheduled') {\r\n const controller = args[0] ?? {};\r\n const invocation: Invocation = {\r\n name: `cron ${controller.cron ?? ''}`.trim(),\r\n kind: SpanKind.SERVER,\r\n mechanism: 'cloudflare.scheduled',\r\n attributes: {\r\n 'faas.trigger': 'timer',\r\n 'faas.cron': controller.cron,\r\n 'faas.time': typeof controller.scheduledTime === 'number' ? new Date(controller.scheduledTime).toISOString() : undefined,\r\n },\r\n };\r\n return invoke(runtime, invocation, ctx, (state) => original.call(self, controller, wrappedEnv, watchWaitUntil(ctx, state, runtime)));\r\n }\r\n\r\n if (name === 'queue') {\r\n const batch = args[0] ?? {};\r\n const invocation: Invocation = {\r\n name: `${batch.queue ?? 'queue'} process`,\r\n kind: SpanKind.CONSUMER,\r\n mechanism: 'cloudflare.queue',\r\n attributes: {\r\n 'faas.trigger': 'pubsub',\r\n 'messaging.system': 'cloudflare_queues',\r\n 'messaging.operation.type': 'process',\r\n 'messaging.destination.name': batch.queue,\r\n 'messaging.batch.message_count': Array.isArray(batch.messages) ? batch.messages.length : undefined,\r\n },\r\n };\r\n return invoke(runtime, invocation, ctx, (state) => original.call(self, batch, wrappedEnv, watchWaitUntil(ctx, state, runtime)));\r\n }\r\n\r\n // email, tail and the rest: one span named after the handler.\r\n const invocation: Invocation = { name, kind: SpanKind.SERVER, mechanism: `cloudflare.${name}`, attributes: { 'faas.trigger': 'other' } };\r\n return invoke(runtime, invocation, ctx, (state) => original.call(self, args[0], wrappedEnv, watchWaitUntil(ctx, state, runtime), ...args.slice(3)));\r\n };\r\n}\r\n\r\nconst HANDLERS = new Set(['fetch', 'scheduled', 'queue', 'email', 'tail', 'trace', 'test']);\r\n\r\n/**\r\n * A Worker's default export, traced:\r\n *\r\n * export default withZharp((env) => ({ key: env.ZHARP_KEY }), {\r\n * async fetch(request, env, ctx) { … },\r\n * async scheduled(controller, env, ctx) { … },\r\n * });\r\n *\r\n * The handler can be an object (`{ fetch, scheduled, queue }`), a Hono app, or a\r\n * `WorkerEntrypoint` class. With no config, settings come from `env` (`ZHARP_KEY`, …).\r\n */\r\nexport function withZharp<H>(handler: H): H;\r\nexport function withZharp<H, E = any>(config: ZharpConfig<E> | undefined, handler: H): H;\r\nexport function withZharp(configOrHandler: any, maybeHandler?: any): any {\r\n const [config, handler] = maybeHandler === undefined ? [undefined, configOrHandler] : [configOrHandler, maybeHandler];\r\n if (typeof handler === 'function') return instrumentClass(handler, config, WORKER, 'worker');\r\n if (!handler || typeof handler !== 'object') return handler;\r\n const wrapped = new Map<string, Function>();\r\n return new Proxy(handler, {\r\n get(target, prop, receiver) {\r\n const value = Reflect.get(target, prop, receiver);\r\n if (typeof prop !== 'string' || !HANDLERS.has(prop) || typeof value !== 'function') return value;\r\n let fn = wrapped.get(prop);\r\n if (!fn) wrapped.set(prop, (fn = workerMethod(prop, value, target, config, target)));\r\n return fn;\r\n },\r\n });\r\n}\r\n\r\n// ── Durable Objects and WorkerEntrypoint classes ────────────────────────\r\n\r\nconst WEBSOCKET: Record<string, string> = { webSocketMessage: 'websocket message', webSocketClose: 'websocket close', webSocketError: 'websocket error' };\r\nconst NOT_RPC = new Set(['constructor', 'then', 'toJSON', 'dup', 'ctx', 'env', 'state', 'storage']);\r\n\r\n/**\r\n * A Durable Object class, traced: each `fetch`, RPC method, `alarm` and WebSocket message is a\r\n * span, and errors are reported.\r\n *\r\n * export const Cart = instrumentDurableObject(CartObject);\r\n *\r\n * Settings come from `config`, else from the config given to `withZharp`, else from `env`.\r\n */\r\nexport function instrumentDurableObject<C extends new (...args: any[]) => any>(cls: C, config?: ZharpConfig): C {\r\n return instrumentClass(cls, config, WORKER, 'durable-object');\r\n}\r\n\r\nfunction instrumentClass<C extends new (...args: any[]) => any>(cls: C, config: ZharpConfig | undefined, defaults: typeof WORKER, kind: 'durable-object' | 'worker'): C {\r\n return new Proxy(cls, {\r\n construct(target, args, newTarget) {\r\n const [state, env] = args;\r\n const runtime = runtimeFor(env, config, defaults);\r\n if (!runtime) return Reflect.construct(target, args, newTarget);\r\n const instance = Reflect.construct(target, [state, instrumentEnv(env, runtime), ...args.slice(2)], newTarget);\r\n const className = (target as any).name || (kind === 'durable-object' ? 'DurableObject' : 'Worker');\r\n const id = safely(() => state?.id?.toString?.()) as string | undefined;\r\n const wrapped = new Map<PropertyKey, Function>();\r\n\r\n const method = (prop: string, original: Function) =>\r\n function (this: unknown, ...callArgs: any[]) {\r\n const base = {\r\n 'cloudflare.durable_object.class': kind === 'durable-object' ? className : undefined,\r\n 'cloudflare.durable_object.id': kind === 'durable-object' ? id : undefined,\r\n };\r\n let invocation: Invocation;\r\n let after: ((result: any, span: ZharpSpan) => void) | undefined;\r\n if (prop === 'fetch' && callArgs[0] instanceof Request) {\r\n invocation = requestInvocation(callArgs[0], runtime, kind === 'durable-object' ? 'cloudflare.durable_object' : 'cloudflare.fetch', base);\r\n after = responseDone(runtime);\r\n } else if (prop === 'alarm') {\r\n invocation = { name: `${className} alarm`, kind: SpanKind.SERVER, mechanism: 'cloudflare.alarm', attributes: { 'faas.trigger': 'timer', ...base } };\r\n } else if (WEBSOCKET[prop]) {\r\n invocation = { name: `${className} ${WEBSOCKET[prop]}`, kind: SpanKind.SERVER, mechanism: 'cloudflare.websocket', attributes: { 'faas.trigger': 'other', ...base } };\r\n } else if (prop === 'scheduled' || prop === 'queue') {\r\n invocation = {\r\n name: prop === 'scheduled' ? `cron ${callArgs[0]?.cron ?? ''}`.trim() : `${callArgs[0]?.queue ?? 'queue'} process`,\r\n kind: prop === 'queue' ? SpanKind.CONSUMER : SpanKind.SERVER,\r\n mechanism: `cloudflare.${prop}`,\r\n attributes: { 'faas.trigger': prop === 'queue' ? 'pubsub' : 'timer', 'faas.cron': callArgs[0]?.cron, 'messaging.destination.name': callArgs[0]?.queue },\r\n };\r\n } else {\r\n invocation = {\r\n name: `${className}.${prop}`,\r\n kind: SpanKind.SERVER,\r\n mechanism: 'cloudflare.rpc',\r\n attributes: { 'rpc.system': 'cloudflare_rpc', 'rpc.service': className, 'rpc.method': prop, ...base },\r\n };\r\n }\r\n const waiter: Waiter | undefined = typeof state?.waitUntil === 'function' ? state : undefined;\r\n // On the object itself, not this proxy: a method calling another through `this` is not a\r\n // new invocation, and private fields work.\r\n return invoke(runtime, invocation, waiter, () => original.apply(instance, callArgs), after);\r\n };\r\n\r\n return new Proxy(instance, {\r\n get(obj, prop, receiver) {\r\n const value = Reflect.get(obj, prop, receiver);\r\n if (typeof prop !== 'string' || typeof value !== 'function' || NOT_RPC.has(prop) || prop.startsWith('_')) return value;\r\n // Only what the class (or a parent below DurableObject) defines: not Object's own methods.\r\n if (value === (Object.prototype as any)[prop]) return value;\r\n let fn = wrapped.get(prop);\r\n if (!fn) wrapped.set(prop, (fn = method(prop, value)));\r\n return fn;\r\n },\r\n });\r\n },\r\n });\r\n}\r\n\r\n// ── Pages Functions ─────────────────────────────────────────────────────\r\n\r\ninterface PagesContext {\r\n request: Request;\r\n env: Record<string, unknown>;\r\n waitUntil(promise: Promise<unknown>): void;\r\n next(input?: Request | string, init?: RequestInit): Promise<Response>;\r\n functionPath?: string;\r\n [key: string]: unknown;\r\n}\r\n\r\n/**\r\n * Pages Functions: in `functions/_middleware.ts`,\r\n *\r\n * export const onRequest = zharpPagesPlugin((context) => ({ key: context.env.ZHARP_KEY }));\r\n *\r\n * Every request through the project's Functions is a span, errors they throw are reported, and\r\n * D1, KV, R2 and the rest of `context.env` are traced for the functions after it.\r\n */\r\nexport function zharpPagesPlugin<E = any>(config?: ZharpConfig<E> | ((context: PagesContext) => ReturnType<Extract<ZharpConfig<E>, Function>>)) {\r\n return async (context: PagesContext): Promise<Response> => {\r\n const settingsFrom = typeof config === 'function' ? (env: E) => (config as Function)({ ...context, env }) : config;\r\n const runtime = runtimeFor(context.env, settingsFrom as ZharpConfig | undefined, PAGES);\r\n if (!runtime) return context.next();\r\n // The functions after this one get their own context, built from the same env object.\r\n safely(() => {\r\n for (const key of Object.keys(context.env)) {\r\n const wrapped = wrapBinding(context.env[key], key, runtime);\r\n if (wrapped) context.env[key] = wrapped;\r\n }\r\n });\r\n const invocation = requestInvocation(context.request, runtime, 'cloudflare.pages');\r\n return invoke(runtime, invocation, context, (state) => {\r\n // Their waitUntil work, watched like a Worker's.\r\n const watched = watchWaitUntil({ waitUntil: context.waitUntil.bind(context) }, state, runtime);\r\n safely(() => {\r\n (context as any).waitUntil = watched.waitUntil;\r\n });\r\n return context.next();\r\n }, responseDone(runtime));\r\n };\r\n}\r\n","/**\r\n * @zharp/cloudflare: errors, traces, D1 queries and (when asked for) logs from Cloudflare\r\n * Workers, Durable Objects and Pages Functions, sent to Zharp as OTLP.\r\n *\r\n * import { withZharp } from '@zharp/cloudflare';\r\n *\r\n * export default withZharp((env) => ({ key: env.ZHARP_KEY }), {\r\n * async fetch(request, env, ctx) { … },\r\n * });\r\n */\r\nimport { SpanStatusCode } from '@opentelemetry/api';\r\nimport { asError } from '../../browser/src/instrument/errors';\r\nimport { safely } from '../../browser/src/util';\r\nimport { currentRuntime, setTag, setUser, type Level } from './state';\r\nimport { activeSpan, startSpan as startZharpSpan, withSpan } from './tracing';\r\nimport type { Attributes, ZharpUser } from './types';\r\n\r\nexport { withZharp, instrumentDurableObject, zharpPagesPlugin } from './handlers';\r\nexport type { Attributes, ZharpCloudflareOptions, ZharpConfig, ZharpUser } from './types';\r\nexport { VERSION } from './version';\r\n\r\ntype LogFn = (message: unknown, attributes?: Attributes) => void;\r\n\r\n/** A span made with `Zharp.startSpan`. */\r\nexport interface ZharpSpanHandle {\r\n readonly traceId: string;\r\n readonly spanId: string;\r\n setAttribute(key: string, value: unknown): ZharpSpanHandle;\r\n setAttributes(attributes: Attributes): ZharpSpanHandle;\r\n}\r\n\r\nconst log = (level: Level): LogFn => (message, attributes) => currentRuntime()?.emit(level, message, attributes);\r\n\r\nconst noopSpan: ZharpSpanHandle = {\r\n traceId: '',\r\n spanId: '',\r\n setAttribute: () => noopSpan,\r\n setAttributes: () => noopSpan,\r\n};\r\n\r\n/**\r\n * The API, as in the other Zharp JavaScript SDKs. Inside a request, tags and the user belong to\r\n * that request only; outside one (at module scope) they apply to everything this isolate sends.\r\n */\r\nexport const Zharp = {\r\n /** Report an error you caught. Sent as handled, grouped with its other occurrences. */\r\n captureError(error: unknown, attributes?: Attributes): void {\r\n currentRuntime()?.report(error, true, attributes);\r\n },\r\n\r\n /** Who the request is for: `enduser.id` (and email, name) on its spans, logs and errors. */\r\n setUser(user: ZharpUser | null): void {\r\n safely(() => setUser(user));\r\n },\r\n\r\n /** An attribute on the request's spans, logs and errors. `null` removes it. */\r\n setTag(key: string, value: string | number | boolean | null | undefined): void {\r\n safely(() => setTag(key, value));\r\n },\r\n\r\n /** Logs, sent whatever `ZHARP_LOGS` says, with the active request's trace. */\r\n log: {\r\n trace: log('trace'),\r\n debug: log('debug'),\r\n info: log('info'),\r\n warn: log('warn'),\r\n error: log('error'),\r\n fatal: log('fatal'),\r\n } as Record<Level, LogFn>,\r\n\r\n /**\r\n * Run `fn` in a span named `name`. Fetches, queries and logs inside it belong to it; a promise\r\n * it returns ends the span when it settles. Errors pass through unchanged.\r\n */\r\n startSpan<T>(name: string, fn: (span: ZharpSpanHandle) => T, attributes?: Attributes): T {\r\n if (!currentRuntime()) return fn(noopSpan);\r\n const span = startZharpSpan(name, { attributes: attributes as any });\r\n const fail = (error: unknown) => {\r\n span.setStatus({ code: SpanStatusCode.ERROR, message: asError(error).message });\r\n span.end();\r\n };\r\n try {\r\n const result = withSpan(span, () => fn(span));\r\n if (result && typeof (result as any).then === 'function') {\r\n return (result as any).then(\r\n (value: unknown) => {\r\n span.end();\r\n return value;\r\n },\r\n (error: unknown) => {\r\n fail(error);\r\n throw error;\r\n },\r\n );\r\n }\r\n span.end();\r\n return result;\r\n } catch (error) {\r\n fail(error);\r\n throw error;\r\n }\r\n },\r\n\r\n /** The active span's trace ID, e.g. to show on an error page. */\r\n get traceId(): string | undefined {\r\n return activeSpan()?.traceId;\r\n },\r\n\r\n /** Send everything queued now. The wrappers already do this at the end of each request. */\r\n async flush(): Promise<void> {\r\n await currentRuntime()?.flush();\r\n },\r\n};\r\n\r\nexport default Zharp;\r\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,73 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zharp/cloudflare",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Zharp Application Monitoring for Cloudflare Workers, Durable Objects and Pages Functions — errors, traces, D1 queries and logs",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"module": "dist/index.mjs",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"import": {
|
|
11
|
+
"types": "./dist/index.d.mts",
|
|
12
|
+
"default": "./dist/index.mjs"
|
|
13
|
+
},
|
|
14
|
+
"require": {
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"default": "./dist/index.js"
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
"./package.json": "./package.json"
|
|
20
|
+
},
|
|
21
|
+
"sideEffects": false,
|
|
22
|
+
"files": [
|
|
23
|
+
"dist"
|
|
24
|
+
],
|
|
25
|
+
"keywords": [
|
|
26
|
+
"zharp",
|
|
27
|
+
"cloudflare",
|
|
28
|
+
"cloudflare-workers",
|
|
29
|
+
"workers",
|
|
30
|
+
"durable-objects",
|
|
31
|
+
"pages-functions",
|
|
32
|
+
"hono",
|
|
33
|
+
"d1",
|
|
34
|
+
"apm",
|
|
35
|
+
"error-tracking",
|
|
36
|
+
"tracing",
|
|
37
|
+
"opentelemetry",
|
|
38
|
+
"traceparent",
|
|
39
|
+
"monitoring",
|
|
40
|
+
"observability"
|
|
41
|
+
],
|
|
42
|
+
"license": "MIT",
|
|
43
|
+
"repository": {
|
|
44
|
+
"type": "git",
|
|
45
|
+
"url": "git+https://github.com/zharp-io/zharp-javascript-lib.git",
|
|
46
|
+
"directory": "packages/cloudflare"
|
|
47
|
+
},
|
|
48
|
+
"homepage": "https://zharp.io/docs/sdks/cloudflare",
|
|
49
|
+
"bugs": "https://github.com/zharp-io/zharp-javascript-lib/issues",
|
|
50
|
+
"publishConfig": {
|
|
51
|
+
"access": "public"
|
|
52
|
+
},
|
|
53
|
+
"dependencies": {
|
|
54
|
+
"@opentelemetry/api": "^1.9.0"
|
|
55
|
+
},
|
|
56
|
+
"devDependencies": {
|
|
57
|
+
"@cloudflare/vitest-plugin": "^1.9.0",
|
|
58
|
+
"@types/node": "^25.9.3",
|
|
59
|
+
"hono": "^4.13.20",
|
|
60
|
+
"tsup": "^8.5.1",
|
|
61
|
+
"typescript": "^5.9.3",
|
|
62
|
+
"vitest": "^4.1.12",
|
|
63
|
+
"wrangler": "^4.166.0",
|
|
64
|
+
"@zharp/internal": "0.0.0"
|
|
65
|
+
},
|
|
66
|
+
"scripts": {
|
|
67
|
+
"build": "tsup",
|
|
68
|
+
"dev": "tsup --watch",
|
|
69
|
+
"typecheck": "tsc --noEmit",
|
|
70
|
+
"test": "vitest run",
|
|
71
|
+
"size": "node scripts/size.mjs"
|
|
72
|
+
}
|
|
6
73
|
}
|