@alwaysmeticulous/backend-recorder-workerd 2.326.0 → 2.329.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.
Files changed (82) hide show
  1. package/README.md +36 -0
  2. package/dist/binding-patch.js +2 -2
  3. package/dist/binding-patch.js.map +1 -1
  4. package/dist/body-capture.js +2 -2
  5. package/dist/body-capture.js.map +1 -1
  6. package/dist/capture-buffer.js +2 -2
  7. package/dist/capture-buffer.js.map +1 -1
  8. package/dist/context.js +2 -2
  9. package/dist/context.js.map +1 -1
  10. package/dist/coverage/coverage.types.d.ts +32 -0
  11. package/dist/coverage/replay-coverage.js +84 -0
  12. package/dist/coverage/replay-coverage.js.map +1 -0
  13. package/dist/coverage/runtime.d.ts +70 -0
  14. package/dist/coverage/runtime.js +138 -0
  15. package/dist/coverage/runtime.js.map +1 -0
  16. package/dist/error-capture.js +2 -2
  17. package/dist/error-capture.js.map +1 -1
  18. package/dist/fetch-patch.js +2 -2
  19. package/dist/fetch-patch.js.map +1 -1
  20. package/dist/index.d.ts +5 -2
  21. package/dist/index.js +6 -4
  22. package/dist/index.js.map +1 -1
  23. package/dist/kv-capture.js +2 -2
  24. package/dist/kv-capture.js.map +1 -1
  25. package/dist/kv-patch.js +2 -2
  26. package/dist/kv-patch.js.map +1 -1
  27. package/dist/log.js +2 -2
  28. package/dist/log.js.map +1 -1
  29. package/dist/original-fetch.js +2 -2
  30. package/dist/original-fetch.js.map +1 -1
  31. package/dist/outbound-capture.js +2 -2
  32. package/dist/outbound-capture.js.map +1 -1
  33. package/dist/pages-function.js +2 -2
  34. package/dist/pages-function.js.map +1 -1
  35. package/dist/postgres/capture.js +2 -2
  36. package/dist/postgres/capture.js.map +1 -1
  37. package/dist/postgres/with-meticulous-postgres.js +2 -2
  38. package/dist/postgres/with-meticulous-postgres.js.map +1 -1
  39. package/dist/protocol.d.ts +48 -18
  40. package/dist/protocol.js +22 -6
  41. package/dist/protocol.js.map +1 -1
  42. package/dist/provisional-session-id.js +2 -2
  43. package/dist/provisional-session-id.js.map +1 -1
  44. package/dist/publish-session-id.js +2 -2
  45. package/dist/publish-session-id.js.map +1 -1
  46. package/dist/publish-shim-version.js +37 -0
  47. package/dist/publish-shim-version.js.map +1 -0
  48. package/dist/redact-body.js +2 -2
  49. package/dist/redact-body.js.map +1 -1
  50. package/dist/replay-fetch.js +15 -12
  51. package/dist/replay-fetch.js.map +1 -1
  52. package/dist/replay-log-tagging.js +57 -0
  53. package/dist/replay-log-tagging.js.map +1 -0
  54. package/dist/replay-sidecar-url.js +2 -2
  55. package/dist/replay-sidecar-url.js.map +1 -1
  56. package/dist/sidecar-client.js +47 -6
  57. package/dist/sidecar-client.js.map +1 -1
  58. package/dist/sidecar-transport.js +2 -2
  59. package/dist/sidecar-transport.js.map +1 -1
  60. package/dist/spans/attributes.js +2 -2
  61. package/dist/spans/attributes.js.map +1 -1
  62. package/dist/spans/readable-span.js +2 -2
  63. package/dist/spans/readable-span.js.map +1 -1
  64. package/dist/spans/serialize-span.js +2 -2
  65. package/dist/spans/serialize-span.js.map +1 -1
  66. package/dist/spans/span-builder.js +2 -2
  67. package/dist/spans/span-builder.js.map +1 -1
  68. package/dist/spans/url-redaction.js +2 -2
  69. package/dist/spans/url-redaction.js.map +1 -1
  70. package/dist/version.d.ts +14 -0
  71. package/dist/version.js +18 -0
  72. package/dist/version.js.map +1 -0
  73. package/dist/virtual-clock.js +2 -2
  74. package/dist/virtual-clock.js.map +1 -1
  75. package/dist/virtual-random.js +47 -20
  76. package/dist/virtual-random.js.map +1 -1
  77. package/dist/vite/index.d.ts +62 -0
  78. package/dist/vite/index.js +6764 -0
  79. package/dist/vite/index.js.map +1 -0
  80. package/dist/with-meticulous.js +0 -0
  81. package/dist/with-meticulous.js.map +1 -1
  82. package/package.json +5 -2
@@ -1 +1 @@
1
- {"version":3,"file":"with-meticulous-postgres.js","sources":["../../src/postgres/with-meticulous-postgres.ts"],"sourcesContent":["import { type RequestCaptureContext, requestCaptureContext } from \"../context\";\nimport { warnOnce } from \"../log\";\nimport type { PostgresQueryEvent } from \"../protocol\";\nimport {\n isSupportedPostgresJsQuery,\n MAX_POSTGRES_JS_RESULT_SIZE,\n type PostgresJsQueryLike,\n reconstructQueryText,\n resolveRowMode,\n serializePostgresJsArgs,\n serializePostgresJsError,\n serializePostgresJsResult,\n} from \"./capture\";\n\n/**\n * Records postgres.js queries a deployed Worker makes — typically over Hyperdrive, which is the\n * only way a Worker reaches Postgres.\n *\n * There is no seam to patch automatically here. The Node recorder can hook Node's module loader\n * to patch `postgres/{src,cjs/src,cf/src}/query.js`, but a Worker is a single bundle: `postgres`\n * was inlined at build time and never passes through a loader. So the app hands us its client:\n *\n * const sql = withMeticulousPostgres(postgres(env.HYPERDRIVE.connectionString));\n *\n * Every postgres.js query funnels through one internal method, `Query.prototype.handle`, and this\n * reaches that shared prototype *through the instance* — via a throwaway query, which is free\n * because postgres.js queries are lazy and nothing executes until awaited. One call therefore also\n * covers read-replica clients and any other client in the isolate.\n *\n * Apply it **outermost** if something else also wraps the client (Sentry's\n * `instrumentPostgresJsSql`, a logging proxy): those wrappers return a proxy whose `handle` is\n * still the shared prototype's, so ordering does not change what is captured — but keeping ours\n * outermost matches the Node recorder's contract and stays correct if that ever changes.\n *\n * Record-only, deliberately. A Worker recording is replayed against the app running under Node,\n * where `@alwaysmeticulous/backend-recorder-js` serves these queries from its own mock store —\n * which is why the captured attributes here are exactly the ones that store reads. Outside a\n * recorded request this is a complete pass-through, so it is safe to leave in deployed code.\n *\n * Returns the client unchanged; the patch is on the prototype.\n */\nexport const withMeticulousPostgres = <Sql>(sql: Sql): Sql => {\n try {\n const prototype = findQueryPrototype(sql);\n if (prototype === undefined) {\n warnOnce(\n \"postgres-wrapper-unsupported\",\n \"withMeticulousPostgres could not reach postgres.js' Query prototype — queries will not be recorded.\",\n );\n return sql;\n }\n patchHandle(prototype);\n } catch (error) {\n warnOnce(\n \"postgres-wrapper-failed\",\n \"withMeticulousPostgres failed — queries will not be recorded.\",\n error,\n );\n }\n return sql;\n};\n\n// Symbol.for so a second copy of the shim (e.g. bundled twice) still detects the patch.\nconst HANDLE_PATCHED = Symbol.for(\"meticulous.workerd.postgresJsPatched\");\n\ntype HandleFn = (this: PostgresJsQueryLike) => unknown;\n\n/**\n * The `Query` prototype, reached by building a query and reading its prototype.\n *\n * `sql.unsafe` is used rather than a tagged template because it takes the text as a plain\n * argument: no interpolation, and postgres.js does not touch a connection until the query is\n * awaited, which nothing here does. The query is discarded.\n */\nconst findQueryPrototype = (sql: unknown): object | undefined => {\n const unsafe = (sql as { unsafe?: unknown } | null)?.unsafe;\n if (typeof unsafe !== \"function\") {\n return undefined;\n }\n const probe: unknown = (unsafe as (text: string) => unknown).call(\n sql,\n \"select 1\",\n );\n if (probe === null || typeof probe !== \"object\") {\n return undefined;\n }\n const prototype = Object.getPrototypeOf(probe) as object | null;\n if (prototype === null) {\n return undefined;\n }\n const descriptor = Object.getOwnPropertyDescriptor(prototype, \"handle\");\n return descriptor !== undefined &&\n typeof descriptor.value === \"function\" &&\n descriptor.configurable === true\n ? prototype\n : undefined;\n};\n\nconst patchHandle = (prototype: object): void => {\n const descriptor = Object.getOwnPropertyDescriptor(prototype, \"handle\");\n const original = descriptor?.value as HandleFn | undefined;\n if (\n original === undefined ||\n (original as unknown as Record<symbol, unknown>)[HANDLE_PATCHED] === true\n ) {\n return;\n }\n\n const patched = function (this: PostgresJsQueryLike): unknown {\n // `handle` is reachable from then/catch/finally/execute, so it can be called more than once\n // for one query; postgres.js itself no-ops on the repeats via `executed`. Bail before\n // instrumenting so a query is never captured twice.\n if (this.executed || !isSupportedPostgresJsQuery(this)) {\n return original.call(this);\n }\n const ctx = requestCaptureContext.getStore();\n if (!ctx || ctx.mode !== \"record\") {\n return original.call(this);\n }\n try {\n captureQuery(ctx, this);\n } catch (error) {\n warnOnce(\n \"postgres-capture\",\n \"Failed to capture a postgres.js query.\",\n error,\n );\n }\n return original.call(this);\n };\n Object.defineProperty(patched, HANDLE_PATCHED, {\n value: true,\n enumerable: false,\n configurable: true,\n });\n Object.defineProperty(prototype, \"handle\", {\n value: patched,\n writable: true,\n enumerable: false,\n configurable: true,\n });\n};\n\n/**\n * Wraps the query's own `resolve`/`reject` so the outcome is captured without the query being\n * awaited here — the same trick the Node instrumentation uses, and the only place a query's input\n * and its result are both visible.\n */\nconst captureQuery = (\n ctx: RequestCaptureContext,\n query: PostgresJsQueryLike,\n): void => {\n const queryText = reconstructQueryText(query.strings);\n if (queryText === undefined) {\n return;\n }\n const startTimeMs = Date.now();\n const base = {\n kind: \"postgres\" as const,\n requestId: ctx.requestId,\n ...(ctx.frontendSessionId !== undefined\n ? { frontendSessionId: ctx.frontendSessionId }\n : {}),\n traceId: ctx.traceId,\n serverSpanId: ctx.serverSpanId,\n queryText,\n params: serializePostgresJsArgs(query.args),\n rowMode: resolveRowMode(query.isRaw),\n startTimeMs,\n };\n\n const report = (outcome: Partial<PostgresQueryEvent>): void => {\n try {\n ctx.buffer.add({ ...base, ...outcome, endTimeMs: Date.now() });\n } catch (error) {\n warnOnce(\n \"postgres-report\",\n \"Failed to report a postgres.js query.\",\n error,\n );\n }\n };\n\n const originalResolve = query.resolve;\n const originalReject = query.reject;\n query.resolve = (result: unknown) => {\n // A result that cannot be serialized is simply not captured → it misses during replay and\n // errors hermetically, rather than serving something wrong.\n let json: string | undefined;\n try {\n json = serializePostgresJsResult(result);\n } catch {\n json = undefined;\n }\n report(\n json === undefined\n ? {}\n : {\n result: {\n body:\n json.length > MAX_POSTGRES_JS_RESULT_SIZE\n ? json.slice(0, MAX_POSTGRES_JS_RESULT_SIZE)\n : json,\n truncated: json.length > MAX_POSTGRES_JS_RESULT_SIZE,\n },\n },\n );\n return originalResolve.call(query, result);\n };\n query.reject = (error: unknown) => {\n let errorJson: string | undefined;\n try {\n errorJson = serializePostgresJsError(error);\n } catch {\n errorJson = undefined;\n }\n report(errorJson === undefined ? {} : { errorJson });\n return originalReject.call(query, error);\n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EACzC,OAAO;EACP,UAAU;EACV,YAAY;EACZ,cAAc;EACf,CAAC;;;;;;;AAQJ,MAAM,gBACJ,KACA,UACS;CACT,MAAM,YAAY,qBAAqB,MAAM,QAAQ;AACrD,KAAI,cAAc,KAAA,EAChB;CAEF,MAAM,cAAc,KAAK,KAAK;CAC9B,MAAM,OAAO;EACX,MAAM;EACN,WAAW,IAAI;EACf,GAAI,IAAI,sBAAsB,KAAA,IAC1B,EAAE,mBAAmB,IAAI,mBAAmB,GAC5C,EAAE;EACN,SAAS,IAAI;EACb,cAAc,IAAI;EAClB;EACA,QAAQ,wBAAwB,MAAM,KAAK;EAC3C,SAAS,eAAe,MAAM,MAAM;EACpC;EACD;CAED,MAAM,UAAU,YAA+C;AAC7D,MAAI;AACF,OAAI,OAAO,IAAI;IAAE,GAAG;IAAM,GAAG;IAAS,WAAW,KAAK,KAAK;IAAE,CAAC;WACvD,OAAO;AACd,YACE,mBACA,yCACA,MACD;;;CAIL,MAAM,kBAAkB,MAAM;CAC9B,MAAM,iBAAiB,MAAM;AAC7B,OAAM,WAAW,WAAoB;EAGnC,IAAI;AACJ,MAAI;AACF,UAAO,0BAA0B,OAAO;UAClC;AACN,UAAO,KAAA;;AAET,SACE,SAAS,KAAA,IACL,EAAE,GACF,EACE,QAAQ;GACN,MACE,KAAK,SAAA,SACD,KAAK,MAAM,GAAG,4BAA4B,GAC1C;GACN,WAAW,KAAK,SAAS;GAC1B,EACF,CACN;AACD,SAAO,gBAAgB,KAAK,OAAO,OAAO;;AAE5C,OAAM,UAAU,UAAmB;EACjC,IAAI;AACJ,MAAI;AACF,eAAY,yBAAyB,MAAM;UACrC;AACN,eAAY,KAAA;;AAEd,SAAO,cAAc,KAAA,IAAY,EAAE,GAAG,EAAE,WAAW,CAAC;AACpD,SAAO,eAAe,KAAK,OAAO,MAAM","debugId":"7437e682-9879-55d9-aa51-34f2920d26d3"}
1
+ {"version":3,"file":"with-meticulous-postgres.js","sources":["../../src/postgres/with-meticulous-postgres.ts"],"sourcesContent":["import { type RequestCaptureContext, requestCaptureContext } from \"../context\";\nimport { warnOnce } from \"../log\";\nimport type { PostgresQueryEvent } from \"../protocol\";\nimport {\n isSupportedPostgresJsQuery,\n MAX_POSTGRES_JS_RESULT_SIZE,\n type PostgresJsQueryLike,\n reconstructQueryText,\n resolveRowMode,\n serializePostgresJsArgs,\n serializePostgresJsError,\n serializePostgresJsResult,\n} from \"./capture\";\n\n/**\n * Records postgres.js queries a deployed Worker makes — typically over Hyperdrive, which is the\n * only way a Worker reaches Postgres.\n *\n * There is no seam to patch automatically here. The Node recorder can hook Node's module loader\n * to patch `postgres/{src,cjs/src,cf/src}/query.js`, but a Worker is a single bundle: `postgres`\n * was inlined at build time and never passes through a loader. So the app hands us its client:\n *\n * const sql = withMeticulousPostgres(postgres(env.HYPERDRIVE.connectionString));\n *\n * Every postgres.js query funnels through one internal method, `Query.prototype.handle`, and this\n * reaches that shared prototype *through the instance* — via a throwaway query, which is free\n * because postgres.js queries are lazy and nothing executes until awaited. One call therefore also\n * covers read-replica clients and any other client in the isolate.\n *\n * Apply it **outermost** if something else also wraps the client (Sentry's\n * `instrumentPostgresJsSql`, a logging proxy): those wrappers return a proxy whose `handle` is\n * still the shared prototype's, so ordering does not change what is captured — but keeping ours\n * outermost matches the Node recorder's contract and stays correct if that ever changes.\n *\n * Record-only, deliberately. A Worker recording is replayed against the app running under Node,\n * where `@alwaysmeticulous/backend-recorder-js` serves these queries from its own mock store —\n * which is why the captured attributes here are exactly the ones that store reads. Outside a\n * recorded request this is a complete pass-through, so it is safe to leave in deployed code.\n *\n * Returns the client unchanged; the patch is on the prototype.\n */\nexport const withMeticulousPostgres = <Sql>(sql: Sql): Sql => {\n try {\n const prototype = findQueryPrototype(sql);\n if (prototype === undefined) {\n warnOnce(\n \"postgres-wrapper-unsupported\",\n \"withMeticulousPostgres could not reach postgres.js' Query prototype — queries will not be recorded.\",\n );\n return sql;\n }\n patchHandle(prototype);\n } catch (error) {\n warnOnce(\n \"postgres-wrapper-failed\",\n \"withMeticulousPostgres failed — queries will not be recorded.\",\n error,\n );\n }\n return sql;\n};\n\n// Symbol.for so a second copy of the shim (e.g. bundled twice) still detects the patch.\nconst HANDLE_PATCHED = Symbol.for(\"meticulous.workerd.postgresJsPatched\");\n\ntype HandleFn = (this: PostgresJsQueryLike) => unknown;\n\n/**\n * The `Query` prototype, reached by building a query and reading its prototype.\n *\n * `sql.unsafe` is used rather than a tagged template because it takes the text as a plain\n * argument: no interpolation, and postgres.js does not touch a connection until the query is\n * awaited, which nothing here does. The query is discarded.\n */\nconst findQueryPrototype = (sql: unknown): object | undefined => {\n const unsafe = (sql as { unsafe?: unknown } | null)?.unsafe;\n if (typeof unsafe !== \"function\") {\n return undefined;\n }\n const probe: unknown = (unsafe as (text: string) => unknown).call(\n sql,\n \"select 1\",\n );\n if (probe === null || typeof probe !== \"object\") {\n return undefined;\n }\n const prototype = Object.getPrototypeOf(probe) as object | null;\n if (prototype === null) {\n return undefined;\n }\n const descriptor = Object.getOwnPropertyDescriptor(prototype, \"handle\");\n return descriptor !== undefined &&\n typeof descriptor.value === \"function\" &&\n descriptor.configurable === true\n ? prototype\n : undefined;\n};\n\nconst patchHandle = (prototype: object): void => {\n const descriptor = Object.getOwnPropertyDescriptor(prototype, \"handle\");\n const original = descriptor?.value as HandleFn | undefined;\n if (\n original === undefined ||\n (original as unknown as Record<symbol, unknown>)[HANDLE_PATCHED] === true\n ) {\n return;\n }\n\n const patched = function (this: PostgresJsQueryLike): unknown {\n // `handle` is reachable from then/catch/finally/execute, so it can be called more than once\n // for one query; postgres.js itself no-ops on the repeats via `executed`. Bail before\n // instrumenting so a query is never captured twice.\n if (this.executed || !isSupportedPostgresJsQuery(this)) {\n return original.call(this);\n }\n const ctx = requestCaptureContext.getStore();\n if (!ctx || ctx.mode !== \"record\") {\n return original.call(this);\n }\n try {\n captureQuery(ctx, this);\n } catch (error) {\n warnOnce(\n \"postgres-capture\",\n \"Failed to capture a postgres.js query.\",\n error,\n );\n }\n return original.call(this);\n };\n Object.defineProperty(patched, HANDLE_PATCHED, {\n value: true,\n enumerable: false,\n configurable: true,\n });\n Object.defineProperty(prototype, \"handle\", {\n value: patched,\n writable: true,\n enumerable: false,\n configurable: true,\n });\n};\n\n/**\n * Wraps the query's own `resolve`/`reject` so the outcome is captured without the query being\n * awaited here — the same trick the Node instrumentation uses, and the only place a query's input\n * and its result are both visible.\n */\nconst captureQuery = (\n ctx: RequestCaptureContext,\n query: PostgresJsQueryLike,\n): void => {\n const queryText = reconstructQueryText(query.strings);\n if (queryText === undefined) {\n return;\n }\n const startTimeMs = Date.now();\n const base = {\n kind: \"postgres\" as const,\n requestId: ctx.requestId,\n ...(ctx.frontendSessionId !== undefined\n ? { frontendSessionId: ctx.frontendSessionId }\n : {}),\n traceId: ctx.traceId,\n serverSpanId: ctx.serverSpanId,\n queryText,\n params: serializePostgresJsArgs(query.args),\n rowMode: resolveRowMode(query.isRaw),\n startTimeMs,\n };\n\n const report = (outcome: Partial<PostgresQueryEvent>): void => {\n try {\n ctx.buffer.add({ ...base, ...outcome, endTimeMs: Date.now() });\n } catch (error) {\n warnOnce(\n \"postgres-report\",\n \"Failed to report a postgres.js query.\",\n error,\n );\n }\n };\n\n const originalResolve = query.resolve;\n const originalReject = query.reject;\n query.resolve = (result: unknown) => {\n // A result that cannot be serialized is simply not captured → it misses during replay and\n // errors hermetically, rather than serving something wrong.\n let json: string | undefined;\n try {\n json = serializePostgresJsResult(result);\n } catch {\n json = undefined;\n }\n report(\n json === undefined\n ? {}\n : {\n result: {\n body:\n json.length > MAX_POSTGRES_JS_RESULT_SIZE\n ? json.slice(0, MAX_POSTGRES_JS_RESULT_SIZE)\n : json,\n truncated: json.length > MAX_POSTGRES_JS_RESULT_SIZE,\n },\n },\n );\n return originalResolve.call(query, result);\n };\n query.reject = (error: unknown) => {\n let errorJson: string | undefined;\n try {\n errorJson = serializePostgresJsError(error);\n } catch {\n errorJson = undefined;\n }\n report(errorJson === undefined ? {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LAY_ID_HEADER = "x-meticulous-replay-id";
26
26
  declare const METICULOUS_PASSTHROUGH_HEADER = "meticulous-passthrough";
27
27
  declare const SIDECAR_EVENTS_PATH = "/v1/events";
28
28
  /**
29
- * Replay routes. A sidecar started in record mode answers 404 on both, which the shim
30
- * treats as "replay unavailable" and falls back to plain pass-through — so a new shim
31
- * keeps working against an older, record-only sidecar.
29
+ * Replay routes. A sidecar started in record mode answers 404 on both. Replay is hermetic,
30
+ * so an unanswered outbound-fetch lookup fails the app's call rather than letting it reach
31
+ * the real service — the same as any other failure to stub.
32
32
  */
33
33
  declare const SIDECAR_REPLAY_SESSION_PATH = "/v1/replay/session";
34
34
  declare const SIDECAR_REPLAY_OUTBOUND_FETCH_PATH = "/v1/replay/outbound-fetch";
35
+ /**
36
+ * Line-coverage reporting. Additive: an older sidecar answers 404, which the
37
+ * shim treats as "coverage not collected here" and stops reporting for the life
38
+ * of the isolate. Deliberately NOT guarded by a
39
+ * {@link SIDECAR_PROTOCOL_VERSION} bump — that check is exact equality, so a
40
+ * bump would stop every already-built customer image from mocking at all.
41
+ */
42
+ declare const SIDECAR_REPLAY_COVERAGE_PATH = "/v1/replay/coverage";
35
43
  /**
36
44
  * Header carrying the replay sidecar's origin, injected by the Meticulous replay runner
37
45
  * on requests to the app under test. Workerd cannot see container environment variables,
@@ -41,6 +49,14 @@ declare const SIDECAR_REPLAY_OUTBOUND_FETCH_PATH = "/v1/replay/outbound-fetch";
41
49
  * `host.docker.internal` / private-network `http:` origin — see `replay-sidecar-url.ts`.
42
50
  */
43
51
  declare const REPLAY_SIDECAR_URL_HEADER = "x-meticulous-backend-replay-sidecar-url";
52
+ /**
53
+ * Header the in-worker shim stamps on every app response (record and replay)
54
+ * carrying the shim's npm package version. The replay runner reads this from
55
+ * Puppeteer — workerd cannot see container env, and the execute pod cannot
56
+ * reach the in-pod sidecar, so a response header is the only channel that
57
+ * reports which bundled shim produced a replay's After screenshots.
58
+ */
59
+ declare const WORKERD_SHIM_VERSION_HEADER = "x-meticulous-workerd-shim-version";
44
60
  /**
45
61
  * The only headers persisted on capture events. Everything else — notably
46
62
  * authorization, cookie/set-cookie, and API-key headers — is dropped at
@@ -244,6 +260,25 @@ interface ReplaySessionInfoResponse {
244
260
  */
245
261
  clockAnchorMs?: number;
246
262
  }
263
+ /**
264
+ * One request's line coverage, sent to {@link SIDECAR_REPLAY_COVERAGE_PATH}
265
+ * after the response has been produced.
266
+ *
267
+ * `files` carries the build-time id→line map and is sent only on the first
268
+ * report of an isolate: it is the same for every request the isolate serves and
269
+ * is far larger than the hits themselves.
270
+ */
271
+ interface CoverageReportRequest {
272
+ frontendSessionId: string;
273
+ /** Global line ids marked during this request, ascending. */
274
+ hitIds: number[];
275
+ /** Present on an isolate's first report only. */
276
+ files?: Array<{
277
+ path: string;
278
+ firstId: number; /** Inclusive 1-based line ranges, flattened as `[s1, e1, s2, e2, ...]`. */
279
+ lineRanges: number[];
280
+ }>;
281
+ }
247
282
  /** Lookup for a single outbound `fetch`, sent to {@link SIDECAR_REPLAY_OUTBOUND_FETCH_PATH}. */
248
283
  interface OutboundFetchLookupRequest {
249
284
  frontendSessionId: string;
@@ -259,9 +294,10 @@ interface OutboundFetchLookupRequest {
259
294
  requestBody?: CapturedBody;
260
295
  }
261
296
  /**
262
- * A recorded response to serve, a miss the caller must fail, or an instruction to let the
263
- * real call through. An unrecognised `outcome` must be treated as `passthrough`, so an older
264
- * shim keeps working against a newer sidecar.
297
+ * A recorded response to serve, or a signal the caller must fail the request. Replay is
298
+ * hermetic, so the shim never turns any of these into a real call — nor an outcome it does
299
+ * not recognise. The only live path is the request-side `meticulous-passthrough` header,
300
+ * handled before the lookup, not any response here.
265
301
  */
266
302
  type OutboundFetchLookupResponse = {
267
303
  outcome: "mock";
@@ -270,21 +306,15 @@ type OutboundFetchLookupResponse = {
270
306
  headers: Record<string, string>;
271
307
  }
272
308
  /**
273
- * The store was consulted and holds nothing for this call. Replay is hermetic, so the
274
- * shim fails the request rather than letting it reach the real service — matching the
275
- * Node backend recorder's http/undici mocks.
309
+ * The store holds nothing for this call — a genuine miss, or a call the sidecar could not
310
+ * look up at all (an unparseable URL). Replay is hermetic, so the shim fails the request
311
+ * rather than letting it reach the real service — matching the Node backend recorder's
312
+ * http/undici mocks. There is deliberately no "let the call through" outcome: the only
313
+ * live path is the request-side `meticulous-passthrough` header.
276
314
  */
277
315
  | {
278
316
  outcome: "no-mock";
279
- }
280
- /**
281
- * The call cannot be looked up at all (an unparseable URL), so there is no miss to report.
282
- * Also what an older sidecar answers on a miss, in which case the shim degrades to the
283
- * pre-`no-mock` fail-open behaviour rather than breaking the app.
284
- */
285
- | {
286
- outcome: "passthrough";
287
317
  };
288
318
  //#endregion
289
- export { BindingRequestEvent, CAPTURED_HEADERS, CaptureEvent, CaptureEventsPayload, CapturedBody, FRONTEND_SESSION_ID_HEADER, InboundRequestEvent, KvOmittedReason, KvOperation, KvOperationEvent, METICULOUS_PASSTHROUGH_HEADER, OutboundFetchLookupRequest, OutboundFetchLookupResponse, OutboundRequestEvent, PostgresQueryEvent, REPLAY_ID_HEADER, REPLAY_SIDECAR_URL_HEADER, ReplaySessionInfoResponse, SIDECAR_EVENTS_PATH, SIDECAR_PROTOCOL_VERSION, SIDECAR_PROTOCOL_VERSION_HEADER, SIDECAR_REPLAY_OUTBOUND_FETCH_PATH, SIDECAR_REPLAY_SESSION_PATH };
319
+ export { BindingRequestEvent, CAPTURED_HEADERS, CaptureEvent, CaptureEventsPayload, CapturedBody, CoverageReportRequest, FRONTEND_SESSION_ID_HEADER, InboundRequestEvent, KvOmittedReason, KvOperation, KvOperationEvent, METICULOUS_PASSTHROUGH_HEADER, OutboundFetchLookupRequest, OutboundFetchLookupResponse, OutboundRequestEvent, PostgresQueryEvent, REPLAY_ID_HEADER, REPLAY_SIDECAR_URL_HEADER, ReplaySessionInfoResponse, SIDECAR_EVENTS_PATH, SIDECAR_PROTOCOL_VERSION, SIDECAR_PROTOCOL_VERSION_HEADER, SIDECAR_REPLAY_COVERAGE_PATH, SIDECAR_REPLAY_OUTBOUND_FETCH_PATH, SIDECAR_REPLAY_SESSION_PATH, WORKERD_SHIM_VERSION_HEADER };
290
320
  //# sourceMappingURL=protocol.d.ts.map
package/dist/protocol.js CHANGED
@@ -5,7 +5,7 @@
5
5
  * is the single source of truth for the shape of capture events.
6
6
  */
7
7
 
8
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="36a20e1c-cf70-5563-a474-2863eaacfbe8")}catch(e){}}();
8
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="195758e9-bc4f-5373-96e6-e0aef542ce8c")}catch(e){}}();
9
9
  const SIDECAR_PROTOCOL_VERSION = "2";
10
10
  /** Header carrying {@link SIDECAR_PROTOCOL_VERSION} on every shim → sidecar request. */
11
11
  const SIDECAR_PROTOCOL_VERSION_HEADER = "x-meticulous-sidecar-protocol-version";
@@ -28,13 +28,21 @@ const REPLAY_ID_HEADER = "x-meticulous-replay-id";
28
28
  const METICULOUS_PASSTHROUGH_HEADER = "meticulous-passthrough";
29
29
  const SIDECAR_EVENTS_PATH = "/v1/events";
30
30
  /**
31
- * Replay routes. A sidecar started in record mode answers 404 on both, which the shim
32
- * treats as "replay unavailable" and falls back to plain pass-through — so a new shim
33
- * keeps working against an older, record-only sidecar.
31
+ * Replay routes. A sidecar started in record mode answers 404 on both. Replay is hermetic,
32
+ * so an unanswered outbound-fetch lookup fails the app's call rather than letting it reach
33
+ * the real service — the same as any other failure to stub.
34
34
  */
35
35
  const SIDECAR_REPLAY_SESSION_PATH = "/v1/replay/session";
36
36
  const SIDECAR_REPLAY_OUTBOUND_FETCH_PATH = "/v1/replay/outbound-fetch";
37
37
  /**
38
+ * Line-coverage reporting. Additive: an older sidecar answers 404, which the
39
+ * shim treats as "coverage not collected here" and stops reporting for the life
40
+ * of the isolate. Deliberately NOT guarded by a
41
+ * {@link SIDECAR_PROTOCOL_VERSION} bump — that check is exact equality, so a
42
+ * bump would stop every already-built customer image from mocking at all.
43
+ */
44
+ const SIDECAR_REPLAY_COVERAGE_PATH = "/v1/replay/coverage";
45
+ /**
38
46
  * Header carrying the replay sidecar's origin, injected by the Meticulous replay runner
39
47
  * on requests to the app under test. Workerd cannot see container environment variables,
40
48
  * so an inbound header is the only way per-replay config can reach the shim.
@@ -44,6 +52,14 @@ const SIDECAR_REPLAY_OUTBOUND_FETCH_PATH = "/v1/replay/outbound-fetch";
44
52
  */
45
53
  const REPLAY_SIDECAR_URL_HEADER = "x-meticulous-backend-replay-sidecar-url";
46
54
  /**
55
+ * Header the in-worker shim stamps on every app response (record and replay)
56
+ * carrying the shim's npm package version. The replay runner reads this from
57
+ * Puppeteer — workerd cannot see container env, and the execute pod cannot
58
+ * reach the in-pod sidecar, so a response header is the only channel that
59
+ * reports which bundled shim produced a replay's After screenshots.
60
+ */
61
+ const WORKERD_SHIM_VERSION_HEADER = "x-meticulous-workerd-shim-version";
62
+ /**
47
63
  * The only headers persisted on capture events. Everything else — notably
48
64
  * authorization, cookie/set-cookie, and API-key headers — is dropped at
49
65
  * capture time, before it ever leaves the worker.
@@ -55,7 +71,7 @@ const REPLAY_SIDECAR_URL_HEADER = "x-meticulous-backend-replay-sidecar-url";
55
71
  */
56
72
  const CAPTURED_HEADERS = ["content-type", FRONTEND_SESSION_ID_HEADER];
57
73
  //#endregion
58
- export { CAPTURED_HEADERS, FRONTEND_SESSION_ID_HEADER, METICULOUS_PASSTHROUGH_HEADER, REPLAY_ID_HEADER, REPLAY_SIDECAR_URL_HEADER, SIDECAR_EVENTS_PATH, SIDECAR_PROTOCOL_VERSION, SIDECAR_PROTOCOL_VERSION_HEADER, SIDECAR_REPLAY_OUTBOUND_FETCH_PATH, SIDECAR_REPLAY_SESSION_PATH };
74
+ export { CAPTURED_HEADERS, FRONTEND_SESSION_ID_HEADER, METICULOUS_PASSTHROUGH_HEADER, REPLAY_ID_HEADER, REPLAY_SIDECAR_URL_HEADER, SIDECAR_EVENTS_PATH, SIDECAR_PROTOCOL_VERSION, SIDECAR_PROTOCOL_VERSION_HEADER, SIDECAR_REPLAY_COVERAGE_PATH, SIDECAR_REPLAY_OUTBOUND_FETCH_PATH, SIDECAR_REPLAY_SESSION_PATH, WORKERD_SHIM_VERSION_HEADER };
59
75
 
60
76
  //# sourceMappingURL=protocol.js.map
61
- //# debugId=36a20e1c-cf70-5563-a474-2863eaacfbe8
77
+ //# debugId=195758e9-bc4f-5373-96e6-e0aef542ce8c
@@ -1 +1 @@
1
- {"version":3,"file":"protocol.js","sources":["../src/protocol.ts"],"sourcesContent":["/**\n * Wire protocol between the in-worker shim and the Meticulous backend\n * recorder sidecar. The sidecar imports these types (type-only), so this file\n * is the single source of truth for the shape of capture events.\n */\n\nexport const SIDECAR_PROTOCOL_VERSION = \"2\";\n\n/** Header carrying {@link SIDECAR_PROTOCOL_VERSION} on every shim → sidecar request. */\nexport const SIDECAR_PROTOCOL_VERSION_HEADER =\n \"x-meticulous-sidecar-protocol-version\";\n\n/**\n * Header the Meticulous frontend recorder stamps on requests made by the app\n * under recording; its value ties backend spans to the frontend session.\n */\nexport const FRONTEND_SESSION_ID_HEADER = \"x-meticulous-session-id\";\n\n/** Header identifying one replay attempt of a recorded frontend session. */\nexport const REPLAY_ID_HEADER = \"x-meticulous-replay-id\";\n\n/**\n * A request carrying this header set to `\"true\"` is never served from the recording and\n * never fails on a miss — it goes to the real network. Use it for a call that must be live\n * during replay (a health probe, telemetry, a resource the recording cannot cover).\n *\n * Same convention and value as the frontend network stubbing and the Node backend recorder\n * (`METICULOUS_PASSTHROUGH_HEADER` in `@alwaysmeticulous/backend-recorder-js`); the value\n * must stay in step with both.\n */\nexport const METICULOUS_PASSTHROUGH_HEADER = \"meticulous-passthrough\";\n\nexport const SIDECAR_EVENTS_PATH = \"/v1/events\";\n\n/**\n * Replay routes. A sidecar started in record mode answers 404 on both, which the shim\n * treats as \"replay unavailable\" and falls back to plain pass-through — so a new shim\n * keeps working against an older, record-only sidecar.\n */\nexport const SIDECAR_REPLAY_SESSION_PATH = \"/v1/replay/session\";\nexport const SIDECAR_REPLAY_OUTBOUND_FETCH_PATH = \"/v1/replay/outbound-fetch\";\n\n/**\n * Header carrying the replay sidecar's origin, injected by the Meticulous replay runner\n * on requests to the app under test. Workerd cannot see container environment variables,\n * so an inbound header is the only way per-replay config can reach the shim.\n *\n * The shim validates the value before using it and only honours a loopback /\n * `host.docker.internal` / private-network `http:` origin — see `replay-sidecar-url.ts`.\n */\nexport const REPLAY_SIDECAR_URL_HEADER =\n \"x-meticulous-backend-replay-sidecar-url\";\n\n/**\n * The only headers persisted on capture events. Everything else — notably\n * authorization, cookie/set-cookie, and API-key headers — is dropped at\n * capture time, before it ever leaves the worker.\n *\n * The Node backend recorder persists the same two, plus the inbound request's\n * `Cookie` header on SERVER spans (`recorded-request-headers.ts`). This list\n * has not followed it there, so a workerd recording of an authenticated server\n * render still carries no session cookie.\n */\nexport const CAPTURED_HEADERS = [\n \"content-type\",\n FRONTEND_SESSION_ID_HEADER,\n] as const;\n\nexport interface CapturedBody {\n /** UTF-8 decoded body, truncated to the capture cap. */\n body: string;\n /** True when the body exceeded the capture cap or the read was cut short. */\n truncated: boolean;\n}\n\n/**\n * The fields every capture event carries to say which request, session and trace it belongs to.\n */\ninterface CorrelatedEvent {\n /** Correlates outbound events to the inbound request being handled. */\n requestId: string;\n /** Value of {@link FRONTEND_SESSION_ID_HEADER} on the inbound request, if any. */\n frontendSessionId?: string;\n /**\n * Trace the request's spans belong to (32 hex chars), minted by the shim.\n *\n * The shim mints it, rather than the sidecar deriving it from {@link requestId}, so span\n * assembly is stateless: a sidecar that had to remember `requestId → traceId` would give a\n * request's SERVER span and its CLIENT children different traces whenever it lost that memory\n * between two batches — which, for a Worker-hosted sidecar, an eviction can do at any moment.\n *\n * Optional so a sidecar keeps working against a shim that predates this field, in which case\n * it falls back to its own per-`requestId` map.\n */\n traceId?: string;\n /**\n * Span id of the request's SERVER span (16 hex chars), also minted by the shim: it is the\n * parent of every CLIENT span the request produced, and the inbound event's own span id.\n */\n serverSpanId?: string;\n}\n\ninterface BaseRequestEvent extends CorrelatedEvent {\n method: string;\n /** Full URL including query string. */\n url: string;\n /** Lower-cased header name → values. */\n requestHeaders: Record<string, string[]>;\n responseHeaders?: Record<string, string[]>;\n statusCode?: number;\n startTimeMs: number;\n endTimeMs: number;\n /** Set when the request failed before a response was produced. */\n error?: string;\n}\n\n/**\n * The worker's own inbound request (becomes a SERVER span). Bodies are not\n * captured, matching the Node backend recorder's SERVER-span contract.\n */\nexport interface InboundRequestEvent extends BaseRequestEvent {\n kind: \"inbound\";\n /**\n * Where {@link BaseRequestEvent.frontendSessionId} came from. Absent means the browser\n * minted it and sent it on the request, which is the normal case. `\"backend\"` means the\n * shim minted it for a document navigation the browser could not tag, and the page may or\n * may not have gone on to adopt it — a distinction ingestion needs, because an unadopted\n * backend-minted id names a session that will never exist and must be treated as unstamped.\n * The sidecar turns it into `meticulous.session_id_origin`.\n *\n * Optional, and therefore compatible with an older sidecar (which ignores it) — which is\n * why adding it does not bump {@link SIDECAR_PROTOCOL_VERSION}, a strict-equality check\n * whose bump would instead make this shim unusable against one.\n */\n sessionIdOrigin?: \"backend\";\n}\n\n/**\n * An outgoing `fetch` call made while handling an inbound request (becomes a\n * CLIENT span).\n */\nexport interface OutboundRequestEvent extends BaseRequestEvent {\n kind: \"outbound\";\n requestBody?: CapturedBody;\n responseBody?: CapturedBody;\n}\n\n/**\n * A `fetch` through a Cloudflare binding — a service binding, an assets binding, or a\n * Durable Object stub — made while handling an inbound request (becomes a CLIENT span).\n *\n * Request/Response-shaped like {@link OutboundRequestEvent}, but a distinct kind because the\n * call never leaves the isolate and its URL is whatever the caller invented. Keeping the two\n * apart means a binding call and real egress can never be confused for one another when\n * these spans are eventually mocked.\n */\nexport interface BindingRequestEvent extends BaseRequestEvent {\n kind: \"binding\";\n /**\n * The `env` key the binding was found under. Absent when the instance was never seen on\n * `env` — most commonly a Durable Object stub, which `namespace.get()` produces rather\n * than being a binding in its own right.\n */\n bindingName?: string;\n requestBody?: CapturedBody;\n responseBody?: CapturedBody;\n}\n\n/** KV namespace methods the shim records. */\nexport type KvOperation = \"get\" | \"getWithMetadata\" | \"put\" | \"delete\" | \"list\";\n\n/**\n * Why a KV value is absent from an event: workerd handed it over in a form that cannot be\n * persisted as text. A `\"stream\"` value must not even be read — consuming it would take the\n * bytes away from the app — and binary values are skipped deliberately, since KV blobs are\n * large and would both bloat the recording and be mangled by UTF-8 capture.\n */\nexport type KvOmittedReason = \"binary\" | \"stream\";\n\n/**\n * An operation on a Cloudflare KV namespace binding, made while handling an inbound request\n * (becomes a CLIENT span).\n *\n * KV is not HTTP: there is no method, URL or status code, so this event shares nothing with\n * {@link BaseRequestEvent} beyond correlation and timing. Values are JSON so that a single\n * `JSON.parse` reconstructs exactly what the app saw, whichever `type` the read asked for.\n */\nexport interface KvOperationEvent extends CorrelatedEvent {\n kind: \"kv\";\n /**\n * The `env` key the KV namespace was found under. Always present, unlike on a binding\n * event: a namespace has no factory equivalent to `DurableObjectNamespace.get()`, so one\n * that was never seen on `env` is not recorded at all.\n */\n bindingName: string;\n operation: KvOperation;\n /**\n * The key operated on, when it is a single string. Absent for `list` (which spans keys) and\n * for a bulk `get` (which takes an array) — both keep their arguments in {@link args}.\n */\n key?: string;\n /**\n * JSON of the call's arguments: the read `type`, the `put` options, the `list` selector.\n * A `put` value appears as `null` here — it is captured in {@link value} instead, so that\n * redaction applies to it.\n */\n args?: CapturedBody;\n /** JSON of the value a `put` wrote, with secret-looking fields redacted. */\n value?: CapturedBody;\n /**\n * JSON of what the operation returned: the value for `get`, `{value, metadata}` for\n * `getWithMetadata`, the key page for `list`. Absent for `put`/`delete`, which return\n * nothing, and for a value that could not be captured (see {@link omitted}).\n */\n result?: CapturedBody;\n /**\n * Why the operation's value is missing. Refers to the written value for `put` and to the\n * read value otherwise — a `put` has no result, so this is never ambiguous.\n */\n omitted?: KvOmittedReason;\n startTimeMs: number;\n endTimeMs: number;\n /** Set when the operation threw. */\n error?: string;\n}\n\n/**\n * One postgres.js query made while handling an inbound request (becomes a CLIENT span).\n *\n * Deliberately carries the same fields the Node recorder puts on a postgres.js span rather than\n * anything Worker-specific: `PostgresJsMockStore` builds its match key from those attributes at\n * load time, so a query recorded here replays through the existing Node mock path unchanged.\n * See `postgres/capture.ts` for the serialization, which both surfaces share.\n */\nexport interface PostgresQueryEvent extends CorrelatedEvent {\n kind: \"postgres\";\n /** SQL rebuilt from the tagged template's chunks, with `$1`, `$2`… placeholders. */\n queryText: string;\n /** JSON of the interpolated values, from `serializePostgresJsArgs`. */\n params: string;\n /** `\"\"`, `\"raw\"` or `\"values\"` — the row shape the query asked for. */\n rowMode: string;\n /** JSON of the resolved `Result`, capped at {@link MAX_POSTGRES_JS_RESULT_SIZE}. */\n result?: CapturedBody;\n /**\n * JSON of the rejection, from `serializePostgresJsError`. Set instead of {@link result}, and\n * distinct from the transport-level `error` string on the HTTP-shaped events: this one is a\n * recorded outcome the replay reproduces, not a note that capture failed.\n */\n errorJson?: string;\n startTimeMs: number;\n endTimeMs: number;\n}\n\nexport type CaptureEvent =\n | InboundRequestEvent\n | OutboundRequestEvent\n | BindingRequestEvent\n | KvOperationEvent\n | PostgresQueryEvent;\n\nexport interface CaptureEventsPayload {\n events: CaptureEvent[];\n}\n\n/**\n * Answer to `GET {SIDECAR_REPLAY_SESSION_PATH}?sessionId=<id>`: whether the sidecar holds\n * mocks for a session, and the virtual clock anchor to freeze `Date` at while serving it.\n */\nexport interface ReplaySessionInfoResponse {\n found: boolean;\n /**\n * Epoch ms of the session's last recorded activity. The worker freezes its clock here so\n * that credentials minted during the recording are already issued but not yet expired.\n */\n clockAnchorMs?: number;\n}\n\n/** Lookup for a single outbound `fetch`, sent to {@link SIDECAR_REPLAY_OUTBOUND_FETCH_PATH}. */\nexport interface OutboundFetchLookupRequest {\n frontendSessionId: string;\n replayId: string;\n method: string;\n /** Full URL including query string. */\n url: string;\n /**\n * Request body as captured by `readBodyWithCap`. The sidecar hashes this itself, so the\n * hash it compares against a recording is derived from byte-identical input on both the\n * record and replay sides.\n */\n requestBody?: CapturedBody;\n}\n\n/**\n * A recorded response to serve, a miss the caller must fail, or an instruction to let the\n * real call through. An unrecognised `outcome` must be treated as `passthrough`, so an older\n * shim keeps working against a newer sidecar.\n */\nexport type OutboundFetchLookupResponse =\n | {\n outcome: \"mock\";\n statusCode: number;\n body: string;\n headers: Record<string, string>;\n }\n /**\n * The store was consulted and holds nothing for this call. Replay is hermetic, so the\n * shim fails the request rather than letting it reach the real service — matching the\n * Node backend recorder's http/undici mocks.\n */\n | { outcome: \"no-mock\" }\n /**\n * The call cannot be looked up at all (an unparseable URL), so there is no miss to report.\n * Also what an older sidecar answers on a miss, in which case the shim degrades to the\n * pre-`no-mock` fail-open behaviour rather than breaking the app.\n */\n | { outcome: \"passthrough\" };\n"],"names":[],"mappings":";;;;;;;;AAMA,MAAa,2BAA2B;;AAGxC,MAAa,kCACX;;;;;AAMF,MAAa,6BAA6B;;AAG1C,MAAa,mBAAmB;;;;;;;;;;AAWhC,MAAa,gCAAgC;AAE7C,MAAa,sBAAsB;;;;;;AAOnC,MAAa,8BAA8B;AAC3C,MAAa,qCAAqC;;;;;;;;;AAUlD,MAAa,4BACX;;;;;;;;;;;AAYF,MAAa,mBAAmB,CAC9B,gBACA,2BACD","debugId":"36a20e1c-cf70-5563-a474-2863eaacfbe8"}
1
+ {"version":3,"file":"protocol.js","sources":["../src/protocol.ts"],"sourcesContent":["/**\n * Wire protocol between the in-worker shim and the Meticulous backend\n * recorder sidecar. The sidecar imports these types (type-only), so this file\n * is the single source of truth for the shape of capture events.\n */\n\nexport const SIDECAR_PROTOCOL_VERSION = \"2\";\n\n/** Header carrying {@link SIDECAR_PROTOCOL_VERSION} on every shim → sidecar request. */\nexport const SIDECAR_PROTOCOL_VERSION_HEADER =\n \"x-meticulous-sidecar-protocol-version\";\n\n/**\n * Header the Meticulous frontend recorder stamps on requests made by the app\n * under recording; its value ties backend spans to the frontend session.\n */\nexport const FRONTEND_SESSION_ID_HEADER = \"x-meticulous-session-id\";\n\n/** Header identifying one replay attempt of a recorded frontend session. */\nexport const REPLAY_ID_HEADER = \"x-meticulous-replay-id\";\n\n/**\n * A request carrying this header set to `\"true\"` is never served from the recording and\n * never fails on a miss — it goes to the real network. Use it for a call that must be live\n * during replay (a health probe, telemetry, a resource the recording cannot cover).\n *\n * Same convention and value as the frontend network stubbing and the Node backend recorder\n * (`METICULOUS_PASSTHROUGH_HEADER` in `@alwaysmeticulous/backend-recorder-js`); the value\n * must stay in step with both.\n */\nexport const METICULOUS_PASSTHROUGH_HEADER = \"meticulous-passthrough\";\n\nexport const SIDECAR_EVENTS_PATH = \"/v1/events\";\n\n/**\n * Replay routes. A sidecar started in record mode answers 404 on both. Replay is hermetic,\n * so an unanswered outbound-fetch lookup fails the app's call rather than letting it reach\n * the real service — the same as any other failure to stub.\n */\nexport const SIDECAR_REPLAY_SESSION_PATH = \"/v1/replay/session\";\nexport const SIDECAR_REPLAY_OUTBOUND_FETCH_PATH = \"/v1/replay/outbound-fetch\";\n\n/**\n * Line-coverage reporting. Additive: an older sidecar answers 404, which the\n * shim treats as \"coverage not collected here\" and stops reporting for the life\n * of the isolate. Deliberately NOT guarded by a\n * {@link SIDECAR_PROTOCOL_VERSION} bump — that check is exact equality, so a\n * bump would stop every already-built customer image from mocking at all.\n */\nexport const SIDECAR_REPLAY_COVERAGE_PATH = \"/v1/replay/coverage\";\n\n/**\n * Header carrying the replay sidecar's origin, injected by the Meticulous replay runner\n * on requests to the app under test. Workerd cannot see container environment variables,\n * so an inbound header is the only way per-replay config can reach the shim.\n *\n * The shim validates the value before using it and only honours a loopback /\n * `host.docker.internal` / private-network `http:` origin — see `replay-sidecar-url.ts`.\n */\nexport const REPLAY_SIDECAR_URL_HEADER =\n \"x-meticulous-backend-replay-sidecar-url\";\n\n/**\n * Header the in-worker shim stamps on every app response (record and replay)\n * carrying the shim's npm package version. The replay runner reads this from\n * Puppeteer — workerd cannot see container env, and the execute pod cannot\n * reach the in-pod sidecar, so a response header is the only channel that\n * reports which bundled shim produced a replay's After screenshots.\n */\nexport const WORKERD_SHIM_VERSION_HEADER = \"x-meticulous-workerd-shim-version\";\n\n/**\n * The only headers persisted on capture events. Everything else — notably\n * authorization, cookie/set-cookie, and API-key headers — is dropped at\n * capture time, before it ever leaves the worker.\n *\n * The Node backend recorder persists the same two, plus the inbound request's\n * `Cookie` header on SERVER spans (`recorded-request-headers.ts`). This list\n * has not followed it there, so a workerd recording of an authenticated server\n * render still carries no session cookie.\n */\nexport const CAPTURED_HEADERS = [\n \"content-type\",\n FRONTEND_SESSION_ID_HEADER,\n] as const;\n\nexport interface CapturedBody {\n /** UTF-8 decoded body, truncated to the capture cap. */\n body: string;\n /** True when the body exceeded the capture cap or the read was cut short. */\n truncated: boolean;\n}\n\n/**\n * The fields every capture event carries to say which request, session and trace it belongs to.\n */\ninterface CorrelatedEvent {\n /** Correlates outbound events to the inbound request being handled. */\n requestId: string;\n /** Value of {@link FRONTEND_SESSION_ID_HEADER} on the inbound request, if any. */\n frontendSessionId?: string;\n /**\n * Trace the request's spans belong to (32 hex chars), minted by the shim.\n *\n * The shim mints it, rather than the sidecar deriving it from {@link requestId}, so span\n * assembly is stateless: a sidecar that had to remember `requestId → traceId` would give a\n * request's SERVER span and its CLIENT children different traces whenever it lost that memory\n * between two batches — which, for a Worker-hosted sidecar, an eviction can do at any moment.\n *\n * Optional so a sidecar keeps working against a shim that predates this field, in which case\n * it falls back to its own per-`requestId` map.\n */\n traceId?: string;\n /**\n * Span id of the request's SERVER span (16 hex chars), also minted by the shim: it is the\n * parent of every CLIENT span the request produced, and the inbound event's own span id.\n */\n serverSpanId?: string;\n}\n\ninterface BaseRequestEvent extends CorrelatedEvent {\n method: string;\n /** Full URL including query string. */\n url: string;\n /** Lower-cased header name → values. */\n requestHeaders: Record<string, string[]>;\n responseHeaders?: Record<string, string[]>;\n statusCode?: number;\n startTimeMs: number;\n endTimeMs: number;\n /** Set when the request failed before a response was produced. */\n error?: string;\n}\n\n/**\n * The worker's own inbound request (becomes a SERVER span). Bodies are not\n * captured, matching the Node backend recorder's SERVER-span contract.\n */\nexport interface InboundRequestEvent extends BaseRequestEvent {\n kind: \"inbound\";\n /**\n * Where {@link BaseRequestEvent.frontendSessionId} came from. Absent means the browser\n * minted it and sent it on the request, which is the normal case. `\"backend\"` means the\n * shim minted it for a document navigation the browser could not tag, and the page may or\n * may not have gone on to adopt it — a distinction ingestion needs, because an unadopted\n * backend-minted id names a session that will never exist and must be treated as unstamped.\n * The sidecar turns it into `meticulous.session_id_origin`.\n *\n * Optional, and therefore compatible with an older sidecar (which ignores it) — which is\n * why adding it does not bump {@link SIDECAR_PROTOCOL_VERSION}, a strict-equality check\n * whose bump would instead make this shim unusable against one.\n */\n sessionIdOrigin?: \"backend\";\n}\n\n/**\n * An outgoing `fetch` call made while handling an inbound request (becomes a\n * CLIENT span).\n */\nexport interface OutboundRequestEvent extends BaseRequestEvent {\n kind: \"outbound\";\n requestBody?: CapturedBody;\n responseBody?: CapturedBody;\n}\n\n/**\n * A `fetch` through a Cloudflare binding — a service binding, an assets binding, or a\n * Durable Object stub — made while handling an inbound request (becomes a CLIENT span).\n *\n * Request/Response-shaped like {@link OutboundRequestEvent}, but a distinct kind because the\n * call never leaves the isolate and its URL is whatever the caller invented. Keeping the two\n * apart means a binding call and real egress can never be confused for one another when\n * these spans are eventually mocked.\n */\nexport interface BindingRequestEvent extends BaseRequestEvent {\n kind: \"binding\";\n /**\n * The `env` key the binding was found under. Absent when the instance was never seen on\n * `env` — most commonly a Durable Object stub, which `namespace.get()` produces rather\n * than being a binding in its own right.\n */\n bindingName?: string;\n requestBody?: CapturedBody;\n responseBody?: CapturedBody;\n}\n\n/** KV namespace methods the shim records. */\nexport type KvOperation = \"get\" | \"getWithMetadata\" | \"put\" | \"delete\" | \"list\";\n\n/**\n * Why a KV value is absent from an event: workerd handed it over in a form that cannot be\n * persisted as text. A `\"stream\"` value must not even be read — consuming it would take the\n * bytes away from the app — and binary values are skipped deliberately, since KV blobs are\n * large and would both bloat the recording and be mangled by UTF-8 capture.\n */\nexport type KvOmittedReason = \"binary\" | \"stream\";\n\n/**\n * An operation on a Cloudflare KV namespace binding, made while handling an inbound request\n * (becomes a CLIENT span).\n *\n * KV is not HTTP: there is no method, URL or status code, so this event shares nothing with\n * {@link BaseRequestEvent} beyond correlation and timing. Values are JSON so that a single\n * `JSON.parse` reconstructs exactly what the app saw, whichever `type` the read asked for.\n */\nexport interface KvOperationEvent extends CorrelatedEvent {\n kind: \"kv\";\n /**\n * The `env` key the KV namespace was found under. Always present, unlike on a binding\n * event: a namespace has no factory equivalent to `DurableObjectNamespace.get()`, so one\n * that was never seen on `env` is not recorded at all.\n */\n bindingName: string;\n operation: KvOperation;\n /**\n * The key operated on, when it is a single string. Absent for `list` (which spans keys) and\n * for a bulk `get` (which takes an array) — both keep their arguments in {@link args}.\n */\n key?: string;\n /**\n * JSON of the call's arguments: the read `type`, the `put` options, the `list` selector.\n * A `put` value appears as `null` here — it is captured in {@link value} instead, so that\n * redaction applies to it.\n */\n args?: CapturedBody;\n /** JSON of the value a `put` wrote, with secret-looking fields redacted. */\n value?: CapturedBody;\n /**\n * JSON of what the operation returned: the value for `get`, `{value, metadata}` for\n * `getWithMetadata`, the key page for `list`. Absent for `put`/`delete`, which return\n * nothing, and for a value that could not be captured (see {@link omitted}).\n */\n result?: CapturedBody;\n /**\n * Why the operation's value is missing. Refers to the written value for `put` and to the\n * read value otherwise — a `put` has no result, so this is never ambiguous.\n */\n omitted?: KvOmittedReason;\n startTimeMs: number;\n endTimeMs: number;\n /** Set when the operation threw. */\n error?: string;\n}\n\n/**\n * One postgres.js query made while handling an inbound request (becomes a CLIENT span).\n *\n * Deliberately carries the same fields the Node recorder puts on a postgres.js span rather than\n * anything Worker-specific: `PostgresJsMockStore` builds its match key from those attributes at\n * load time, so a query recorded here replays through the existing Node mock path unchanged.\n * See `postgres/capture.ts` for the serialization, which both surfaces share.\n */\nexport interface PostgresQueryEvent extends CorrelatedEvent {\n kind: \"postgres\";\n /** SQL rebuilt from the tagged template's chunks, with `$1`, `$2`… placeholders. */\n queryText: string;\n /** JSON of the interpolated values, from `serializePostgresJsArgs`. */\n params: string;\n /** `\"\"`, `\"raw\"` or `\"values\"` — the row shape the query asked for. */\n rowMode: string;\n /** JSON of the resolved `Result`, capped at {@link MAX_POSTGRES_JS_RESULT_SIZE}. */\n result?: CapturedBody;\n /**\n * JSON of the rejection, from `serializePostgresJsError`. Set instead of {@link result}, and\n * distinct from the transport-level `error` string on the HTTP-shaped events: this one is a\n * recorded outcome the replay reproduces, not a note that capture failed.\n */\n errorJson?: string;\n startTimeMs: number;\n endTimeMs: number;\n}\n\nexport type CaptureEvent =\n | InboundRequestEvent\n | OutboundRequestEvent\n | BindingRequestEvent\n | KvOperationEvent\n | PostgresQueryEvent;\n\nexport interface CaptureEventsPayload {\n events: CaptureEvent[];\n}\n\n/**\n * Answer to `GET {SIDECAR_REPLAY_SESSION_PATH}?sessionId=<id>`: whether the sidecar holds\n * mocks for a session, and the virtual clock anchor to freeze `Date` at while serving it.\n */\nexport interface ReplaySessionInfoResponse {\n found: boolean;\n /**\n * Epoch ms of the session's last recorded activity. The worker freezes its clock here so\n * that credentials minted during the recording are already issued but not yet expired.\n */\n clockAnchorMs?: number;\n}\n\n/**\n * One request's line coverage, sent to {@link SIDECAR_REPLAY_COVERAGE_PATH}\n * after the response has been produced.\n *\n * `files` carries the build-time id→line map and is sent only on the first\n * report of an isolate: it is the same for every request the isolate serves and\n * is far larger than the hits themselves.\n */\nexport interface CoverageReportRequest {\n frontendSessionId: string;\n /** Global line ids marked during this request, ascending. */\n hitIds: number[];\n /** Present on an isolate's first report only. */\n files?: Array<{\n path: string;\n firstId: number;\n /** Inclusive 1-based line ranges, flattened as `[s1, e1, s2, e2, ...]`. */\n lineRanges: number[];\n }>;\n}\n\n/** Lookup for a single outbound `fetch`, sent to {@link SIDECAR_REPLAY_OUTBOUND_FETCH_PATH}. */\nexport interface OutboundFetchLookupRequest {\n frontendSessionId: string;\n replayId: string;\n method: string;\n /** Full URL including query string. */\n url: string;\n /**\n * Request body as captured by `readBodyWithCap`. The sidecar hashes this itself, so the\n * hash it compares against a recording is derived from byte-identical input on both the\n * record and replay sides.\n */\n requestBody?: CapturedBody;\n}\n\n/**\n * A recorded response to serve, or a signal the caller must fail the request. Replay is\n * hermetic, so the shim never turns any of these into a real call — nor an outcome it does\n * not recognise. The only live path is the request-side `meticulous-passthrough` header,\n * handled before the lookup, not any response here.\n */\nexport type OutboundFetchLookupResponse =\n | {\n outcome: \"mock\";\n statusCode: number;\n body: string;\n headers: Record<string, string>;\n }\n /**\n * The store holds nothing for this call — a genuine miss, or a call the sidecar could not\n * look up at all (an unparseable URL). Replay is hermetic, so the shim fails the request\n * rather than letting it reach the real service — matching the Node backend recorder's\n * http/undici mocks. There is deliberately no \"let the call through\" outcome: the only\n * live path is the request-side `meticulous-passthrough` header.\n */\n | { outcome: \"no-mock\" };\n"],"names":[],"mappings":";;;;;;;;AAMA,MAAa,2BAA2B;;AAGxC,MAAa,kCACX;;;;;AAMF,MAAa,6BAA6B;;AAG1C,MAAa,mBAAmB;;;;;;;;;;AAWhC,MAAa,gCAAgC;AAE7C,MAAa,sBAAsB;;;;;;AAOnC,MAAa,8BAA8B;AAC3C,MAAa,qCAAqC;;;;;;;;AASlD,MAAa,+BAA+B;;;;;;;;;AAU5C,MAAa,4BACX;;;;;;;;AASF,MAAa,8BAA8B;;;;;;;;;;;AAY3C,MAAa,mBAAmB,CAC9B,gBACA,2BACD","debugId":"195758e9-bc4f-5373-96e6-e0aef542ce8c"}
@@ -1,5 +1,5 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="6222100c-04df-5fc9-b0f6-dcdf8a7b87ab")}catch(e){}}();
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="08993983-84c7-52a8-95ae-69986b1ed730")}catch(e){}}();
3
3
  import "./protocol.js";
4
4
  //#region src/provisional-session-id.ts
5
5
  const SERVER_TIMING_HEADER = "server-timing";
@@ -72,4 +72,4 @@ const isDocumentNavigation = (getHeader) => {
72
72
  export { SERVER_TIMING_HEADER, SERVER_TIMING_SESSION_METRIC, buildServerTimingSessionEntry, isProvisionalSessionIdCandidate, mintProvisionalSessionId };
73
73
 
74
74
  //# sourceMappingURL=provisional-session-id.js.map
75
- //# debugId=6222100c-04df-5fc9-b0f6-dcdf8a7b87ab
75
+ //# debugId=08993983-84c7-52a8-95ae-69986b1ed730
@@ -1 +1 @@
1
- {"version":3,"file":"provisional-session-id.js","sources":["../src/provisional-session-id.ts"],"sourcesContent":["import { FRONTEND_SESSION_ID_HEADER } from \"./protocol\";\n\n/**\n * A session id the *backend* mints, for the one request that can never carry one from the\n * browser: a top-level document navigation. Browsers cannot add custom headers to a\n * navigation, and on the session-starting navigation the frontend has not minted an id yet\n * (it does so only once the HTML has arrived and the snippet has run) — so the server-side\n * render's spans are recorded against no session and nothing about that traffic can be\n * replayed exactly.\n *\n * Everything here is runtime-agnostic on purpose. Both backend recorders mint the same ids\n * by the same rule and publish them under the same `Server-Timing` metric, and all three are\n * wire contracts with the page, so there is exactly one implementation — the same reason\n * kv-capture.ts lives here rather than being written twice. The Node recorder imports these\n * from the package entry; see `provisional-session-id.ts` in\n * `@alwaysmeticulous/backend-recorder-js` for the `http.IncomingMessage` adapter, and\n * `publish-session-id.ts` next door for the workerd one.\n */\n\n/**\n * Reads one request header by its lower-cased name. Both `IncomingMessage.headers[name]`\n * (after the caller flattens Node's `string | string[]`) and `Headers.get(name)` satisfy it,\n * which is what lets the rules below be shared.\n */\nexport type HeaderReader = (name: string) => string | null | undefined;\n\nexport const SERVER_TIMING_HEADER = \"server-timing\";\n\n/**\n * The `Server-Timing` metric name carrying a backend-minted session id to the page. A wire\n * contract with the frontend recorder, which matches on it case-insensitively when reading\n * `PerformanceNavigationTiming.serverTiming` (see `resolve-session-id.ts` in\n * packages/recorder). Must be a valid HTTP token — no `.` or `:`, which is why it is not the\n * dotted span-attribute name.\n */\nexport const SERVER_TIMING_SESSION_METRIC = \"metsession\";\n\n/**\n * `Server-Timing` is the one response header a document's own JavaScript can read back, and\n * the navigation entry persists for the document's lifetime — so unlike a header-sniffing\n * approach this works no matter how late the snippet loads.\n */\nexport const buildServerTimingSessionEntry = (sessionId: string): string =>\n `${SERVER_TIMING_SESSION_METRIC};desc=\"${sessionId}\"`;\n\n/**\n * nanoid's default alphabet and length, reproduced rather than imported: this package carries\n * no runtime dependencies, and an id that did not look like every other session id would be a\n * gratuitous difference in S3 keys and URLs. 64 characters divides 256 exactly, so masking a\n * random byte with 63 is uniform — which is how nanoid itself generates them.\n */\nconst ID_ALPHABET =\n \"ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW\";\nconst ID_LENGTH = 21;\n\n/**\n * Mints an id in exactly the frontend recorder's format: `<ISO timestamp>_<nanoid>` (see\n * `createConfig` in packages/recorder). The format is a wire contract, not cosmetic —\n * ingestion parses the ISO prefix back out to anchor the inferred-attachment window\n * (`parseTimestampFromFrontendSessionId` in lambda-upload-sessions), and the page uses it to\n * reject an id stale enough to have come from a cache.\n */\nexport const mintProvisionalSessionId = (): string => {\n const bytes = new Uint8Array(ID_LENGTH);\n crypto.getRandomValues(bytes);\n let suffix = \"\";\n for (const byte of bytes) {\n suffix += ID_ALPHABET[byte & 63];\n }\n return `${new Date().toISOString()}_${suffix}`;\n};\n\n/**\n * Whether to mint for this inbound request. Deliberately narrow: an id nothing adopts is\n * worse than no id at all, because a span stamped with a session that never materialises is\n * excluded from the time-window fallback that would otherwise have caught it. So we mint only\n * for what is plausibly a browser navigating to a page.\n *\n * The caller decides separately whether minting is enabled at all.\n */\nexport const isProvisionalSessionIdCandidate = (\n method: string,\n getHeader: HeaderReader,\n): boolean => {\n // A request that already names its session needs nothing from us.\n if (getHeader(FRONTEND_SESSION_ID_HEADER) != null) {\n return false;\n }\n const normalizedMethod = method.toUpperCase();\n if (normalizedMethod !== \"GET\" && normalizedMethod !== \"HEAD\") {\n return false;\n }\n return isDocumentNavigation(getHeader);\n};\n\n/**\n * `Sec-Fetch-Dest` is the exact signal and every current browser sends it: `document` for a\n * navigation, `empty` for an in-page fetch (so a Next.js RSC navigation, which is a fetch, is\n * correctly excluded), `iframe` for a subframe — excluded too, since the top frame owns the\n * session and an iframe recorder reports into it.\n *\n * Absent, the caller is an older browser or not a browser at all (curl, a health check, a\n * crawler), and `Accept` is the only hint left.\n */\nconst isDocumentNavigation = (getHeader: HeaderReader): boolean => {\n const dest = getHeader(\"sec-fetch-dest\");\n if (typeof dest === \"string\") {\n return dest === \"document\";\n }\n const accept = getHeader(\"accept\");\n return typeof accept === \"string\" && accept.includes(\"text/html\");\n};\n"],"names":[],"mappings":";;;;AA0BA,MAAa,uBAAuB;;;;;;;;AASpC,MAAa,+BAA+B;;;;;;AAO5C,MAAa,iCAAiC,cAC5C,GAAG,6BAA6B,SAAS,UAAU;;;;;;;AAQrD,MAAM,cACJ;AACF,MAAM,YAAY;;;;;;;;AASlB,MAAa,iCAAyC;CACpD,MAAM,QAAQ,IAAI,WAAW,UAAU;AACvC,QAAO,gBAAgB,MAAM;CAC7B,IAAI,SAAS;AACb,MAAK,MAAM,QAAQ,MACjB,WAAU,YAAY,OAAO;AAE/B,QAAO,oBAAG,IAAI,MAAM,EAAC,aAAa,CAAC,GAAG;;;;;;;;;;AAWxC,MAAa,mCACX,QACA,cACY;AAEZ,KAAI,UAAA,0BAAqC,IAAI,KAC3C,QAAO;CAET,MAAM,mBAAmB,OAAO,aAAa;AAC7C,KAAI,qBAAqB,SAAS,qBAAqB,OACrD,QAAO;AAET,QAAO,qBAAqB,UAAU;;;;;;;;;;;AAYxC,MAAM,wBAAwB,cAAqC;CACjE,MAAM,OAAO,UAAU,iBAAiB;AACxC,KAAI,OAAO,SAAS,SAClB,QAAO,SAAS;CAElB,MAAM,SAAS,UAAU,SAAS;AAClC,QAAO,OAAO,WAAW,YAAY,OAAO,SAAS,YAAY","debugId":"6222100c-04df-5fc9-b0f6-dcdf8a7b87ab"}
1
+ {"version":3,"file":"provisional-session-id.js","sources":["../src/provisional-session-id.ts"],"sourcesContent":["import { FRONTEND_SESSION_ID_HEADER } from \"./protocol\";\n\n/**\n * A session id the *backend* mints, for the one request that can never carry one from the\n * browser: a top-level document navigation. Browsers cannot add custom headers to a\n * navigation, and on the session-starting navigation the frontend has not minted an id yet\n * (it does so only once the HTML has arrived and the snippet has run) — so the server-side\n * render's spans are recorded against no session and nothing about that traffic can be\n * replayed exactly.\n *\n * Everything here is runtime-agnostic on purpose. Both backend recorders mint the same ids\n * by the same rule and publish them under the same `Server-Timing` metric, and all three are\n * wire contracts with the page, so there is exactly one implementation — the same reason\n * kv-capture.ts lives here rather than being written twice. The Node recorder imports these\n * from the package entry; see `provisional-session-id.ts` in\n * `@alwaysmeticulous/backend-recorder-js` for the `http.IncomingMessage` adapter, and\n * `publish-session-id.ts` next door for the workerd one.\n */\n\n/**\n * Reads one request header by its lower-cased name. Both `IncomingMessage.headers[name]`\n * (after the caller flattens Node's `string | string[]`) and `Headers.get(name)` satisfy it,\n * which is what lets the rules below be shared.\n */\nexport type HeaderReader = (name: string) => string | null | undefined;\n\nexport const SERVER_TIMING_HEADER = \"server-timing\";\n\n/**\n * The `Server-Timing` metric name carrying a backend-minted session id to the page. A wire\n * contract with the frontend recorder, which matches on it case-insensitively when reading\n * `PerformanceNavigationTiming.serverTiming` (see `resolve-session-id.ts` in\n * packages/recorder). Must be a valid HTTP token — no `.` or `:`, which is why it is not the\n * dotted span-attribute name.\n */\nexport const SERVER_TIMING_SESSION_METRIC = \"metsession\";\n\n/**\n * `Server-Timing` is the one response header a document's own JavaScript can read back, and\n * the navigation entry persists for the document's lifetime — so unlike a header-sniffing\n * approach this works no matter how late the snippet loads.\n */\nexport const buildServerTimingSessionEntry = (sessionId: string): string =>\n `${SERVER_TIMING_SESSION_METRIC};desc=\"${sessionId}\"`;\n\n/**\n * nanoid's default alphabet and length, reproduced rather than imported: this package carries\n * no runtime dependencies, and an id that did not look like every other session id would be a\n * gratuitous difference in S3 keys and URLs. 64 characters divides 256 exactly, so masking a\n * random byte with 63 is uniform — which is how nanoid itself generates them.\n */\nconst ID_ALPHABET =\n \"ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW\";\nconst ID_LENGTH = 21;\n\n/**\n * Mints an id in exactly the frontend recorder's format: `<ISO timestamp>_<nanoid>` (see\n * `createConfig` in packages/recorder). The format is a wire contract, not cosmetic —\n * ingestion parses the ISO prefix back out to anchor the inferred-attachment window\n * (`parseTimestampFromFrontendSessionId` in lambda-upload-sessions), and the page uses it to\n * reject an id stale enough to have come from a cache.\n */\nexport const mintProvisionalSessionId = (): string => {\n const bytes = new Uint8Array(ID_LENGTH);\n crypto.getRandomValues(bytes);\n let suffix = \"\";\n for (const byte of bytes) {\n suffix += ID_ALPHABET[byte & 63];\n }\n return `${new Date().toISOString()}_${suffix}`;\n};\n\n/**\n * Whether to mint for this inbound request. Deliberately narrow: an id nothing adopts is\n * worse than no id at all, because a span stamped with a session that never materialises is\n * excluded from the time-window fallback that would otherwise have caught it. So we mint only\n * for what is plausibly a browser navigating to a page.\n *\n * The caller decides separately whether minting is enabled at all.\n */\nexport const isProvisionalSessionIdCandidate = (\n method: string,\n getHeader: HeaderReader,\n): boolean => {\n // A request that already names its session needs nothing from us.\n if (getHeader(FRONTEND_SESSION_ID_HEADER) != null) {\n return false;\n }\n const normalizedMethod = method.toUpperCase();\n if (normalizedMethod !== \"GET\" && normalizedMethod !== \"HEAD\") {\n return false;\n }\n return isDocumentNavigation(getHeader);\n};\n\n/**\n * `Sec-Fetch-Dest` is the exact signal and every current browser sends it: `document` for a\n * navigation, `empty` for an in-page fetch (so a Next.js RSC navigation, which is a fetch, is\n * correctly excluded), `iframe` for a subframe — excluded too, since the top frame owns the\n * session and an iframe recorder reports into it.\n *\n * Absent, the caller is an older browser or not a browser at all (curl, a health check, a\n * crawler), and `Accept` is the only hint left.\n */\nconst isDocumentNavigation = (getHeader: HeaderReader): boolean => {\n const dest = getHeader(\"sec-fetch-dest\");\n if (typeof dest === \"string\") {\n return dest === \"document\";\n }\n const accept = getHeader(\"accept\");\n return typeof accept === \"string\" && accept.includes(\"text/html\");\n};\n"],"names":[],"mappings":";;;;AA0BA,MAAa,uBAAuB;;;;;;;;AASpC,MAAa,+BAA+B;;;;;;AAO5C,MAAa,iCAAiC,cAC5C,GAAG,6BAA6B,SAAS,UAAU;;;;;;;AAQrD,MAAM,cACJ;AACF,MAAM,YAAY;;;;;;;;AASlB,MAAa,iCAAyC;CACpD,MAAM,QAAQ,IAAI,WAAW,UAAU;AACvC,QAAO,gBAAgB,MAAM;CAC7B,IAAI,SAAS;AACb,MAAK,MAAM,QAAQ,MACjB,WAAU,YAAY,OAAO;AAE/B,QAAO,oBAAG,IAAI,MAAM,EAAC,aAAa,CAAC,GAAG;;;;;;;;;;AAWxC,MAAa,mCACX,QACA,cACY;AAEZ,KAAI,UAAA,0BAAqC,IAAI,KAC3C,QAAO;CAET,MAAM,mBAAmB,OAAO,aAAa;AAC7C,KAAI,qBAAqB,SAAS,qBAAqB,OACrD,QAAO;AAET,QAAO,qBAAqB,UAAU;;;;;;;;;;;AAYxC,MAAM,wBAAwB,cAAqC;CACjE,MAAM,OAAO,UAAU,iBAAiB;AACxC,KAAI,OAAO,SAAS,SAClB,QAAO,SAAS;CAElB,MAAM,SAAS,UAAU,SAAS;AAClC,QAAO,OAAO,WAAW,YAAY,OAAO,SAAS,YAAY","debugId":"08993983-84c7-52a8-95ae-69986b1ed730"}
@@ -1,5 +1,5 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f69367d2-e59d-5650-b0fe-e117c8ca00ac")}catch(e){}}();
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="c7b8eed0-1eb8-5c3b-9d7f-7dec5248e263")}catch(e){}}();
3
3
  import { warnOnce } from "./log.js";
4
4
  import { hasWebSocket } from "./outbound-capture.js";
5
5
  import { SERVER_TIMING_HEADER, buildServerTimingSessionEntry } from "./provisional-session-id.js";
@@ -38,4 +38,4 @@ const publishSessionIdOnResponse = (response, sessionId) => {
38
38
  export { publishSessionIdOnResponse };
39
39
 
40
40
  //# sourceMappingURL=publish-session-id.js.map
41
- //# debugId=f69367d2-e59d-5650-b0fe-e117c8ca00ac
41
+ //# debugId=c7b8eed0-1eb8-5c3b-9d7f-7dec5248e263
@@ -1 +1 @@
1
- {"version":3,"file":"publish-session-id.js","sources":["../src/publish-session-id.ts"],"sourcesContent":["import { warnOnce } from \"./log\";\nimport { hasWebSocket } from \"./outbound-capture\";\nimport {\n SERVER_TIMING_HEADER,\n buildServerTimingSessionEntry,\n} from \"./provisional-session-id\";\n\n/**\n * Publishes a backend-minted session id to the page on the response it is about to receive,\n * so the frontend recorder adopts it instead of minting its own and the whole page load —\n * server-side render included — ends up under one session id.\n *\n * Returns the response to send, which is not always the one passed in: a `Response` handed\n * back by `fetch` or by an assets binding has immutable headers, and the only way to add one\n * is to rebuild around the same body. Best-effort throughout — a recorder must never break\n * the customer's app, so anything unexpected returns the original response unchanged.\n *\n * Unlike the Node recorder there is no `headersSent` race to lose: workerd flushes the\n * response only once the handler has returned it to us, so even a streaming SSR body still\n * has its headers in front of it at this point.\n */\nexport const publishSessionIdOnResponse = (\n response: Response,\n sessionId: string,\n): Response => {\n const entry = buildServerTimingSessionEntry(sessionId);\n\n try {\n // Appends rather than replaces: apps publish their own server timings, and clobbering\n // them would be a visible regression in their tooling.\n response.headers.append(SERVER_TIMING_HEADER, entry);\n return response;\n } catch {\n // Immutable headers. Fall through and rebuild.\n }\n\n try {\n // A WebSocket upgrade carries the socket rather than a body and cannot survive being\n // rebuilt; it is never a document navigation either, so there is nothing to publish to.\n if (hasWebSocket(response) || response.status === 101) {\n return response;\n }\n const rebuilt = new Response(response.body, response);\n rebuilt.headers.append(SERVER_TIMING_HEADER, entry);\n return rebuilt;\n } catch (error) {\n warnOnce(\n \"publish-session-id\",\n \"Failed to publish the backend-minted session id on the response.\",\n error,\n );\n return response;\n }\n};\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAqBA,MAAa,8BACX,UACA,cACa;CACb,MAAM,QAAQ,8BAA8B,UAAU;AAEtD,KAAI;AAGF,WAAS,QAAQ,OAAO,sBAAsB,MAAM;AACpD,SAAO;SACD;AAIR,KAAI;AAGF,MAAI,aAAa,SAAS,IAAI,SAAS,WAAW,IAChD,QAAO;EAET,MAAM,UAAU,IAAI,SAAS,SAAS,MAAM,SAAS;AACrD,UAAQ,QAAQ,OAAO,sBAAsB,MAAM;AACnD,SAAO;UACA,OAAO;AACd,WACE,sBACA,oEACA,MACD;AACD,SAAO","debugId":"f69367d2-e59d-5650-b0fe-e117c8ca00ac"}
1
+ {"version":3,"file":"publish-session-id.js","sources":["../src/publish-session-id.ts"],"sourcesContent":["import { warnOnce } from \"./log\";\nimport { hasWebSocket } from \"./outbound-capture\";\nimport {\n SERVER_TIMING_HEADER,\n buildServerTimingSessionEntry,\n} from \"./provisional-session-id\";\n\n/**\n * Publishes a backend-minted session id to the page on the response it is about to receive,\n * so the frontend recorder adopts it instead of minting its own and the whole page load —\n * server-side render included — ends up under one session id.\n *\n * Returns the response to send, which is not always the one passed in: a `Response` handed\n * back by `fetch` or by an assets binding has immutable headers, and the only way to add one\n * is to rebuild around the same body. Best-effort throughout — a recorder must never break\n * the customer's app, so anything unexpected returns the original response unchanged.\n *\n * Unlike the Node recorder there is no `headersSent` race to lose: workerd flushes the\n * response only once the handler has returned it to us, so even a streaming SSR body still\n * has its headers in front of it at this point.\n */\nexport const publishSessionIdOnResponse = (\n response: Response,\n sessionId: string,\n): Response => {\n const entry = buildServerTimingSessionEntry(sessionId);\n\n try {\n // Appends rather than replaces: apps publish their own server timings, and clobbering\n // them would be a visible regression in their tooling.\n response.headers.append(SERVER_TIMING_HEADER, entry);\n return response;\n } catch {\n // Immutable headers. Fall through and rebuild.\n }\n\n try {\n // A WebSocket upgrade carries the socket rather than a body and cannot survive being\n // rebuilt; it is never a document navigation either, so there is nothing to publish to.\n if (hasWebSocket(response) || response.status === 101) {\n return response;\n }\n const rebuilt = new Response(response.body, response);\n rebuilt.headers.append(SERVER_TIMING_HEADER, entry);\n return rebuilt;\n } catch (error) {\n warnOnce(\n \"publish-session-id\",\n \"Failed to publish the backend-minted session id on the response.\",\n error,\n );\n return response;\n }\n};\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAqBA,MAAa,8BACX,UACA,cACa;CACb,MAAM,QAAQ,8BAA8B,UAAU;AAEtD,KAAI;AAGF,WAAS,QAAQ,OAAO,sBAAsB,MAAM;AACpD,SAAO;SACD;AAIR,KAAI;AAGF,MAAI,aAAa,SAAS,IAAI,SAAS,WAAW,IAChD,QAAO;EAET,MAAM,UAAU,IAAI,SAAS,SAAS,MAAM,SAAS;AACrD,UAAQ,QAAQ,OAAO,sBAAsB,MAAM;AACnD,SAAO;UACA,OAAO;AACd,WACE,sBACA,oEACA,MACD;AACD,SAAO","debugId":"c7b8eed0-1eb8-5c3b-9d7f-7dec5248e263"}
@@ -0,0 +1,37 @@
1
+
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="1cb92f56-68e8-5791-b6c7-c8bca161b130")}catch(e){}}();
3
+ import { warnOnce } from "./log.js";
4
+ import { WORKERD_SHIM_VERSION_HEADER } from "./protocol.js";
5
+ import { hasWebSocket } from "./outbound-capture.js";
6
+ import { WORKERD_SHIM_VERSION } from "./version.js";
7
+ //#region src/publish-shim-version.ts
8
+ /**
9
+ * Stamps this shim's npm package version on the response the browser is about
10
+ * to receive, so the replay runner can tell which bundled shim produced the
11
+ * After screenshots.
12
+ *
13
+ * Returns the response to send, which is not always the one passed in: a
14
+ * `Response` handed back by `fetch` or by an assets binding has immutable
15
+ * headers, and the only way to add one is to rebuild around the same body.
16
+ * Best-effort throughout — a recorder must never break the customer's app.
17
+ */
18
+ const publishWorkerdShimVersionOnResponse = (response) => {
19
+ try {
20
+ response.headers.set(WORKERD_SHIM_VERSION_HEADER, WORKERD_SHIM_VERSION);
21
+ return response;
22
+ } catch {}
23
+ try {
24
+ if (hasWebSocket(response) || response.status === 101) return response;
25
+ const rebuilt = new Response(response.body, response);
26
+ rebuilt.headers.set(WORKERD_SHIM_VERSION_HEADER, WORKERD_SHIM_VERSION);
27
+ return rebuilt;
28
+ } catch (error) {
29
+ warnOnce("publish-shim-version", "Failed to publish the workerd shim version on the response.", error);
30
+ return response;
31
+ }
32
+ };
33
+ //#endregion
34
+ export { publishWorkerdShimVersionOnResponse };
35
+
36
+ //# sourceMappingURL=publish-shim-version.js.map
37
+ //# debugId=1cb92f56-68e8-5791-b6c7-c8bca161b130
@@ -0,0 +1 @@
1
+ {"version":3,"file":"publish-shim-version.js","sources":["../src/publish-shim-version.ts"],"sourcesContent":["import { warnOnce } from \"./log\";\nimport { hasWebSocket } from \"./outbound-capture\";\nimport { WORKERD_SHIM_VERSION_HEADER } from \"./protocol\";\nimport { WORKERD_SHIM_VERSION } from \"./version\";\n\n/**\n * Stamps this shim's npm package version on the response the browser is about\n * to receive, so the replay runner can tell which bundled shim produced the\n * After screenshots.\n *\n * Returns the response to send, which is not always the one passed in: a\n * `Response` handed back by `fetch` or by an assets binding has immutable\n * headers, and the only way to add one is to rebuild around the same body.\n * Best-effort throughout — a recorder must never break the customer's app.\n */\nexport const publishWorkerdShimVersionOnResponse = (\n response: Response,\n): Response => {\n try {\n response.headers.set(WORKERD_SHIM_VERSION_HEADER, WORKERD_SHIM_VERSION);\n return response;\n } catch {\n // Immutable headers. Fall through and rebuild.\n }\n\n try {\n // A WebSocket upgrade carries the socket rather than a body and cannot\n // survive being rebuilt.\n if (hasWebSocket(response) || response.status === 101) {\n return response;\n }\n const rebuilt = new Response(response.body, response);\n rebuilt.headers.set(WORKERD_SHIM_VERSION_HEADER, WORKERD_SHIM_VERSION);\n return rebuilt;\n } catch (error) {\n warnOnce(\n \"publish-shim-version\",\n \"Failed to publish the workerd shim version on the response.\",\n error,\n );\n return response;\n }\n};\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAeA,MAAa,uCACX,aACa;AACb,KAAI;AACF,WAAS,QAAQ,IAAI,6BAA6B,qBAAqB;AACvE,SAAO;SACD;AAIR,KAAI;AAGF,MAAI,aAAa,SAAS,IAAI,SAAS,WAAW,IAChD,QAAO;EAET,MAAM,UAAU,IAAI,SAAS,SAAS,MAAM,SAAS;AACrD,UAAQ,QAAQ,IAAI,6BAA6B,qBAAqB;AACtE,SAAO;UACA,OAAO;AACd,WACE,wBACA,+DACA,MACD;AACD,SAAO","debugId":"1cb92f56-68e8-5791-b6c7-c8bca161b130"}
@@ -1,7 +1,7 @@
1
1
  //#region src/redact-body.ts
2
2
  /** Replacement for a redacted value. Matches the Node recorder's redaction marker. */
3
3
 
4
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="36ac86ad-0c78-5b5e-87b8-88acca7728a4")}catch(e){}}();
4
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="c9ea8914-5f33-5a57-a950-20eae083e1d7")}catch(e){}}();
5
5
  const STR_REDACTED = "REDACTED";
6
6
  const secretKeys = new Set([
7
7
  "accesstoken",
@@ -50,4 +50,4 @@ const redactValue = (value) => {
50
50
  export { STR_REDACTED, redactRequestBody };
51
51
 
52
52
  //# sourceMappingURL=redact-body.js.map
53
- //# debugId=36ac86ad-0c78-5b5e-87b8-88acca7728a4
53
+ //# debugId=c9ea8914-5f33-5a57-a950-20eae083e1d7
@@ -1 +1 @@
1
- {"version":3,"file":"redact-body.js","sources":["../src/redact-body.ts"],"sourcesContent":["/** Replacement for a redacted value. Matches the Node recorder's redaction marker. */\nexport const STR_REDACTED = \"REDACTED\";\n\n/**\n * Object keys whose values are replaced before a captured request body leaves the worker.\n *\n * Request bodies are captured verbatim, and plenty of APIs carry a credential in the body\n * rather than a header — an OAuth2 token exchange, or a feature-flag resolver that takes its\n * client secret as a JSON field. Header redaction (an allow-list of two) does nothing for\n * those, so without this the credential would be persisted in the recorded span.\n *\n * Compared case-insensitively, ignoring `_` and `-`, so `clientSecret`, `client_secret` and\n * `CLIENT-SECRET` all match one entry.\n */\nconst SECRET_KEYS = [\n \"accesstoken\",\n \"apikey\",\n \"authorization\",\n \"clientsecret\",\n \"credential\",\n \"idtoken\",\n \"password\",\n \"privatekey\",\n \"refreshtoken\",\n \"secret\",\n \"token\",\n] as const;\n\nconst secretKeys = new Set<string>(SECRET_KEYS);\n\nconst normalizeKey = (key: string): string =>\n key.toLowerCase().replace(/[_-]/g, \"\");\n\nconst isSecretKey = (key: string): boolean => secretKeys.has(normalizeKey(key));\n\n/**\n * Redacts secret-looking fields from a captured request body, returning the body unchanged\n * if it is not JSON.\n *\n * Applied to request bodies only. Response bodies must stay byte-exact: replay serves them\n * back to the app, so redacting one would corrupt what the app receives. Request bodies are\n * only ever used to key a lookup, and because the same function runs on both the record and\n * the replay side the keys still agree.\n *\n * Never throws — a body that cannot be parsed or re-serialized is returned as-is, which is\n * no worse than today's behaviour.\n */\nexport const redactRequestBody = (body: string): string => {\n if (body.length === 0) {\n return body;\n }\n try {\n const parsed: unknown = JSON.parse(body);\n const redacted = redactValue(parsed);\n const serialized = JSON.stringify(redacted);\n return serialized ?? body;\n } catch {\n // Not JSON (form-encoded, protobuf, plain text) — left alone rather than mangled.\n return body;\n }\n};\n\nconst redactValue = (value: unknown): unknown => {\n if (Array.isArray(value)) {\n return value.map(redactValue);\n }\n if (value === null || typeof value !== \"object\") {\n return value;\n }\n const result: Record<string, unknown> = {};\n for (const [key, nested] of Object.entries(value)) {\n result[key] = isSecretKey(key) ? STR_REDACTED : redactValue(nested);\n }\n return result;\n};\n"],"names":[],"mappings":";;;;AACA,MAAa,eAAe;AA2B5B,MAAM,aAAa,IAAI,IAAY;CAbjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAG4C,CAAC;AAE/C,MAAM,gBAAgB,QACpB,IAAI,aAAa,CAAC,QAAQ,SAAS,GAAG;AAExC,MAAM,eAAe,QAAyB,WAAW,IAAI,aAAa,IAAI,CAAC;;;;;;;;;;;;;AAc/E,MAAa,qBAAqB,SAAyB;AACzD,KAAI,KAAK,WAAW,EAClB,QAAO;AAET,KAAI;EAEF,MAAM,WAAW,YADO,KAAK,MAAM,KACA,CAAC;AAEpC,SADmB,KAAK,UAAU,SACjB,IAAI;SACf;AAEN,SAAO;;;AAIX,MAAM,eAAe,UAA4B;AAC/C,KAAI,MAAM,QAAQ,MAAM,CACtB,QAAO,MAAM,IAAI,YAAY;AAE/B,KAAI,UAAU,QAAQ,OAAO,UAAU,SACrC,QAAO;CAET,MAAM,SAAkC,EAAE;AAC1C,MAAK,MAAM,CAAC,KAAK,WAAW,OAAO,QAAQ,MAAM,CAC/C,QAAO,OAAO,YAAY,IAAI,GAAG,eAAe,YAAY,OAAO;AAErE,QAAO","debugId":"36ac86ad-0c78-5b5e-87b8-88acca7728a4"}
1
+ {"version":3,"file":"redact-body.js","sources":["../src/redact-body.ts"],"sourcesContent":["/** Replacement for a redacted value. Matches the Node recorder's redaction marker. */\nexport const STR_REDACTED = \"REDACTED\";\n\n/**\n * Object keys whose values are replaced before a captured request body leaves the worker.\n *\n * Request bodies are captured verbatim, and plenty of APIs carry a credential in the body\n * rather than a header — an OAuth2 token exchange, or a feature-flag resolver that takes its\n * client secret as a JSON field. Header redaction (an allow-list of two) does nothing for\n * those, so without this the credential would be persisted in the recorded span.\n *\n * Compared case-insensitively, ignoring `_` and `-`, so `clientSecret`, `client_secret` and\n * `CLIENT-SECRET` all match one entry.\n */\nconst SECRET_KEYS = [\n \"accesstoken\",\n \"apikey\",\n \"authorization\",\n \"clientsecret\",\n \"credential\",\n \"idtoken\",\n \"password\",\n \"privatekey\",\n \"refreshtoken\",\n \"secret\",\n \"token\",\n] as const;\n\nconst secretKeys = new Set<string>(SECRET_KEYS);\n\nconst normalizeKey = (key: string): string =>\n key.toLowerCase().replace(/[_-]/g, \"\");\n\nconst isSecretKey = (key: string): boolean => secretKeys.has(normalizeKey(key));\n\n/**\n * Redacts secret-looking fields from a captured request body, returning the body unchanged\n * if it is not JSON.\n *\n * Applied to request bodies only. Response bodies must stay byte-exact: replay serves them\n * back to the app, so redacting one would corrupt what the app receives. Request bodies are\n * only ever used to key a lookup, and because the same function runs on both the record and\n * the replay side the keys still agree.\n *\n * Never throws — a body that cannot be parsed or re-serialized is returned as-is, which is\n * no worse than today's behaviour.\n */\nexport const redactRequestBody = (body: string): string => {\n if (body.length === 0) {\n return body;\n }\n try {\n const parsed: unknown = JSON.parse(body);\n const redacted = redactValue(parsed);\n const serialized = JSON.stringify(redacted);\n return serialized ?? body;\n } catch {\n // Not JSON (form-encoded, protobuf, plain text) — left alone rather than mangled.\n return body;\n }\n};\n\nconst redactValue = (value: unknown): unknown => {\n if (Array.isArray(value)) {\n return value.map(redactValue);\n }\n if (value === null || typeof value !== \"object\") {\n return value;\n }\n const result: Record<string, unknown> = {};\n for (const [key, nested] of Object.entries(value)) {\n result[key] = isSecretKey(key) ? STR_REDACTED : redactValue(nested);\n }\n return result;\n};\n"],"names":[],"mappings":";;;;AACA,MAAa,eAAe;AA2B5B,MAAM,aAAa,IAAI,IAAY;CAbjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAG4C,CAAC;AAE/C,MAAM,gBAAgB,QACpB,IAAI,aAAa,CAAC,QAAQ,SAAS,GAAG;AAExC,MAAM,eAAe,QAAyB,WAAW,IAAI,aAAa,IAAI,CAAC;;;;;;;;;;;;;AAc/E,MAAa,qBAAqB,SAAyB;AACzD,KAAI,KAAK,WAAW,EAClB,QAAO;AAET,KAAI;EAEF,MAAM,WAAW,YADO,KAAK,MAAM,KACA,CAAC;AAEpC,SADmB,KAAK,UAAU,SACjB,IAAI;SACf;AAEN,SAAO;;;AAIX,MAAM,eAAe,UAA4B;AAC/C,KAAI,MAAM,QAAQ,MAAM,CACtB,QAAO,MAAM,IAAI,YAAY;AAE/B,KAAI,UAAU,QAAQ,OAAO,UAAU,SACrC,QAAO;CAET,MAAM,SAAkC,EAAE;AAC1C,MAAK,MAAM,CAAC,KAAK,WAAW,OAAO,QAAQ,MAAM,CAC/C,QAAO,OAAO,YAAY,IAAI,GAAG,eAAe,YAAY,OAAO;AAErE,QAAO","debugId":"c9ea8914-5f33-5a57-a950-20eae083e1d7"}
@@ -1,5 +1,5 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a94f1f04-279f-5292-9600-fe52b2a08c6c")}catch(e){}}();
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="151bf2a1-75aa-51ce-be4a-6973d2815547")}catch(e){}}();
3
3
  import { warn, warnOnce } from "./log.js";
4
4
  import { readRequestBodyWithCap } from "./body-capture.js";
5
5
  import { METICULOUS_PASSTHROUGH_HEADER } from "./protocol.js";
@@ -16,12 +16,13 @@ import { postOutboundFetchLookup } from "./sidecar-client.js";
16
16
  * Replay is hermetic: a call the recording does not cover must not silently reach the real
17
17
  * service, since that turns a replay into live traffic against real credentials and hides
18
18
  * the gap in the recording behind a response no base replay will reproduce. So anything we
19
- * cannot serve from the recording — a miss, an unreachable sidecar, a mock that cannot be
20
- * represented — throws, matching the Node recorder's http/undici mocks.
19
+ * cannot serve from the recording — a miss, a call the sidecar cannot look up, an
20
+ * unreachable sidecar, a mock that cannot be represented, or an outcome this shim does not
21
+ * recognise — throws, matching the Node recorder's http/undici mocks.
21
22
  *
22
- * The two ways out are an explicit `meticulous-passthrough: true` header on the request, and
23
- * a sidecar that answers `passthrough` (it cannot look the call up, or it predates
24
- * `no-mock`).
23
+ * The only way out is an explicit `meticulous-passthrough: true` header on the request: a
24
+ * call the customer has marked as one that must reach the real service. A failure to stub is
25
+ * never treated as such a mark.
25
26
  */
26
27
  const replayOutboundCall = async (ctx, request, invoke) => {
27
28
  if (hasPassthroughHeader(request)) return invoke(request);
@@ -40,12 +41,14 @@ const replayOutboundCall = async (ctx, request, invoke) => {
40
41
  }
41
42
  const result = await postOutboundFetchLookup(getOriginalFetch(), ctx.sidecarUrl, lookup);
42
43
  if (result === void 0) throw buildReplayError(request, ctx.frontendSessionId, "the replay sidecar did not answer a mock lookup");
43
- if (result.outcome === "no-mock") throw buildReplayError(request, ctx.frontendSessionId, "no recorded response");
44
- if (result.outcome !== "mock") return invoke(request);
45
- const mocked = buildMockResponse(result);
46
- if (mocked === void 0) throw buildReplayError(request, ctx.frontendSessionId, `the recorded response (status ${result.statusCode}) cannot be represented`);
47
- return mocked;
44
+ if (result.outcome === "mock") {
45
+ const mocked = buildMockResponse(result);
46
+ if (mocked === void 0) throw buildReplayError(request, ctx.frontendSessionId, `the recorded response (status ${result.statusCode}) cannot be represented`);
47
+ return mocked;
48
+ }
49
+ throw buildReplayError(request, ctx.frontendSessionId, describeUnservedOutcome(result.outcome));
48
50
  };
51
+ const describeUnservedOutcome = (outcome) => outcome === "no-mock" ? "no recorded response" : `an unrecognised sidecar outcome (${outcome})`;
49
52
  const hasPassthroughHeader = (request) => {
50
53
  try {
51
54
  return request.headers.get(METICULOUS_PASSTHROUGH_HEADER) === "true";
@@ -127,4 +130,4 @@ const buildMockResponse = (mock) => {
127
130
  export { replayOutboundCall };
128
131
 
129
132
  //# sourceMappingURL=replay-fetch.js.map
130
- //# debugId=a94f1f04-279f-5292-9600-fe52b2a08c6c
133
+ //# debugId=151bf2a1-75aa-51ce-be4a-6973d2815547
@@ -1 +1 @@
1
- {"version":3,"file":"replay-fetch.js","sources":["../src/replay-fetch.ts"],"sourcesContent":["import { readRequestBodyWithCap } from \"./body-capture\";\nimport type { RequestReplayContext } from \"./context\";\nimport { warn, warnOnce } from \"./log\";\nimport { getOriginalFetch } from \"./original-fetch\";\nimport {\n METICULOUS_PASSTHROUGH_HEADER,\n type OutboundFetchLookupRequest,\n} from \"./protocol\";\nimport { postOutboundFetchLookup } from \"./sidecar-client\";\n\n/**\n * Serves a recorded response for an outbound call, or fails it.\n *\n * The mirror image of `captureOutboundCall`: recording tees a call that happens anyway,\n * whereas replay decides first and only then calls — so the sidecar sits in the request\n * path here.\n *\n * Replay is hermetic: a call the recording does not cover must not silently reach the real\n * service, since that turns a replay into live traffic against real credentials and hides\n * the gap in the recording behind a response no base replay will reproduce. So anything we\n * cannot serve from the recording — a miss, an unreachable sidecar, a mock that cannot be\n * represented — throws, matching the Node recorder's http/undici mocks.\n *\n * The two ways out are an explicit `meticulous-passthrough: true` header on the request, and\n * a sidecar that answers `passthrough` (it cannot look the call up, or it predates\n * `no-mock`).\n */\nexport const replayOutboundCall = async (\n ctx: RequestReplayContext,\n request: Request,\n invoke: (request: Request) => Promise<Response>,\n): Promise<Response> => {\n if (hasPassthroughHeader(request)) {\n return invoke(request);\n }\n\n let lookup: OutboundFetchLookupRequest;\n try {\n // Read the clone and pass the original through untouched, mirroring the record path.\n // The sidecar hashes what we send here, and it was captured by the same\n // readRequestBodyWithCap the recorder used (redaction included), so the hashes on both\n // sides derive from byte-identical input.\n const requestBody = request.body\n ? await readRequestBodyWithCap(request.clone().body).catch(\n () => undefined,\n )\n : undefined;\n lookup = {\n frontendSessionId: ctx.frontendSessionId,\n replayId: ctx.replayId,\n method: request.method,\n url: request.url,\n ...(requestBody !== undefined ? { requestBody } : {}),\n };\n } catch (error) {\n // Without a lookup there is nothing to serve, and passing through would be exactly the\n // silent real call this path exists to prevent.\n throw buildReplayError(\n request,\n ctx.frontendSessionId,\n \"could not prepare a mock lookup\",\n error,\n );\n }\n\n const result = await postOutboundFetchLookup(\n getOriginalFetch(),\n ctx.sidecarUrl,\n lookup,\n );\n if (result === undefined) {\n throw buildReplayError(\n request,\n ctx.frontendSessionId,\n \"the replay sidecar did not answer a mock lookup\",\n );\n }\n if (result.outcome === \"no-mock\") {\n throw buildReplayError(\n request,\n ctx.frontendSessionId,\n \"no recorded response\",\n );\n }\n // Covers `passthrough` and an unrecognised `outcome` from a newer sidecar.\n if (result.outcome !== \"mock\") {\n return invoke(request);\n }\n const mocked = buildMockResponse(result);\n if (mocked === undefined) {\n throw buildReplayError(\n request,\n ctx.frontendSessionId,\n `the recorded response (status ${result.statusCode}) cannot be represented`,\n );\n }\n return mocked;\n};\n\nconst hasPassthroughHeader = (request: Request): boolean => {\n try {\n return request.headers.get(METICULOUS_PASSTHROUGH_HEADER) === \"true\";\n } catch {\n return false;\n }\n};\n\n/**\n * Builds — and logs — the error the app sees for a call replay cannot serve. Deliberately\n * names the shim and the session so an app-side stack trace is enough to tell a replay gap\n * from a real bug, and logs as well because an app that catches its own fetch errors would\n * otherwise swallow the only signal.\n *\n * The query string is left out on purpose — it routinely carries API keys, and the sidecar\n * logs the full path anyway.\n */\nconst buildReplayError = (\n request: Request,\n frontendSessionId: string,\n reason: string,\n cause?: unknown,\n): Error => {\n const error = new Error(\n `[backend-recorder] workerd replay: ${reason} for ${describeRequest(request)} (session ${frontendSessionId}). Set the \"${METICULOUS_PASSTHROUGH_HEADER}: true\" header on this request if it must reach the real service during replay.`,\n );\n if (cause !== undefined) {\n // `cause` in the constructor options is not universally available in workerd builds.\n (error as { cause?: unknown }).cause = cause;\n }\n warn(error.message);\n return error;\n};\n\nconst describeRequest = (request: Request): string => {\n let method = \"GET\";\n let url = \"\";\n try {\n method = request.method;\n url = request.url;\n } catch {\n return method;\n }\n try {\n const parsed = new URL(url);\n return `${method} ${parsed.origin}${parsed.pathname}`;\n } catch {\n return `${method} ${url}`;\n }\n};\n\n// Recorded bodies are already decoded and may have been truncated, so the recorded framing\n// headers no longer describe them; the Response constructor recomputes what it needs.\nconst HEADERS_TO_DROP = new Set([\n \"content-encoding\",\n \"content-length\",\n \"transfer-encoding\",\n]);\n\n// Statuses the Response constructor refuses to pair with a body.\nconst NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);\n\n/**\n * Turns a recorded response into a real one, or undefined if it cannot be represented (the\n * constructor throws a RangeError on an out-of-range status, or a body on a null-body\n * status), in which case the caller fails the request.\n *\n * Note recorded headers are limited to CAPTURED_HEADERS, so a mocked response carries\n * essentially just content-type. In particular it can never set cookies — fine for the API\n * calls this path serves, but a real limitation for a backend that authenticates that way.\n */\nconst buildMockResponse = (mock: {\n statusCode: number;\n body: string;\n headers: Record<string, string>;\n}): Response | undefined => {\n try {\n const headers = new Headers();\n for (const [name, value] of Object.entries(mock.headers)) {\n if (HEADERS_TO_DROP.has(name.toLowerCase())) {\n continue;\n }\n try {\n headers.set(name, value);\n } catch {\n // Skip a header name/value the runtime rejects rather than losing the whole mock.\n }\n }\n const body = NULL_BODY_STATUSES.has(mock.statusCode) ? null : mock.body;\n return new Response(body, { status: mock.statusCode, headers });\n } catch (error) {\n warnOnce(\n \"replay-mock-response\",\n \"Could not construct a mocked response.\",\n error,\n );\n return undefined;\n }\n};\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,MAAa,qBAAqB,OAChC,KACA,SACA,WACsB;AACtB,KAAI,qBAAqB,QAAQ,CAC/B,QAAO,OAAO,QAAQ;CAGxB,IAAI;AACJ,KAAI;EAKF,MAAM,cAAc,QAAQ,OACxB,MAAM,uBAAuB,QAAQ,OAAO,CAAC,KAAK,CAAC,YAC3C,KAAA,EACP,GACD,KAAA;AACJ,WAAS;GACP,mBAAmB,IAAI;GACvB,UAAU,IAAI;GACd,QAAQ,QAAQ;GAChB,KAAK,QAAQ;GACb,GAAI,gBAAgB,KAAA,IAAY,EAAE,aAAa,GAAG,EAAE;GACrD;UACM,OAAO;AAGd,QAAM,iBACJ,SACA,IAAI,mBACJ,mCACA,MACD;;CAGH,MAAM,SAAS,MAAM,wBACnB,kBAAkB,EAClB,IAAI,YACJ,OACD;AACD,KAAI,WAAW,KAAA,EACb,OAAM,iBACJ,SACA,IAAI,mBACJ,kDACD;AAEH,KAAI,OAAO,YAAY,UACrB,OAAM,iBACJ,SACA,IAAI,mBACJ,uBACD;AAGH,KAAI,OAAO,YAAY,OACrB,QAAO,OAAO,QAAQ;CAExB,MA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;GAAS,CAAC;UACxD,OAAO;AACd,WACE,wBACA,0CACA,MACD;AACD","debugId":"a94f1f04-279f-5292-9600-fe52b2a08c6c"}
1
+ {"version":3,"file":"replay-fetch.js","sources":["../src/replay-fetch.ts"],"sourcesContent":["import { readRequestBodyWithCap } from \"./body-capture\";\nimport type { RequestReplayContext } from \"./context\";\nimport { warn, warnOnce } from \"./log\";\nimport { getOriginalFetch } from \"./original-fetch\";\nimport {\n METICULOUS_PASSTHROUGH_HEADER,\n type OutboundFetchLookupRequest,\n} from \"./protocol\";\nimport { postOutboundFetchLookup } from \"./sidecar-client\";\n\n/**\n * Serves a recorded response for an outbound call, or fails it.\n *\n * The mirror image of `captureOutboundCall`: recording tees a call that happens anyway,\n * whereas replay decides first and only then calls — so the sidecar sits in the request\n * path here.\n *\n * Replay is hermetic: a call the recording does not cover must not silently reach the real\n * service, since that turns a replay into live traffic against real credentials and hides\n * the gap in the recording behind a response no base replay will reproduce. So anything we\n * cannot serve from the recording — a miss, a call the sidecar cannot look up, an\n * unreachable sidecar, a mock that cannot be represented, or an outcome this shim does not\n * recognise — throws, matching the Node recorder's http/undici mocks.\n *\n * The only way out is an explicit `meticulous-passthrough: true` header on the request: a\n * call the customer has marked as one that must reach the real service. A failure to stub is\n * never treated as such a mark.\n */\nexport const replayOutboundCall = async (\n ctx: RequestReplayContext,\n request: Request,\n invoke: (request: Request) => Promise<Response>,\n): Promise<Response> => {\n if (hasPassthroughHeader(request)) {\n return invoke(request);\n }\n\n let lookup: OutboundFetchLookupRequest;\n try {\n // Read the clone and pass the original through untouched, mirroring the record path.\n // The sidecar hashes what we send here, and it was captured by the same\n // readRequestBodyWithCap the recorder used (redaction included), so the hashes on both\n // sides derive from byte-identical input.\n const requestBody = request.body\n ? await readRequestBodyWithCap(request.clone().body).catch(\n () => undefined,\n )\n : undefined;\n lookup = {\n frontendSessionId: ctx.frontendSessionId,\n replayId: ctx.replayId,\n method: request.method,\n url: request.url,\n ...(requestBody !== undefined ? { requestBody } : {}),\n };\n } catch (error) {\n // Without a lookup there is nothing to serve, and passing through would be exactly the\n // silent real call this path exists to prevent.\n throw buildReplayError(\n request,\n ctx.frontendSessionId,\n \"could not prepare a mock lookup\",\n error,\n );\n }\n\n const result = await postOutboundFetchLookup(\n getOriginalFetch(),\n ctx.sidecarUrl,\n lookup,\n );\n if (result === undefined) {\n throw buildReplayError(\n request,\n ctx.frontendSessionId,\n \"the replay sidecar did not answer a mock lookup\",\n );\n }\n if (result.outcome === \"mock\") {\n const mocked = buildMockResponse(result);\n if (mocked === undefined) {\n throw buildReplayError(\n request,\n ctx.frontendSessionId,\n `the recorded response (status ${result.statusCode}) cannot be represented`,\n );\n }\n return mocked;\n }\n // Every other outcome is a failure to stub — a miss (`no-mock`) or an outcome this shim\n // does not recognise (e.g. a legacy `passthrough`). None may reach the real service, so we\n // fail the request; the only path to a live call is the explicit passthrough header\n // handled above.\n throw buildReplayError(\n request,\n ctx.frontendSessionId,\n describeUnservedOutcome(result.outcome),\n );\n};\n\nconst describeUnservedOutcome = (outcome: string): string =>\n outcome === \"no-mock\"\n ? \"no recorded response\"\n : `an unrecognised sidecar outcome (${outcome})`;\n\nconst hasPassthroughHeader = (request: Request): boolean => {\n try {\n return request.headers.get(METICULOUS_PASSTHROUGH_HEADER) === \"true\";\n } catch {\n return false;\n }\n};\n\n/**\n * Builds — and logs — the error the app sees for a call replay cannot serve. Deliberately\n * names the shim and the session so an app-side stack trace is enough to tell a replay gap\n * from a real bug, and logs as well because an app that catches its own fetch errors would\n * otherwise swallow the only signal.\n *\n * The query string is left out on purpose — it routinely carries API keys, and the sidecar\n * logs the full path anyway.\n */\nconst buildReplayError = (\n request: Request,\n frontendSessionId: string,\n reason: string,\n cause?: unknown,\n): Error => {\n const error = new Error(\n `[backend-recorder] workerd replay: ${reason} for ${describeRequest(request)} (session ${frontendSessionId}). Set the \"${METICULOUS_PASSTHROUGH_HEADER}: true\" header on this request if it must reach the real service during replay.`,\n );\n if (cause !== undefined) {\n // `cause` in the constructor options is not universally available in workerd builds.\n (error as { cause?: unknown }).cause = cause;\n }\n warn(error.message);\n return error;\n};\n\nconst describeRequest = (request: Request): string => {\n let method = \"GET\";\n let url = \"\";\n try {\n method = request.method;\n url = request.url;\n } catch {\n return method;\n }\n try {\n const parsed = new URL(url);\n return `${method} ${parsed.origin}${parsed.pathname}`;\n } catch {\n return `${method} ${url}`;\n }\n};\n\n// Recorded bodies are already decoded and may have been truncated, so the recorded framing\n// headers no longer describe them; the Response constructor recomputes what it needs.\nconst HEADERS_TO_DROP = new Set([\n \"content-encoding\",\n \"content-length\",\n \"transfer-encoding\",\n]);\n\n// Statuses the Response constructor refuses to pair with a body.\nconst NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);\n\n/**\n * Turns a recorded response into a real one, or undefined if it cannot be represented (the\n * constructor throws a RangeError on an out-of-range status, or a body on a null-body\n * status), in which case the caller fails the request.\n *\n * Note recorded headers are limited to CAPTURED_HEADERS, so a mocked response carries\n * essentially just content-type. In particular it can never set cookies — fine for the API\n * calls this path serves, but a real limitation for a backend that authenticates that way.\n */\nconst buildMockResponse = (mock: {\n statusCode: number;\n body: string;\n headers: Record<string, string>;\n}): Response | undefined => {\n try {\n const headers = new Headers();\n for (const [name, value] of Object.entries(mock.headers)) {\n if (HEADERS_TO_DROP.has(name.toLowerCase())) {\n continue;\n }\n try {\n headers.set(name, value);\n } catch {\n // Skip a header name/value the runtime rejects rather than losing the whole mock.\n }\n }\n const body = NULL_BODY_STATUSES.has(mock.statusCode) ? null : mock.body;\n return new Response(body, { status: mock.statusCode, headers });\n } catch (error) {\n warnOnce(\n \"replay-mock-response\",\n \"Could not construct a mocked response.\",\n error,\n );\n return undefined;\n }\n};\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,MAAa,qBAAqB,OAChC,KACA,SACA,WACsB;AACtB,KAAI,qBAAqB,QAAQ,CAC/B,QAAO,OAAO,QAAQ;CAGxB,IAAI;AACJ,KAAI;EAKF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