experimental-a2 0.9.0 → 0.11.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 (123) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/dist/actor-D_54lz_1.d.ts +310 -0
  3. package/dist/actor-D_54lz_1.d.ts.map +1 -0
  4. package/dist/actor-client.d.ts +13 -4
  5. package/dist/actor-client.d.ts.map +1 -1
  6. package/dist/actor-client.js +63 -7
  7. package/dist/actor-client.js.map +1 -1
  8. package/dist/actor-react.d.ts +5 -4
  9. package/dist/actor-react.d.ts.map +1 -1
  10. package/dist/actor-react.js +16 -2
  11. package/dist/actor-react.js.map +1 -1
  12. package/dist/actor.d.ts +2 -176
  13. package/dist/actor.js +13 -2
  14. package/dist/actor.js.map +1 -1
  15. package/dist/ai-server.d.ts +1 -1
  16. package/dist/ai-server.js +2 -2
  17. package/dist/ai.d.ts +1 -1
  18. package/dist/ai.js +1 -1
  19. package/dist/client-Bf6uSEAk.js +1342 -0
  20. package/dist/client-Bf6uSEAk.js.map +1 -0
  21. package/dist/client-P_NNNRM-.d.ts +243 -0
  22. package/dist/client-P_NNNRM-.d.ts.map +1 -0
  23. package/dist/client.d.ts +2 -202
  24. package/dist/client.js +2 -1026
  25. package/dist/errors-DCk6ch5n.js.map +1 -1
  26. package/dist/errors-DvhSXnxk.d.ts +28 -0
  27. package/dist/errors-DvhSXnxk.d.ts.map +1 -0
  28. package/dist/index.d.ts +3 -35
  29. package/dist/{internal-DRXJ56EI.js → internal-Dq2qYxou.js} +2 -2
  30. package/dist/{internal-DRXJ56EI.js.map → internal-Dq2qYxou.js.map} +1 -1
  31. package/dist/platform-B4TnJtWu.js +34 -0
  32. package/dist/platform-B4TnJtWu.js.map +1 -0
  33. package/dist/react.d.ts +3 -1
  34. package/dist/react.d.ts.map +1 -1
  35. package/dist/react.js +2 -1
  36. package/dist/react.js.map +1 -1
  37. package/dist/scheduler-qstash.d.ts +2 -2
  38. package/dist/scheduler-qstash.js +3 -2
  39. package/dist/scheduler-qstash.js.map +1 -1
  40. package/dist/scheduler-vercel.d.ts +2 -2
  41. package/dist/scheduler-vercel.js +2 -2
  42. package/dist/{server-CBET-jSz.js → server-Dkz2a84E.js} +295 -133
  43. package/dist/server-Dkz2a84E.js.map +1 -0
  44. package/dist/{server-CKY3_lbw.d.ts → server-DwPrMqHB.d.ts} +4 -2
  45. package/dist/server-DwPrMqHB.d.ts.map +1 -0
  46. package/dist/server.d.ts +2 -2
  47. package/dist/server.js +1 -1
  48. package/dist/{store-DGHeBtIQ.d.ts → store-DtDOWLSn.d.ts} +4 -5
  49. package/dist/{store-DGHeBtIQ.d.ts.map → store-DtDOWLSn.d.ts.map} +1 -1
  50. package/dist/store-N8PXxDAS.js.map +1 -1
  51. package/dist/store-memory.d.ts +1 -1
  52. package/dist/store-memory.js +1 -1
  53. package/dist/{store-polling-6DW7F1DT.js → store-polling-CmxUbV93.js} +56 -7
  54. package/dist/store-polling-CmxUbV93.js.map +1 -0
  55. package/dist/store-postgres.d.ts +6 -4
  56. package/dist/store-postgres.d.ts.map +1 -1
  57. package/dist/store-postgres.js +701 -53
  58. package/dist/store-postgres.js.map +1 -1
  59. package/dist/store-presence-polling-C7-XZyW9.js +94 -0
  60. package/dist/store-presence-polling-C7-XZyW9.js.map +1 -0
  61. package/dist/store-redis-http.d.ts +2 -2
  62. package/dist/store-redis-http.d.ts.map +1 -1
  63. package/dist/store-redis-http.js +184 -38
  64. package/dist/store-redis-http.js.map +1 -1
  65. package/dist/{store-redis-core-z-ykbyMg.js → store-redis-notify-BUCyXOn0.js} +491 -27
  66. package/dist/store-redis-notify-BUCyXOn0.js.map +1 -0
  67. package/dist/store-redis.d.ts +5 -13
  68. package/dist/store-redis.d.ts.map +1 -1
  69. package/dist/store-redis.js +27 -271
  70. package/dist/store-redis.js.map +1 -1
  71. package/dist/store-sqlite.d.ts +1 -1
  72. package/dist/store-sqlite.js +1 -1
  73. package/dist/{wire--yji6mO3.js → wire-BO5wWCb1.js} +18 -16
  74. package/dist/wire-BO5wWCb1.js.map +1 -0
  75. package/docs/actors/04-routes.mdx +40 -8
  76. package/docs/guides/03-react.mdx +52 -10
  77. package/docs/guides/05-production.mdx +54 -5
  78. package/docs/guides/09-presence.mdx +12 -7
  79. package/docs/guides/10-transports.mdx +85 -22
  80. package/docs/reference/01-api.mdx +90 -28
  81. package/docs/reference/02-errors.mdx +45 -11
  82. package/examples/playground/package.json +1 -1
  83. package/package.json +1 -1
  84. package/src/actor-client.ts +114 -14
  85. package/src/actor-react.ts +18 -3
  86. package/src/actor.ts +16 -1
  87. package/src/client-errors.ts +51 -0
  88. package/src/client.ts +577 -175
  89. package/src/errors.ts +4 -9
  90. package/src/index.ts +1 -1
  91. package/src/internal.ts +1 -1
  92. package/src/postgres-notification-scope.ts +134 -0
  93. package/src/postgres-notifications.ts +244 -0
  94. package/src/postgres-pool.ts +65 -0
  95. package/src/postgres-resources.ts +185 -0
  96. package/src/presence-recovery.ts +120 -0
  97. package/src/react.ts +3 -0
  98. package/src/redis-http-subscriptions.ts +199 -0
  99. package/src/server-fetch.ts +51 -23
  100. package/src/server.ts +146 -19
  101. package/src/session-socket.ts +241 -88
  102. package/src/sse.ts +17 -0
  103. package/src/store-polling.ts +32 -12
  104. package/src/store-postgres.ts +292 -75
  105. package/src/store-presence-polling.ts +125 -0
  106. package/src/store-redis-core.ts +37 -30
  107. package/src/store-redis-http.ts +51 -45
  108. package/src/store-redis-notify.ts +464 -0
  109. package/src/store-redis.ts +9 -364
  110. package/src/store.ts +3 -4
  111. package/src/stream-activity.ts +32 -0
  112. package/src/wire.ts +39 -15
  113. package/dist/actor-shared-BACubf4x.d.ts +0 -136
  114. package/dist/actor-shared-BACubf4x.d.ts.map +0 -1
  115. package/dist/actor.d.ts.map +0 -1
  116. package/dist/client.d.ts.map +0 -1
  117. package/dist/client.js.map +0 -1
  118. package/dist/index.d.ts.map +0 -1
  119. package/dist/server-CBET-jSz.js.map +0 -1
  120. package/dist/server-CKY3_lbw.d.ts.map +0 -1
  121. package/dist/store-polling-6DW7F1DT.js.map +0 -1
  122. package/dist/store-redis-core-z-ykbyMg.js.map +0 -1
  123. package/dist/wire--yji6mO3.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"errors-DCk6ch5n.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/**\n * a2 errors — one class, discriminated by `code`.\n *\n * See specs/a2-implementation.md §10 and docs/reference/02-errors.mdx.\n * A single class serializes cleanly across the push-route boundary and\n * keeps `instanceof` checks working after bundling.\n */\n\nexport type A2ErrorCode =\n | 'INVALID_PAYLOAD' // schema validation failed — thrown before anything is written\n | 'FORBIDDEN' // external ingress was denied by server.fetch authorization\n | 'UNKNOWN_EVENT_TYPE' // event type not in the machine's `events` map\n | 'PARTIAL_DUPLICATE_BATCH' // batch mixed already-appended and fresh events\n | 'SUPERSEDED_ATTEMPT' // handler append from an attempt a recovery claim replaced\n | 'CLAIM_EXPIRED' // ctx.signal abort reason: the attempt's lease lapsed without renewal\n | 'STORE_UNAVAILABLE' // store backend failure — retryable, nothing was written\n | 'STORE_NOT_CONFIGURED' // production boot with no `store` passed\n | 'UNKNOWN_PRESENCE_FIELD' // presence field not in the contract's `presence` map\n | 'PRESENCE_NOT_SUPPORTED' // contract declares presence but the store lacks the capability\n\nexport class A2Error extends Error {\n readonly code: A2ErrorCode\n /** e.g. the Standard Schema issues for INVALID_PAYLOAD */\n readonly details: unknown\n\n constructor(\n code: A2ErrorCode,\n message: string,\n options?: { details?: unknown; cause?: unknown },\n ) {\n super(\n message,\n options && 'cause' in options ? { cause: options.cause } : undefined,\n )\n this.name = 'A2Error'\n this.code = code\n this.details = options?.details\n }\n}\n\n/**\n * Wrap an arbitrary thrown value as STORE_UNAVAILABLE, preserving the\n * original as `cause`. A2Errors pass through untouched — they already\n * carry their own meaning.\n */\nexport function asStoreUnavailable(err: unknown): A2Error {\n if (err instanceof A2Error) return err\n return new A2Error('STORE_UNAVAILABLE', 'the store backend failed', {\n cause: err,\n })\n}\n\n/**\n * Throw from a handler to reject retrying: the failure is adjudicated\n * terminal immediately (dead-lettered on the first throw) instead of\n * consuming the ten-failure retry budget. For deterministic failures —\n * a guard that will refuse identically on every attempt — retrying is\n * waste and dead-lettering is the honest outcome. Matched by\n * `instanceof`, so subclasses carry domain meaning.\n */\nexport class NonRetriableError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options)\n this.name = 'NonRetriableError'\n }\n}\n"],"mappings":";AAoBA,IAAa,UAAb,cAA6B,MAAM;CACjC;;CAEA;CAEA,YACE,MACA,SACA,SACA;EACA,MACE,SACA,WAAW,WAAW,UAAU,EAAE,OAAO,QAAQ,MAAM,IAAI,KAAA,CAC7D;EACA,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,UAAU,SAAS;CAC1B;AACF;;;;;;AAOA,SAAgB,mBAAmB,KAAuB;CACxD,IAAI,eAAe,SAAS,OAAO;CACnC,OAAO,IAAI,QAAQ,qBAAqB,4BAA4B,EAClE,OAAO,IACT,CAAC;AACH;;;;;;;;;AAUA,IAAa,oBAAb,cAAuC,MAAM;CAC3C,YAAY,SAAiB,SAA+B;EAC1D,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO;CACd;AACF"}
1
+ {"version":3,"file":"errors-DCk6ch5n.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["export type A2ServerErrorCode =\n | 'INVALID_PAYLOAD' // schema validation failed — thrown before anything is written\n | 'FORBIDDEN' // external ingress was denied by server.fetch authorization\n | 'UNKNOWN_EVENT_TYPE' // event type not in the machine's `events` map\n | 'PARTIAL_DUPLICATE_BATCH' // batch mixed already-appended and fresh events\n | 'SUPERSEDED_ATTEMPT' // handler append from an attempt a recovery claim replaced\n | 'CLAIM_EXPIRED' // ctx.signal abort reason: the attempt's lease lapsed without renewal\n | 'STORE_UNAVAILABLE' // store backend failure — retryable, nothing was written\n | 'STORE_NOT_CONFIGURED' // production boot with no `store` passed\n | 'UNKNOWN_PRESENCE_FIELD' // presence field not in the contract's `presence` map\n | 'PRESENCE_NOT_SUPPORTED' // contract declares presence but the store lacks the capability\n\nexport type A2ErrorCode =\n A2ServerErrorCode | 'TIMEOUT' | 'HTTP_ERROR' | 'CONNECTION_FAILED' | 'UNKNOWN'\n\nexport class A2Error extends Error {\n readonly code: A2ErrorCode\n /** e.g. the Standard Schema issues for INVALID_PAYLOAD */\n readonly details: unknown\n\n constructor(\n code: A2ErrorCode,\n message: string,\n options?: { details?: unknown; cause?: unknown },\n ) {\n super(\n message,\n options && 'cause' in options ? { cause: options.cause } : undefined,\n )\n this.name = 'A2Error'\n this.code = code\n this.details = options?.details\n }\n}\n\n/**\n * Wrap an arbitrary thrown value as STORE_UNAVAILABLE, preserving the\n * original as `cause`. A2Errors pass through untouched — they already\n * carry their own meaning.\n */\nexport function asStoreUnavailable(err: unknown): A2Error {\n if (err instanceof A2Error) return err\n return new A2Error('STORE_UNAVAILABLE', 'the store backend failed', {\n cause: err,\n })\n}\n\n/**\n * Throw from a handler to reject retrying: the failure is adjudicated\n * terminal immediately (dead-lettered on the first throw) instead of\n * consuming the ten-failure retry budget. For deterministic failures —\n * a guard that will refuse identically on every attempt — retrying is\n * waste and dead-lettering is the honest outcome. Matched by\n * `instanceof`, so subclasses carry domain meaning.\n */\nexport class NonRetriableError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options)\n this.name = 'NonRetriableError'\n }\n}\n"],"mappings":";AAeA,IAAa,UAAb,cAA6B,MAAM;CACjC;;CAEA;CAEA,YACE,MACA,SACA,SACA;EACA,MACE,SACA,WAAW,WAAW,UAAU,EAAE,OAAO,QAAQ,MAAM,IAAI,KAAA,CAC7D;EACA,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,UAAU,SAAS;CAC1B;AACF;;;;;;AAOA,SAAgB,mBAAmB,KAAuB;CACxD,IAAI,eAAe,SAAS,OAAO;CACnC,OAAO,IAAI,QAAQ,qBAAqB,4BAA4B,EAClE,OAAO,IACT,CAAC;AACH;;;;;;;;;AAUA,IAAa,oBAAb,cAAuC,MAAM;CAC3C,YAAY,SAAiB,SAA+B;EAC1D,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO;CACd;AACF"}
@@ -0,0 +1,28 @@
1
+ //#region src/errors.d.ts
2
+ type A2ServerErrorCode = "INVALID_PAYLOAD" | "FORBIDDEN" | "UNKNOWN_EVENT_TYPE" | "PARTIAL_DUPLICATE_BATCH" | "SUPERSEDED_ATTEMPT" | "CLAIM_EXPIRED" | "STORE_UNAVAILABLE" | "STORE_NOT_CONFIGURED" | "UNKNOWN_PRESENCE_FIELD" | "PRESENCE_NOT_SUPPORTED";
3
+ type A2ErrorCode = A2ServerErrorCode | "TIMEOUT" | "HTTP_ERROR" | "CONNECTION_FAILED" | "UNKNOWN";
4
+ declare class A2Error extends Error {
5
+ readonly code: A2ErrorCode;
6
+ /** e.g. the Standard Schema issues for INVALID_PAYLOAD */
7
+ readonly details: unknown;
8
+ constructor(code: A2ErrorCode, message: string, options?: {
9
+ details?: unknown;
10
+ cause?: unknown;
11
+ });
12
+ }
13
+ /**
14
+ * Throw from a handler to reject retrying: the failure is adjudicated
15
+ * terminal immediately (dead-lettered on the first throw) instead of
16
+ * consuming the ten-failure retry budget. For deterministic failures —
17
+ * a guard that will refuse identically on every attempt — retrying is
18
+ * waste and dead-lettering is the honest outcome. Matched by
19
+ * `instanceof`, so subclasses carry domain meaning.
20
+ */
21
+ declare class NonRetriableError extends Error {
22
+ constructor(message: string, options?: {
23
+ cause?: unknown;
24
+ });
25
+ }
26
+ //#endregion
27
+ export { NonRetriableError as i, A2ErrorCode as n, A2ServerErrorCode as r, A2Error as t };
28
+ //# sourceMappingURL=errors-DvhSXnxk.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors-DvhSXnxk.d.ts","names":[],"sources":["../src/errors.ts"],"mappings":";KAAY;KAYA,cACV;cAEW,gBAAgB;WAClB,MAAM;;WAEN;EAET,YACE,MAAM,aACN,iBACA;IAAY;IAAmB;;;;;;;;;;;cAgCtB,0BAA0B;EACrC,YAAY,iBAAiB;IAAY"}
package/dist/index.d.ts CHANGED
@@ -1,37 +1,5 @@
1
1
  import { a as ContractEvent, c as PresenceDefs, d as PresenceSnapshot, f as ReducerOptions, h as StandardSchemaV1, i as Contract, l as PresenceMap, m as contract, n as ReducerBuilder, o as EventBatchFactory, r as AppendInput, s as EventDefs, t as Reducer, u as PresencePatch } from "./reducer-DJKWm3cp.js";
2
- import { i as Event } from "./store-DGHeBtIQ.js";
2
+ import { i as Event } from "./store-DtDOWLSn.js";
3
+ import { i as NonRetriableError, n as A2ErrorCode, r as A2ServerErrorCode, t as A2Error } from "./errors-DvhSXnxk.js";
3
4
  import { i as A2Telemetry, n as A2SpanHandle, r as A2SpanName, t as A2AttributeValue } from "./telemetry-CpeclqB2.js";
4
- //#region src/errors.d.ts
5
- /**
6
- * a2 errors — one class, discriminated by `code`.
7
- *
8
- * See specs/a2-implementation.md §10 and docs/reference/02-errors.mdx.
9
- * A single class serializes cleanly across the push-route boundary and
10
- * keeps `instanceof` checks working after bundling.
11
- */
12
- type A2ErrorCode = "INVALID_PAYLOAD" | "FORBIDDEN" | "UNKNOWN_EVENT_TYPE" | "PARTIAL_DUPLICATE_BATCH" | "SUPERSEDED_ATTEMPT" | "CLAIM_EXPIRED" | "STORE_UNAVAILABLE" | "STORE_NOT_CONFIGURED" | "UNKNOWN_PRESENCE_FIELD" | "PRESENCE_NOT_SUPPORTED";
13
- declare class A2Error extends Error {
14
- readonly code: A2ErrorCode;
15
- /** e.g. the Standard Schema issues for INVALID_PAYLOAD */
16
- readonly details: unknown;
17
- constructor(code: A2ErrorCode, message: string, options?: {
18
- details?: unknown;
19
- cause?: unknown;
20
- });
21
- }
22
- /**
23
- * Throw from a handler to reject retrying: the failure is adjudicated
24
- * terminal immediately (dead-lettered on the first throw) instead of
25
- * consuming the ten-failure retry budget. For deterministic failures —
26
- * a guard that will refuse identically on every attempt — retrying is
27
- * waste and dead-lettering is the honest outcome. Matched by
28
- * `instanceof`, so subclasses carry domain meaning.
29
- */
30
- declare class NonRetriableError extends Error {
31
- constructor(message: string, options?: {
32
- cause?: unknown;
33
- });
34
- }
35
- //#endregion
36
- export { type A2AttributeValue, A2Error, type A2ErrorCode, type A2SpanHandle, type A2SpanName, type A2Telemetry, type AppendInput, type Contract, type ContractEvent, type Event, type EventBatchFactory, type EventDefs, NonRetriableError, type PresenceDefs, type PresenceMap, type PresencePatch, type PresenceSnapshot, type Reducer, type ReducerBuilder, type ReducerOptions, type StandardSchemaV1, contract };
37
- //# sourceMappingURL=index.d.ts.map
5
+ export { type A2AttributeValue, A2Error, type A2ErrorCode, type A2ServerErrorCode, type A2SpanHandle, type A2SpanName, type A2Telemetry, type AppendInput, type Contract, type ContractEvent, type Event, type EventBatchFactory, type EventDefs, NonRetriableError, type PresenceDefs, type PresenceMap, type PresencePatch, type PresenceSnapshot, type Reducer, type ReducerBuilder, type ReducerOptions, type StandardSchemaV1, contract };
@@ -141,7 +141,7 @@ const DRAIN_TIMINGS = {
141
141
  */
142
142
  const POLL_TIMINGS = {
143
143
  activeFloorMs: 25,
144
- idleCeilingMs: 250
144
+ idleCeilingMs: 2e3
145
145
  };
146
146
  /**
147
147
  * Safety-read cadence for the notify-driven redis live stream. A
@@ -185,4 +185,4 @@ const PRESENCE_TIMINGS = { sendIntervalMs: 66 };
185
185
  //#endregion
186
186
  export { PRESENCE_TIMINGS as a, STREAM_TIMINGS as c, classifySchedulerSendFailure as d, consumeSchedulerSendFailure as f, serverInternals as g, nullProtoRecord as h, POLL_TIMINGS as i, ambientToolScopeStorage as l, markSchedulerSendFailure as m, MAX_DATE_MS as n, RESERVED_PARTICIPANT_IDS as o, installAmbientToolScopeStorage as p, NOTIFY_TIMINGS as r, SOCKET_TIMINGS as s, DRAIN_TIMINGS as t, assertSchedulerTargets as u };
187
187
 
188
- //# sourceMappingURL=internal-DRXJ56EI.js.map
188
+ //# sourceMappingURL=internal-Dq2qYxou.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"internal-DRXJ56EI.js","names":[],"sources":["../src/internal.ts"],"sourcesContent":["/**\n * Private seams shared by a2 entry points and a2's own tests. Not exported\n * from the package. Nothing here is public API.\n */\n\nimport type { ScheduledEvent } from './scheduler-task.ts'\nimport type { DrainableServer } from './server.ts'\n\nexport type DrainOutcome = 'busy' | 'stalled' | 'settled'\n\n/**\n * A null-prototype record for maps keyed by caller-controlled strings\n * (participant ids, presence field names). On a normal object,\n * assigning to '__proto__' rewrites the prototype instead of creating\n * an own property — the prototype-pollution class. Null-prototype\n * objects still satisfy Record types and JSON.stringify cleanly.\n */\nexport function nullProtoRecord<T extends object>(): T {\n return Object.create(null) as T\n}\n\n/**\n * ECMA-262's maximum Date value (±8.64e15 ms). A presence stamp past\n * it becomes an Invalid Date whose toISOString throws — one hostile\n * stamp would poison every subscriber's snapshot frame — so both\n * seams bound `at` to the representable range.\n */\nexport const MAX_DATE_MS = 8_640_000_000_000_000\n\n/**\n * Participant ids that collide with Object.prototype plumbing.\n * Null-prototype construction already defuses them, but they are\n * rejected at both seams (`parsePushBody`, `setPresence`) so a hostile\n * id never propagates into userland maps either.\n */\nexport const RESERVED_PARTICIPANT_IDS: ReadonlySet<string> = new Set([\n '__proto__',\n 'constructor',\n 'prototype',\n])\n\nexport type DrainResult = {\n settled: boolean\n outcome: DrainOutcome\n /** Existing successor arm a scheduler callback may join before acking. */\n schedulerArm?: Promise<void>\n}\n\nexport type ServerInternals = {\n /**\n * Await every in-flight background drain this machine has scheduled,\n * including ones scheduled while waiting. Lets tests flush the\n * fire-and-forget inline path deterministically — no sleeps.\n */\n settle(): Promise<void>\n /** The public `server.drain()` result deliberately remains `{ settled }`. */\n schedulerDrain(\n sessionId: string,\n opts?: { watchdogDueAt?: number },\n ): Promise<DrainResult>\n /** Deliver a scheduler-owned delayed append through the normal root path. */\n schedulerAppend(\n sessionId: string,\n events: readonly ScheduledEvent[],\n ): Promise<void>\n}\n\nexport const serverInternals: WeakMap<object, ServerInternals> = new WeakMap()\n\nconst objectLike = (value: unknown): value is object =>\n (typeof value === 'object' && value !== null) || typeof value === 'function'\n\n/** The ambient value delivered to `handlerContext` during a tool execution. */\nexport type AmbientToolScope = {\n /** Executing server identity; a test scope from `runWithHandlerContext` has none. */\n contract?: { readonly name: string }\n context: unknown\n}\n\n/**\n * Structural AsyncLocalStorage surface for the ambient tool scope. The\n * instance is created by the server-only AI entry point (the only place\n * `node:async_hooks` may be imported) and shared through a global\n * symbol slot, so `handlerContext` in the isomorphic AI entry point and\n * independently bundled A2 copies all read the same scope.\n */\nexport type AmbientToolScopeStorage = {\n getStore(): AmbientToolScope | undefined\n run<R>(store: AmbientToolScope, callback: () => R): R\n}\n\nconst TOOL_SCOPE_STORAGE = Symbol.for('experimental-a2.ai.tool-scope')\n\nexport function ambientToolScopeStorage(): AmbientToolScopeStorage | undefined {\n const value = Reflect.get(globalThis, TOOL_SCOPE_STORAGE)\n if (\n !objectLike(value) ||\n typeof Reflect.get(value, 'getStore') !== 'function' ||\n typeof Reflect.get(value, 'run') !== 'function'\n ) {\n return undefined\n }\n return value as AmbientToolScopeStorage\n}\n\nexport function installAmbientToolScopeStorage(\n create: () => AmbientToolScopeStorage,\n): AmbientToolScopeStorage {\n const existing = ambientToolScopeStorage()\n if (existing !== undefined) return existing\n const storage = create()\n Reflect.set(globalThis, TOOL_SCOPE_STORAGE, storage)\n return storage\n}\n\nexport type SchedulerSendFailureDisposition = 'retryable' | 'terminal'\n\ntype SchedulerSendFailureMarker = {\n readonly version: 1\n readonly pending: SchedulerSendFailureDisposition[]\n readonly active: SchedulerSendFailureDisposition[]\n}\n\nconst SCHEDULER_SEND_FAILURE = Symbol.for(\n 'experimental-a2.scheduler.send-failure',\n)\n\nconst schedulerSendFailureMarker = (\n value: unknown,\n): SchedulerSendFailureMarker | undefined => {\n if (!objectLike(value)) return undefined\n const marker = Reflect.get(value, SCHEDULER_SEND_FAILURE)\n if (\n !objectLike(marker) ||\n Reflect.get(marker, 'version') !== 1 ||\n !Array.isArray(Reflect.get(marker, 'pending')) ||\n !Array.isArray(Reflect.get(marker, 'active'))\n ) {\n return undefined\n }\n return marker as SchedulerSendFailureMarker\n}\n\nconst schedulerFailureObject = (error: unknown): object => {\n if (\n objectLike(error) &&\n (schedulerSendFailureMarker(error) !== undefined ||\n Object.isExtensible(error))\n ) {\n return error\n }\n return new Error(String(error), { cause: error })\n}\n\nconst schedulerSendFailureState = (\n error: object,\n): SchedulerSendFailureMarker => {\n const existing = schedulerSendFailureMarker(error)\n if (existing !== undefined) return existing\n const marker: SchedulerSendFailureMarker = {\n version: 1,\n pending: [],\n active: [],\n }\n Object.defineProperty(error, SCHEDULER_SEND_FAILURE, {\n value: marker,\n enumerable: false,\n configurable: true,\n writable: false,\n })\n return marker\n}\n\nconst clearSchedulerSendFailureState = (\n error: object,\n marker: SchedulerSendFailureMarker,\n): void => {\n if (marker.pending.length === 0 && marker.active.length === 0) {\n Reflect.deleteProperty(error, SCHEDULER_SEND_FAILURE)\n }\n}\n\n/**\n * Classify an adapter error before throwing it. Unclassified adapter failures\n * are retryable because the caller cannot know whether a remote send landed.\n */\nexport function classifySchedulerSendFailure(\n error: unknown,\n disposition: SchedulerSendFailureDisposition,\n): unknown {\n const classified = schedulerFailureObject(error)\n schedulerSendFailureState(classified).pending.push(disposition)\n return classified\n}\n\n/** Consume a pending adapter classification and count this rejected send. */\nexport function markSchedulerSendFailure(error: unknown): unknown {\n const marked = schedulerFailureObject(error)\n const marker = schedulerSendFailureState(marked)\n marker.active.push(marker.pending.pop() ?? 'retryable')\n return marked\n}\n\nexport function consumeSchedulerSendFailure(\n error: unknown,\n): SchedulerSendFailureDisposition | undefined {\n if (!objectLike(error)) return undefined\n const marker = schedulerSendFailureMarker(error)\n const disposition = marker?.active.pop()\n if (marker !== undefined) clearSchedulerSendFailureState(error, marker)\n return disposition\n}\n\nconst isDrainableServer = (value: unknown): value is DrainableServer => {\n if (value === null || typeof value !== 'object') return false\n const contract = Reflect.get(value, 'contract')\n return (\n contract !== null &&\n typeof contract === 'object' &&\n typeof Reflect.get(contract, 'name') === 'string' &&\n typeof Reflect.get(value, 'drain') === 'function'\n )\n}\n\n/**\n * Validate the server list captured by a scheduler route at construction time.\n * The seam stays structural so custom scheduler integrations can supply their\n * own drainable targets.\n */\nexport function assertSchedulerTargets(\n servers: readonly unknown[],\n): asserts servers is readonly DrainableServer[] {\n const contracts = new Set<string>()\n for (const target of servers) {\n if (!isDrainableServer(target)) {\n throw new TypeError('a2 scheduler: expected a server from createServer()')\n }\n const name = target.contract.name\n if (contracts.has(name)) {\n throw new TypeError(\n `a2 scheduler: duplicate server contract '${name}' in one handler`,\n )\n }\n contracts.add(name)\n }\n}\n\n/**\n * Drain timing knobs. Mutable only as a white-box test seam. Claim\n * heartbeats run on real timers, so tests shrink these to keep suites\n * fast. Production always uses the defaults.\n */\nexport const DRAIN_TIMINGS: {\n /** How long a claim lives without renewal. */\n claimTtlMs: number\n /** Heartbeat cadence while a handler is running. */\n claimHeartbeatMs: number\n /** Base delay before retrying a failed renewal while the lease lives. */\n renewRetryMs: number\n /** Delay between a claim's expiry and its scheduler watchdog. */\n watchdogGraceMs: number\n /** Maximum time a top-level append waits for its initial scheduler arm. */\n schedulerArmTimeoutMs: number\n} = {\n claimTtlMs: 5_000,\n claimHeartbeatMs: 2_000,\n renewRetryMs: 400,\n watchdogGraceMs: 1_000,\n schedulerArmTimeoutMs: 2_000,\n}\n\n/**\n * Stream liveness knobs — the server-side SSE heartbeat and the\n * client-side stall watchdog. Paired by design: the client declares a\n * connection dead after roughly two missed heartbeats. Mutable only as\n * a white-box test seam; production always uses the defaults.\n */\n/**\n * Poll cadence for the poll-based store streams (sqlite, postgres) —\n * owned, not configurable: adaptive polling removed the operator's\n * reason to tune it (the floor keeps active streams smooth; the\n * ceiling bounds idle cost). Mutable only as a white-box test seam so\n * suites don't wait out real idle gaps.\n */\nexport const POLL_TIMINGS: {\n /** Gap between polls while a session is producing events. */\n activeFloorMs: number\n /** The idle ceiling — the longest gap between polls. */\n idleCeilingMs: number\n} = {\n activeFloorMs: 25,\n idleCeilingMs: 250,\n}\n\n/**\n * Safety-read cadence for the notify-driven redis live stream. A\n * parked feed re-reads the store at this interval even without a\n * pub/sub wake-up, so a lost notification (subscriber reconnect gap,\n * dropped PUBLISH) costs latency, never an event. Mutable only as a\n * white-box test seam.\n */\nexport const NOTIFY_TIMINGS: {\n safetyReadMs: number\n} = {\n safetyReadMs: 10_000,\n}\n\nexport const STREAM_TIMINGS: {\n /** Cadence of `: ping` comment frames from `sseResponse`. */\n sseHeartbeatMs: number\n /** How far ahead of an invocation deadline an SSE response closes. */\n sseDeadlineGraceMs: number\n /** Client: silence longer than this means the connection is dead. */\n stallTimeoutMs: number\n /** Client reconnect backoff: first retry delay, doubling per attempt. */\n reconnectBaseMs: number\n /** Client reconnect backoff ceiling. */\n reconnectMaxMs: number\n} = {\n sseHeartbeatMs: 15_000,\n sseDeadlineGraceMs: 1_000,\n stallTimeoutMs: 35_000,\n reconnectBaseMs: 500,\n reconnectMaxMs: 5_000,\n}\n\n/**\n * WebSocket down-pump backpressure — `sessionsSocket` parks its pull\n * loop while the socket reports more buffered bytes than the\n * high-water mark and re-checks on the poll cadence, so a slow reader\n * applies backpressure to the store subscription instead of buffering\n * without bound in the socket. Acks and heartbeats stay exempt: they\n * are small and correctness-relevant. Mutable only as a white-box test\n * seam.\n */\nexport const SOCKET_TIMINGS: {\n highWaterMarkBytes: number\n resumePollMs: number\n /** Up-lane bound: concurrent push/presence handlers per socket. POST\n * gets per-request platform limits for free; the socket must bring\n * its own. Over the cap, pushes are answered with a retryable error\n * ack and presence frames are shed (that plane repaints). */\n maxInFlightMessages: number\n /** Hard ceiling on `bufferedAmount`: past it the peer is a\n * non-reader (acks and pings are park-exempt, so only a peer that\n * never reads can reach it) and the socket closes 1008. */\n disconnectWaterMarkBytes: number\n} = {\n highWaterMarkBytes: 1_048_576,\n resumePollMs: 25,\n maxInFlightMessages: 32,\n disconnectWaterMarkBytes: 8_388_608,\n}\n\n/**\n * Client presence send cadence — a leading send immediately, then at\n * most one merged send per interval (~15Hz). Owned, not configurable\n * (decision #36's rule): coupling the cadence to the POST ack tied\n * remote cursor smoothness to RTT, and the ack serves no correctness\n * purpose on a fire-and-forget LWW plane. Mutable only as a white-box\n * test seam.\n */\nexport const PRESENCE_TIMINGS: {\n sendIntervalMs: number\n} = {\n sendIntervalMs: 66,\n}\n"],"mappings":";;;;;;;;AAiBA,SAAgB,kBAAuC;CACrD,OAAO,OAAO,OAAO,IAAI;AAC3B;;;;;;;AAQA,MAAa,cAAc;;;;;;;AAQ3B,MAAa,2CAAgD,IAAI,IAAI;CACnE;CACA;CACA;AACF,CAAC;AA4BD,MAAa,kCAAoD,IAAI,QAAQ;AAE7E,MAAM,cAAc,UACjB,OAAO,UAAU,YAAY,UAAU,QAAS,OAAO,UAAU;AAqBpE,MAAM,qBAAqB,OAAO,IAAI,+BAA+B;AAErE,SAAgB,0BAA+D;CAC7E,MAAM,QAAQ,QAAQ,IAAI,YAAY,kBAAkB;CACxD,IACE,CAAC,WAAW,KAAK,KACjB,OAAO,QAAQ,IAAI,OAAO,UAAU,MAAM,cAC1C,OAAO,QAAQ,IAAI,OAAO,KAAK,MAAM,YAErC;CAEF,OAAO;AACT;AAEA,SAAgB,+BACd,QACyB;CACzB,MAAM,WAAW,wBAAwB;CACzC,IAAI,aAAa,KAAA,GAAW,OAAO;CACnC,MAAM,UAAU,OAAO;CACvB,QAAQ,IAAI,YAAY,oBAAoB,OAAO;CACnD,OAAO;AACT;AAUA,MAAM,yBAAyB,OAAO,IACpC,wCACF;AAEA,MAAM,8BACJ,UAC2C;CAC3C,IAAI,CAAC,WAAW,KAAK,GAAG,OAAO,KAAA;CAC/B,MAAM,SAAS,QAAQ,IAAI,OAAO,sBAAsB;CACxD,IACE,CAAC,WAAW,MAAM,KAClB,QAAQ,IAAI,QAAQ,SAAS,MAAM,KAC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tE,OAAO;AACT;AAEA,MAAM,qBAAqB,UAA6C;CACtE,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CACxD,MAAM,WAAW,QAAQ,IAAI,OAAO,UAAU;CAC9C,OACE,aAAa,QACb,OAAO,aAAa,YACpB,OAAO,QAAQ,IAAI,UAAU,MAAM,MAAM,YACzC,OAAO,QAAQ,IAAI,OAAO,OAAO,MAAM;AAE3C;;;;;;AAOA,SAAgB,uBACd,SAC+C;CAC/C,MAAM,4BAAY,IAAI,IAAY;CAClC,KAAK,MAAM,UAAU,SAAS;EAC5B,IAAI,CAAC,kBAAkB,MAAM,GAC3B,MAAM,IAAI,UAAU,qDAAqD;EAE3E,MAAM,OAAO,OAAO,SAAS;EAC7B,IAAI,UAAU,IAAI,IAAI,GACpB,MAAM,IAAI,UACR,4CAA4C,KAAK,iBACnD;EAEF,UAAU,IAAI,IAAI;CACpB;AACF;;;;;;AAOA,MAAa,gBAWT;CACF,YAAY;CACZ,kBAAkB;CAClB,cAAc;CACd,iBAAiB;CACjB,uBAAuB;AACzB;;;;;;;;;;;;;;AAeA,MAAa,eAKT;CACF,eAAe;CACf,eAAe;AACjB;;;;;;;;AASA,MAAa,iBAET,EACF,cAAc,IAChB;AAEA,MAAa,iBAWT;CACF,gBAAgB;CAChB,oBAAoB;CACpB,gBAAgB;CAChB,iBAAiB;CACjB,gBAAgB;AAClB;;;;;;;;;;AAWA,MAAa,iBAYT;CACF,oBAAoB;CACpB,cAAc;CACd,qBAAqB;CACrB,0BAA0B;AAC5B;;;;;;;;;AAUA,MAAa,mBAET,EACF,gBAAgB,GAClB"}
1
+ {"version":3,"file":"internal-Dq2qYxou.js","names":[],"sources":["../src/internal.ts"],"sourcesContent":["/**\n * Private seams shared by a2 entry points and a2's own tests. Not exported\n * from the package. Nothing here is public API.\n */\n\nimport type { ScheduledEvent } from './scheduler-task.ts'\nimport type { DrainableServer } from './server.ts'\n\nexport type DrainOutcome = 'busy' | 'stalled' | 'settled'\n\n/**\n * A null-prototype record for maps keyed by caller-controlled strings\n * (participant ids, presence field names). On a normal object,\n * assigning to '__proto__' rewrites the prototype instead of creating\n * an own property — the prototype-pollution class. Null-prototype\n * objects still satisfy Record types and JSON.stringify cleanly.\n */\nexport function nullProtoRecord<T extends object>(): T {\n return Object.create(null) as T\n}\n\n/**\n * ECMA-262's maximum Date value (±8.64e15 ms). A presence stamp past\n * it becomes an Invalid Date whose toISOString throws — one hostile\n * stamp would poison every subscriber's snapshot frame — so both\n * seams bound `at` to the representable range.\n */\nexport const MAX_DATE_MS = 8_640_000_000_000_000\n\n/**\n * Participant ids that collide with Object.prototype plumbing.\n * Null-prototype construction already defuses them, but they are\n * rejected at both seams (`parsePushBody`, `setPresence`) so a hostile\n * id never propagates into userland maps either.\n */\nexport const RESERVED_PARTICIPANT_IDS: ReadonlySet<string> = new Set([\n '__proto__',\n 'constructor',\n 'prototype',\n])\n\nexport type DrainResult = {\n settled: boolean\n outcome: DrainOutcome\n /** Existing successor arm a scheduler callback may join before acking. */\n schedulerArm?: Promise<void>\n}\n\nexport type ServerInternals = {\n /**\n * Await every in-flight background drain this machine has scheduled,\n * including ones scheduled while waiting. Lets tests flush the\n * fire-and-forget inline path deterministically — no sleeps.\n */\n settle(): Promise<void>\n /** The public `server.drain()` result deliberately remains `{ settled }`. */\n schedulerDrain(\n sessionId: string,\n opts?: { watchdogDueAt?: number },\n ): Promise<DrainResult>\n /** Deliver a scheduler-owned delayed append through the normal root path. */\n schedulerAppend(\n sessionId: string,\n events: readonly ScheduledEvent[],\n ): Promise<void>\n}\n\nexport const serverInternals: WeakMap<object, ServerInternals> = new WeakMap()\n\nconst objectLike = (value: unknown): value is object =>\n (typeof value === 'object' && value !== null) || typeof value === 'function'\n\n/** The ambient value delivered to `handlerContext` during a tool execution. */\nexport type AmbientToolScope = {\n /** Executing server identity; a test scope from `runWithHandlerContext` has none. */\n contract?: { readonly name: string }\n context: unknown\n}\n\n/**\n * Structural AsyncLocalStorage surface for the ambient tool scope. The\n * instance is created by the server-only AI entry point (the only place\n * `node:async_hooks` may be imported) and shared through a global\n * symbol slot, so `handlerContext` in the isomorphic AI entry point and\n * independently bundled A2 copies all read the same scope.\n */\nexport type AmbientToolScopeStorage = {\n getStore(): AmbientToolScope | undefined\n run<R>(store: AmbientToolScope, callback: () => R): R\n}\n\nconst TOOL_SCOPE_STORAGE = Symbol.for('experimental-a2.ai.tool-scope')\n\nexport function ambientToolScopeStorage(): AmbientToolScopeStorage | undefined {\n const value = Reflect.get(globalThis, TOOL_SCOPE_STORAGE)\n if (\n !objectLike(value) ||\n typeof Reflect.get(value, 'getStore') !== 'function' ||\n typeof Reflect.get(value, 'run') !== 'function'\n ) {\n return undefined\n }\n return value as AmbientToolScopeStorage\n}\n\nexport function installAmbientToolScopeStorage(\n create: () => AmbientToolScopeStorage,\n): AmbientToolScopeStorage {\n const existing = ambientToolScopeStorage()\n if (existing !== undefined) return existing\n const storage = create()\n Reflect.set(globalThis, TOOL_SCOPE_STORAGE, storage)\n return storage\n}\n\nexport type SchedulerSendFailureDisposition = 'retryable' | 'terminal'\n\ntype SchedulerSendFailureMarker = {\n readonly version: 1\n readonly pending: SchedulerSendFailureDisposition[]\n readonly active: SchedulerSendFailureDisposition[]\n}\n\nconst SCHEDULER_SEND_FAILURE = Symbol.for(\n 'experimental-a2.scheduler.send-failure',\n)\n\nconst schedulerSendFailureMarker = (\n value: unknown,\n): SchedulerSendFailureMarker | undefined => {\n if (!objectLike(value)) return undefined\n const marker = Reflect.get(value, SCHEDULER_SEND_FAILURE)\n if (\n !objectLike(marker) ||\n Reflect.get(marker, 'version') !== 1 ||\n !Array.isArray(Reflect.get(marker, 'pending')) ||\n !Array.isArray(Reflect.get(marker, 'active'))\n ) {\n return undefined\n }\n return marker as SchedulerSendFailureMarker\n}\n\nconst schedulerFailureObject = (error: unknown): object => {\n if (\n objectLike(error) &&\n (schedulerSendFailureMarker(error) !== undefined ||\n Object.isExtensible(error))\n ) {\n return error\n }\n return new Error(String(error), { cause: error })\n}\n\nconst schedulerSendFailureState = (\n error: object,\n): SchedulerSendFailureMarker => {\n const existing = schedulerSendFailureMarker(error)\n if (existing !== undefined) return existing\n const marker: SchedulerSendFailureMarker = {\n version: 1,\n pending: [],\n active: [],\n }\n Object.defineProperty(error, SCHEDULER_SEND_FAILURE, {\n value: marker,\n enumerable: false,\n configurable: true,\n writable: false,\n })\n return marker\n}\n\nconst clearSchedulerSendFailureState = (\n error: object,\n marker: SchedulerSendFailureMarker,\n): void => {\n if (marker.pending.length === 0 && marker.active.length === 0) {\n Reflect.deleteProperty(error, SCHEDULER_SEND_FAILURE)\n }\n}\n\n/**\n * Classify an adapter error before throwing it. Unclassified adapter failures\n * are retryable because the caller cannot know whether a remote send landed.\n */\nexport function classifySchedulerSendFailure(\n error: unknown,\n disposition: SchedulerSendFailureDisposition,\n): unknown {\n const classified = schedulerFailureObject(error)\n schedulerSendFailureState(classified).pending.push(disposition)\n return classified\n}\n\n/** Consume a pending adapter classification and count this rejected send. */\nexport function markSchedulerSendFailure(error: unknown): unknown {\n const marked = schedulerFailureObject(error)\n const marker = schedulerSendFailureState(marked)\n marker.active.push(marker.pending.pop() ?? 'retryable')\n return marked\n}\n\nexport function consumeSchedulerSendFailure(\n error: unknown,\n): SchedulerSendFailureDisposition | undefined {\n if (!objectLike(error)) return undefined\n const marker = schedulerSendFailureMarker(error)\n const disposition = marker?.active.pop()\n if (marker !== undefined) clearSchedulerSendFailureState(error, marker)\n return disposition\n}\n\nconst isDrainableServer = (value: unknown): value is DrainableServer => {\n if (value === null || typeof value !== 'object') return false\n const contract = Reflect.get(value, 'contract')\n return (\n contract !== null &&\n typeof contract === 'object' &&\n typeof Reflect.get(contract, 'name') === 'string' &&\n typeof Reflect.get(value, 'drain') === 'function'\n )\n}\n\n/**\n * Validate the server list captured by a scheduler route at construction time.\n * The seam stays structural so custom scheduler integrations can supply their\n * own drainable targets.\n */\nexport function assertSchedulerTargets(\n servers: readonly unknown[],\n): asserts servers is readonly DrainableServer[] {\n const contracts = new Set<string>()\n for (const target of servers) {\n if (!isDrainableServer(target)) {\n throw new TypeError('a2 scheduler: expected a server from createServer()')\n }\n const name = target.contract.name\n if (contracts.has(name)) {\n throw new TypeError(\n `a2 scheduler: duplicate server contract '${name}' in one handler`,\n )\n }\n contracts.add(name)\n }\n}\n\n/**\n * Drain timing knobs. Mutable only as a white-box test seam. Claim\n * heartbeats run on real timers, so tests shrink these to keep suites\n * fast. Production always uses the defaults.\n */\nexport const DRAIN_TIMINGS: {\n /** How long a claim lives without renewal. */\n claimTtlMs: number\n /** Heartbeat cadence while a handler is running. */\n claimHeartbeatMs: number\n /** Base delay before retrying a failed renewal while the lease lives. */\n renewRetryMs: number\n /** Delay between a claim's expiry and its scheduler watchdog. */\n watchdogGraceMs: number\n /** Maximum time a top-level append waits for its initial scheduler arm. */\n schedulerArmTimeoutMs: number\n} = {\n claimTtlMs: 5_000,\n claimHeartbeatMs: 2_000,\n renewRetryMs: 400,\n watchdogGraceMs: 1_000,\n schedulerArmTimeoutMs: 2_000,\n}\n\n/**\n * Stream liveness knobs — the server-side SSE heartbeat and the\n * client-side stall watchdog. Paired by design: the client declares a\n * connection dead after roughly two missed heartbeats. Mutable only as\n * a white-box test seam; production always uses the defaults.\n */\n/**\n * Poll cadence for the poll-based store streams (sqlite, postgres) —\n * owned, not configurable: adaptive polling removed the operator's\n * reason to tune it (the floor keeps active streams smooth; the\n * ceiling bounds idle cost). Mutable only as a white-box test seam so\n * suites don't wait out real idle gaps.\n */\nexport const POLL_TIMINGS: {\n /** Gap between polls while a session is producing events. */\n activeFloorMs: number\n /** The idle ceiling — the longest gap between polls. */\n idleCeilingMs: number\n} = {\n activeFloorMs: 25,\n idleCeilingMs: 2_000,\n}\n\n/**\n * Safety-read cadence for the notify-driven redis live stream. A\n * parked feed re-reads the store at this interval even without a\n * pub/sub wake-up, so a lost notification (subscriber reconnect gap,\n * dropped PUBLISH) costs latency, never an event. Mutable only as a\n * white-box test seam.\n */\nexport const NOTIFY_TIMINGS: {\n safetyReadMs: number\n} = {\n safetyReadMs: 10_000,\n}\n\nexport const STREAM_TIMINGS: {\n /** Cadence of `: ping` comment frames from `sseResponse`. */\n sseHeartbeatMs: number\n /** How far ahead of an invocation deadline an SSE response closes. */\n sseDeadlineGraceMs: number\n /** Client: silence longer than this means the connection is dead. */\n stallTimeoutMs: number\n /** Client reconnect backoff: first retry delay, doubling per attempt. */\n reconnectBaseMs: number\n /** Client reconnect backoff ceiling. */\n reconnectMaxMs: number\n} = {\n sseHeartbeatMs: 15_000,\n sseDeadlineGraceMs: 1_000,\n stallTimeoutMs: 35_000,\n reconnectBaseMs: 500,\n reconnectMaxMs: 5_000,\n}\n\n/**\n * WebSocket down-pump backpressure — `sessionsSocket` parks its pull\n * loop while the socket reports more buffered bytes than the\n * high-water mark and re-checks on the poll cadence, so a slow reader\n * applies backpressure to the store subscription instead of buffering\n * without bound in the socket. Acks and heartbeats stay exempt: they\n * are small and correctness-relevant. Mutable only as a white-box test\n * seam.\n */\nexport const SOCKET_TIMINGS: {\n highWaterMarkBytes: number\n resumePollMs: number\n /** Up-lane bound: concurrent push/presence handlers per socket. POST\n * gets per-request platform limits for free; the socket must bring\n * its own. Over the cap, pushes are answered with a retryable error\n * ack and presence frames are shed (that plane repaints). */\n maxInFlightMessages: number\n /** Hard ceiling on `bufferedAmount`: past it the peer is a\n * non-reader (acks and pings are park-exempt, so only a peer that\n * never reads can reach it) and the socket closes 1008. */\n disconnectWaterMarkBytes: number\n} = {\n highWaterMarkBytes: 1_048_576,\n resumePollMs: 25,\n maxInFlightMessages: 32,\n disconnectWaterMarkBytes: 8_388_608,\n}\n\n/**\n * Client presence send cadence — a leading send immediately, then at\n * most one merged send per interval (~15Hz). Owned, not configurable\n * (decision #36's rule): coupling the cadence to the POST ack tied\n * remote cursor smoothness to RTT, and the ack serves no correctness\n * purpose on a fire-and-forget LWW plane. Mutable only as a white-box\n * test seam.\n */\nexport const PRESENCE_TIMINGS: {\n sendI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;AAOA,SAAgB,uBACd,SAC+C;CAC/C,MAAM,4BAAY,IAAI,IAAY;CAClC,KAAK,MAAM,UAAU,SAAS;EAC5B,IAAI,CAAC,kBAAkB,MAAM,GAC3B,MAAM,IAAI,UAAU,qDAAqD;EAE3E,MAAM,OAAO,OAAO,SAAS;EAC7B,IAAI,UAAU,IAAI,IAAI,GACpB,MAAM,IAAI,UACR,4CAA4C,KAAK,iBACnD;EAEF,UAAU,IAAI,IAAI;CACpB;AACF;;;;;;AAOA,MAAa,gBAWT;CACF,YAAY;CACZ,kBAAkB;CAClB,cAAc;CACd,iBAAiB;CACjB,uBAAuB;AACzB;;;;;;;;;;;;;;AAeA,MAAa,eAKT;CACF,eAAe;CACf,eAAe;AACjB;;;;;;;;AASA,MAAa,iBAET,EACF,cAAc,IAChB;AAEA,MAAa,iBAWT;CACF,gBAAgB;CAChB,oBAAoB;CACpB,gBAAgB;CAChB,iBAAiB;CACjB,gBAAgB;AAClB;;;;;;;;;;AAWA,MAAa,iBAYT;CACF,oBAAoB;CACpB,cAAc;CACd,qBAAqB;CACrB,0BAA0B;AAC5B;;;;;;;;;AAUA,MAAa,mBAET,EACF,gBAAgB,GAClB"}
@@ -0,0 +1,34 @@
1
+ //#region src/platform.ts
2
+ const SYMBOL_FOR_REQ_CONTEXT = Symbol.for("@vercel/request-context");
3
+ function requestContext() {
4
+ try {
5
+ return Reflect.get(globalThis, SYMBOL_FOR_REQ_CONTEXT)?.get?.() ?? {};
6
+ } catch {
7
+ return {};
8
+ }
9
+ }
10
+ /** The current invocation's Vercel deployment identity, when available. */
11
+ function platformVercelOidcToken() {
12
+ try {
13
+ const token = requestContext().headers?.["x-vercel-oidc-token"];
14
+ return typeof token === "string" && token.length > 0 ? token : null;
15
+ } catch {
16
+ return null;
17
+ }
18
+ }
19
+ function platformWaitUntil(promise) {
20
+ try {
21
+ requestContext().waitUntil?.(promise);
22
+ } catch {}
23
+ }
24
+ /** The invocation's termination time in epoch ms, or null if unknowable. */
25
+ function invocationDeadlineMs() {
26
+ const deadline = requestContext().deadline;
27
+ if (deadline === void 0 || deadline === null) return null;
28
+ const ms = new Date(deadline).getTime();
29
+ return Number.isNaN(ms) ? null : ms;
30
+ }
31
+ //#endregion
32
+ export { platformVercelOidcToken as n, platformWaitUntil as r, invocationDeadlineMs as t };
33
+
34
+ //# sourceMappingURL=platform-B4TnJtWu.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"platform-B4TnJtWu.js","names":[],"sources":["../src/platform.ts"],"sourcesContent":["/**\n * Platform seams, read from the ambient request context — the same\n * channel `@vercel/functions` uses (`Symbol.for('@vercel/request-context')`)\n * — with no dependency on that package. Where no context exists (local\n * dev, long-lived servers, other clouds) everything degrades cleanly:\n * `waitUntil` becomes a no-op (background work is tracked in-process\n * anyway) and the deadline is unknown (claim watchdogs use their ordinary\n * TTL window).\n *\n * Tests exercise these paths by installing a real context object on the\n * symbol — simulating the platform contract, not mocking a2.\n */\n\ntype RequestContext = {\n headers?: Readonly<Record<string, string>>\n waitUntil?: (promise: Promise<unknown>) => void\n /**\n * When the platform will terminate this invocation (epoch ms, ISO\n * string, or Date) — on Vercel this includes `waitUntil` work.\n */\n deadline?: number | string | Date\n}\n\nconst SYMBOL_FOR_REQ_CONTEXT = Symbol.for('@vercel/request-context')\n\nfunction requestContext(): RequestContext {\n try {\n const holder = Reflect.get(globalThis, SYMBOL_FOR_REQ_CONTEXT) as\n { get?: () => RequestContext | undefined } | undefined\n return holder?.get?.() ?? {}\n } catch {\n return {}\n }\n}\n\n/** The current invocation's Vercel deployment identity, when available. */\nexport function platformVercelOidcToken(): string | null {\n try {\n const token = requestContext().headers?.['x-vercel-oidc-token']\n return typeof token === 'string' && token.length > 0 ? token : null\n } catch {\n return null\n }\n}\n\nexport function platformWaitUntil(promise: Promise<unknown>): void {\n try {\n requestContext().waitUntil?.(promise)\n } catch {\n // Best-effort — the promise is tracked in-process either way.\n }\n}\n\n/** The invocation's termination time in epoch ms, or null if unknowable. */\nexport function invocationDeadlineMs(): number | null {\n const deadline = requestContext().deadline\n if (deadline === undefined || deadline === null) return null\n const ms = new Date(deadline as number | string | Date).getTime()\n return Number.isNaN(ms) ? null : ms\n}\n"],"mappings":";AAuBA,MAAM,yBAAyB,OAAO,IAAI,yBAAyB;AAEnE,SAAS,iBAAiC;CACxC,IAAI;EAGF,OAFe,QAAQ,IAAI,YAAY,sBAE3B,CAAC,EAAE,MAAM,KAAK,CAAC;CAC7B,QAAQ;EACN,OAAO,CAAC;CACV;AACF;;AAGA,SAAgB,0BAAyC;CACvD,IAAI;EACF,MAAM,QAAQ,eAAe,CAAC,CAAC,UAAU;EACzC,OAAO,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,QAAQ;CACjE,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAgB,kBAAkB,SAAiC;CACjE,IAAI;EACF,eAAe,CAAC,CAAC,YAAY,OAAO;CACtC,QAAQ,CAER;AACF;;AAGA,SAAgB,uBAAsC;CACpD,MAAM,WAAW,eAAe,CAAC,CAAC;CAClC,IAAI,aAAa,KAAA,KAAa,aAAa,MAAM,OAAO;CACxD,MAAM,KAAK,IAAI,KAAK,QAAkC,CAAC,CAAC,QAAQ;CAChE,OAAO,OAAO,MAAM,EAAE,IAAI,OAAO;AACnC"}
package/dist/react.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { a as ContractEvent, c as PresenceDefs, l as PresenceMap, p as WithPresence, r as AppendInput, s as EventDefs, t as Reducer, u as PresencePatch } from "./reducer-DJKWm3cp.js";
2
- import { A2Client, Connection, HistoryState, LoadHistoryOptions, PushResult } from "./client.js";
2
+ import { a as Connection, c as HistoryState, l as LoadHistoryOptions, t as A2Client, u as PushResult } from "./client-P_NNNRM-.js";
3
3
  import { ReactElement, ReactNode } from "react";
4
4
  //#region src/react.d.ts
5
5
  type UseSessionOptions<S> = {
@@ -81,6 +81,8 @@ type UseSessionResult<D extends EventDefs, S, P extends PresenceDefs = Record<ne
81
81
  * back. Rejects with the server's A2Error codes.
82
82
  */
83
83
  push: (...events: AppendInput<D>[]) => PushResult<D>;
84
+ /** Restart the live subscription without resetting its state or cursor. */
85
+ reconnect: () => void;
84
86
  /**
85
87
  * Backscroll: fetch a bounded slice of older events into `events`.
86
88
  * Defaults page backward 50 at a time from the oldest loaded event.
@@ -1 +1 @@
1
- {"version":3,"file":"react.d.ts","names":[],"sources":["../src/react.ts"],"mappings":";;;;KAoDY,kBAAkB;;;;EAI5B;;;;;;;;;;;;;;;;;EAiBA;IAAY,OAAO;IAAG;;;KAGZ,qBAAqB,UAAU,WAAW;;EAEpD;;EAEA;;EAEA,cAAc;;EAEd;;EAEA,gBAAgB,cAAc;;;EAG9B;EACA,WAAW;;KAGD,0BAA0B,UAAU,WAAW,KAAK,KAC9D,qBAAqB,GAAG;;;;;;KASd,mBAAmB,UAAU;;EAEvC,UAAU,YAAY;;;;;;;;EAQtB,cAAc,QAAQ,cAAc;;KAG1B,iBACV,UAAU,WACV,GACA,UAAU,eAAe,wBACvB,aAAa,GAAG,mBAAmB;;EAErC,OAAO;;EAEP,QAAQ,cAAc;;EAEtB;;;;;;EAMA,YAAY;;;;;;EAMZ,UAAU,QAAQ,YAAY,SAAS,WAAW;;;;;;EAMlD,cAAc,UAAU,uBAAuB,QAAQ,cAAc;;EAErE,SAAS;;KAGC,QACV,UAAU,WACV,GACA,UAAU,eAAe;EAEzB,kBAAkB,OAAO,qBAAqB,GAAG,OAAO;EACxD,kBAAkB,iBAAiB,GAAG,GAAG;;KAG/B,aACV,UAAU,WACV,GACA,UAAU,eAAe;EAEzB,kBAAkB,OAAO,0BAA0B,GAAG,OAAO;EAC7D,kBAAkB,iBAAiB,GAAG,GAAG;;iBAG3B,YACd,UAAU,WACV,GACA,UAAU,eAAe,sBACzB;EAAW,QAAQ,SAAS,GAAG,GAAG;IAAO,aAAa,GAAG,GAAG;iBAC9C,YACd,UAAU,WACV,GACA,UAAU,eAAe,sBACzB;EAAW,SAAS,QAAQ,GAAG,GAAG;I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;;;;;;iBAgKzC,WACd,UAAU,WACV,GACA,UAAU,eAAe,sBAEzB,QAAQ,SAAS,GAAG,GAAG,IACvB,mBACA,UAAU,kBAAkB,KAC3B,iBAAiB,GAAG,GAAG"}
package/dist/react.js CHANGED
@@ -1,5 +1,5 @@
1
1
  "use client";
2
- import { createClient } from "./client.js";
2
+ import { t as createClient } from "./client-Bf6uSEAk.js";
3
3
  import { createContext, createElement, useContext, useEffect, useMemo, useSyncExternalStore } from "react";
4
4
  //#region src/react.ts
5
5
  /**
@@ -97,6 +97,7 @@ function useSessionResult(session) {
97
97
  index: snapshot.index,
98
98
  connection: snapshot.connection,
99
99
  push: session.push,
100
+ reconnect: session.reconnect,
100
101
  loadHistory: session.loadHistory,
101
102
  history: snapshot.history,
102
103
  ...setPresence && presence ? {
package/dist/react.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"react.js","names":[],"sources":["../src/react.ts"],"sourcesContent":["'use client'\n/**\n * experimental-a2/react — React bindings over experimental-a2/client.\n *\n * `createReact({ client })` is a factory (like createContext): call it\n * once in a `'use client'` module with a shared A2 client and export the\n * bound pair. Server components import `SessionProvider` from that module\n * as a client reference; client components import `useSession` from the\n * same file. The shared client also makes imperative pushes and provider\n * renders resolve the same live session. Everything is typed by the\n * reducer value — no type arguments, and nothing here ever touches the\n * machine module.\n *\n * The standalone `useSession(client, sessionId, options?)` is the\n * provider-less primitive for client-first apps: identity-mapped\n * handles, one leased stream per session, and an app-owned hydration\n * input — the hook holds the stream until the app hands it a\n * `{ state, index }` fold.\n */\n\nimport {\n createContext,\n createElement,\n useContext,\n useEffect,\n useMemo,\n useSyncExternalStore,\n type ReactElement,\n type ReactNode,\n} from 'react'\nimport {\n createClient,\n type A2Client,\n type Connection,\n type HistoryState,\n type LoadHistoryOptions,\n type PushResult,\n type SessionClient,\n type SessionClientPresence,\n type SessionSnapshot,\n} from './client.ts'\nimport type {\n AppendInput,\n ContractEvent,\n EventDefs,\n PresenceDefs,\n PresenceMap,\n PresencePatch,\n WithPresence,\n} from './contract.ts'\nimport type { Reducer } from './reducer.ts'\n\nexport type UseSessionOptions<S> = {\n /** Overrides the client's `participant` for this session — for apps\n * whose identity is only known at mount time. Bound once per\n * session handle. */\n participant?: string\n /**\n * The server fold this session mounts from: the `{ state, index }`\n * pair `session.state(reducer)` returns, fetched by the app through\n * its own route. Atomic on purpose — the fold and its frontier\n * travel together or not at all. While `undefined` (the app's fetch\n * has not landed), the hook holds the stream; when the value\n * arrives, the session hydrates through the ordinary re-hydration\n * seam and the stream connects at that frontier. To fold from the log's start\n * deliberately, hand the fold's true starting point:\n * `{ state: reducer.initialState, index: 0 }` — state at index 0 is\n * the reducer's seed by definition, so the explicit replay needs no\n * special vocabulary. There is no pending/ready echo on the result:\n * whether the fold has been handed over is this option — the\n * caller's own input — so the data layer's loading state IS the\n * pending state.\n */\n hydrate?: { state: S; index: number } | undefined\n}\n\nexport type SessionProviderProps<D extends EventDefs, S> = {\n /** Which session to subscribe to. */\n sessionId: string\n /** Base path of the route exposing GET (stream) and POST (push). */\n api: string\n /** The server-rendered fold — the first paint, no client JS needed. */\n initialState: S\n /** The fold's frontier — the stream resumes exactly there. */\n initialIndex: number\n /** Server-rendered event history through `initialIndex`. */\n initialEvents?: ContractEvent<D>[]\n /** Overrides the client's `participant` for this session — for apps\n * whose identity is only known at mount time. */\n participant?: string\n children?: ReactNode\n}\n\nexport type BoundSessionProviderProps<D extends EventDefs, S> = Omit<\n SessionProviderProps<D, S>,\n 'api'\n>\n\n/**\n * The presence members of the hook result — intersected in via\n * `WithPresence`, so they exist exactly when the contract declares\n * presence fields (the reducer is the client's typed handle on it).\n */\nexport type UseSessionPresence<P extends PresenceDefs> = {\n /** The replicated presence map, this client included (local echo). */\n presence: PresenceMap<P>\n /**\n * Fire-and-forget: validated locally, echoed into the map\n * immediately, coalesced on the wire to a fixed cadence (a leading\n * send immediately, then at most one merged send per interval;\n * later values win per field), stamped with the frontier at send\n * time as `seen`. Requires the provider's `participant`.\n */\n setPresence: (values: PresencePatch<P>['values']) => void\n}\n\nexport type UseSessionResult<\n D extends EventDefs,\n S,\n P extends PresenceDefs = Record<never, never>,\n> = WithPresence<P, UseSessionPresence<P>> & {\n /** The live view, folded through the shared reducer. */\n state: S\n /** The raw event feed — observed, seeded, or backscrolled. */\n events: ContractEvent<D>[]\n /** The stream frontier — `lastSeenIndex` for cancellation. */\n index: number\n /**\n * The connection, as a discriminated union — `error` exists only\n * while disconnected; \"reconnecting…\" is\n * `status === 'connecting' && reconnects > 0`.\n */\n connection: Connection\n /**\n * Typed optimistic append. Awaiting it gives the server ack;\n * `.confirmed` resolves when the live stream has delivered the batch\n * back. Rejects with the server's A2Error codes.\n */\n push: (...events: AppendInput<D>[]) => PushResult<D>\n /**\n * Backscroll: fetch a bounded slice of older events into `events`.\n * Defaults page backward 50 at a time from the oldest loaded event.\n * Display data only — `state` and the optimistic overlay never move.\n */\n loadHistory: (options?: LoadHistoryOptions) => Promise<ContractEvent<D>[]>\n /** Backscroll progress: `complete` means the feed reaches index 1. */\n history: HistoryState\n}\n\nexport type A2React<\n D extends EventDefs,\n S,\n P extends PresenceDefs = Record<never, never>,\n> = {\n SessionProvider: (props: SessionProviderProps<D, S>) => ReactElement\n useSession: () => UseSessionResult<D, S, P>\n}\n\nexport type BoundA2React<\n D extends EventDefs,\n S,\n P extends PresenceDefs = Record<never, never>,\n> = {\n SessionProvider: (props: BoundSessionProviderProps<D, S>) => ReactElement\n useSession: () => UseSessionResult<D, S, P>\n}\n\nexport function createReact<\n D extends EventDefs,\n S,\n P extends PresenceDefs = Record<never, never>,\n>(options: { client: A2Client<D, S, P> }): BoundA2React<D, S, P>\nexport function createReact<\n D extends EventDefs,\n S,\n P extends PresenceDefs = Record<never, never>,\n>(options: { reducer: Reducer<D, S, P> }): A2React<D, S, P>\nexport function createReact<\n D extends EventDefs,\n S,\n P extends PresenceDefs = Record<never, never>,\n>(\n options: { client: A2Client<D, S, P> } | { reducer: Reducer<D, S, P> },\n): BoundA2React<D, S, P> | A2React<D, S, P> {\n const Context = createContext<SessionClient<D, S, P> | null>(null)\n const resolveSession: (\n sessionId: string,\n api: string | undefined,\n initialState: S,\n initialIndex: number,\n initialEvents: ContractEvent<D>[] | undefined,\n participant: string | undefined,\n ) => SessionClient<D, S, P> =\n 'client' in options\n ? (\n sessionId,\n _api,\n initialState,\n initialIndex,\n initialEvents,\n participant,\n ) =>\n options.client.session(sessionId, {\n initialState,\n initialIndex,\n ...(initialEvents === undefined ? {} : { initialEvents }),\n ...(participant === undefined ? {} : { participant }),\n })\n : (() => {\n const clients = new Map<string, A2Client<D, S, P>>()\n return (\n sessionId: string,\n api: string | undefined,\n initialState: S,\n initialIndex: number,\n initialEvents: ContractEvent<D>[] | undefined,\n participant: string | undefined,\n ) => {\n if (api === undefined) {\n throw new TypeError(\n 'SessionProvider requires api when createReact binds a reducer',\n )\n }\n let client = clients.get(api)\n if (!client) {\n client = createClient({ reducer: options.reducer, api })\n clients.set(api, client)\n }\n return client.session(sessionId, {\n initialState,\n initialIndex,\n ...(initialEvents === undefined ? {} : { initialEvents }),\n ...(participant === undefined ? {} : { participant }),\n })\n }\n })()\n\n function SessionProvider(\n props: SessionProviderProps<D, S> | BoundSessionProviderProps<D, S>,\n ): ReactElement {\n const {\n sessionId,\n initialState,\n initialIndex,\n initialEvents,\n participant,\n } = props\n const api = 'api' in props ? props.api : undefined\n const client = useMemo(\n () =>\n resolveSession(\n sessionId,\n api,\n initialState,\n initialIndex,\n initialEvents,\n participant,\n ),\n [sessionId, api, initialState, initialIndex, initialEvents, participant],\n )\n useSessionLifecycle(client, true)\n return createElement(Context.Provider, { value: client }, props.children)\n }\n\n function useBoundSession(): UseSessionResult<D, S, P> {\n const client = useContext(Context)\n if (!client) {\n throw new Error(\n 'useSession must be rendered inside its matching SessionProvider',\n )\n }\n return useSessionResult(client)\n }\n\n return { SessionProvider, useSession: useBoundSession }\n}\n\n// ── the shared session lifecycle ───────────────────────────────\n\n/**\n * Hold a stream lease while mounted and `live` — the client refcounts\n * leases per handle, so however many providers and hooks mount one\n * session, the first connects and the last release closes\n * (StrictMode-safe: the lease is retaken on remount). A standalone\n * hook without a `hydrate` value passes `live: false` and holds the\n * stream — connecting an unhydrated session would replay the whole\n * log, and the library never picks the expensive path silently.\n */\nfunction useSessionLifecycle<D extends EventDefs, S, P extends PresenceDefs>(\n session: SessionClient<D, S, P>,\n live: boolean,\n): void {\n useEffect(() => {\n if (!live) return\n return session.connect()\n }, [session, live])\n}\n\nfunction useSessionResult<D extends EventDefs, S, P extends PresenceDefs>(\n session: SessionClient<D, S, P>,\n): UseSessionResult<D, S, P> {\n const snapshot: SessionSnapshot<D, S, P> = useSyncExternalStore(\n session.subscribe,\n session.getSnapshot,\n session.getSnapshot,\n )\n return useMemo(() => {\n // Runtime mirror of the WithPresence surface: the client attaches\n // setPresence (and the snapshot carries presence) exactly when the\n // reducer declares presence fields — no runtime-inert members.\n const { setPresence } = session as Partial<SessionClientPresence<P>>\n const { presence } = snapshot as Partial<{ presence: PresenceMap<P> }>\n return {\n state: snapshot.state,\n events: snapshot.events,\n index: snapshot.index,\n connection: snapshot.connection,\n push: session.push,\n loadHistory: session.loadHistory,\n history: snapshot.history,\n ...(setPresence && presence ? { presence, setPresence } : {}),\n } as UseSessionResult<D, S, P>\n }, [snapshot, session])\n}\n\n/**\n * The standalone, provider-less hook — for apps whose components reach\n * sessions ad hoc (a sidebar of channel sessions, a user session read\n * from a menu). Takes the shared client and a session id; the handle\n * is identity-mapped, so every hook and provider mounting the same\n * session shares one runtime and one leased stream. Hydration is\n * app-owned: pass `hydrate` when your fetch lands; until then the\n * stream is held, and your data layer's loading state is the pending\n * state.\n */\nexport function useSession<\n D extends EventDefs,\n S,\n P extends PresenceDefs = Record<never, never>,\n>(\n client: A2Client<D, S, P>,\n sessionId: string,\n options?: UseSessionOptions<S>,\n): UseSessionResult<D, S, P> {\n const { participant, hydrate } = options ?? {}\n const session = useMemo(\n () =>\n client.session(sessionId, {\n ...(hydrate === undefined\n ? {}\n : { initialState: hydrate.state, initialIndex: hydrate.index }),\n ...(participant === undefined ? {} : { participant }),\n }),\n [client, sessionId, hydrate, participant],\n )\n useSessionLifecycle(session, hydrate !== undefined)\n return useSessionResult(session)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAiLA,SAAgB,YAKd,SAC0C;CAC1C,MAAM,UAAU,cAA6C,IAAI;CACjE,MAAM,iBAQJ,YAAY,WAEN,WACA,MACA,cACA,cACA,eACA,gBAEA,QAAQ,OAAO,QAAQ,WAAW;EAChC;EACA;EACA,GAAI,kBAAkB,KAAA,IAAY,CAAC,IAAI,EAAE,cAAc;EACvD,GAAI,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY;CACrD,CAAC,WACI;EACL,MAAM,0BAAU,IAAI,IAA+B;EACnD,QACE,WACA,KACA,cACA,cACA,eACA,gBACG;GACH,IAAI,QAAQ,KAAA,GACV,MAAM,IAAI,UACR,+DACF;GAEF,IAAI,SAAS,QAAQ,IAAI,GAAG;GAC5B,IAAI,CAAC,QAAQ;IACX,SAAS,aAAa;KAAE,SAAS,QAAQ;KAAS;IAAI,CAAC;IACvD,QAAQ,IAAI,KAAK,MAAM;GACzB;GACA,OAAO,OAAO,QAAQ,WAAW;IAC/B;IACA;IACA,GAAI,kBAAkB,KAAA,IAAY,CAAC,IAAI,EAAE,cAAc;IACvD,GAAI,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY;GACrD,CAAC;EACH;CACF,EAAA,CAAG;CAET,SAAS,gBACP,OACc;EACd,MAAM,EACJ,WACA,cACA,cACA,eACA,gBACE;EACJ,MAAM,MAAM,SAAS,QAAQ,MAAM,MAAM,KAAA;EACzC,MAAM,SAAS,cAEX,eACE,WACA,KACA,cACA,cACA,eACA,WACF,GACF;GAAC;GAAW;GAAK;GAAc;GAAc;GAAe;EAAW,CACzE;EACA,oBAAoB,QAAQ,IAAI;EAChC,OAAO,cAAc,QAAQ,UAAU,EAA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ental-a2/react — React bindings over experimental-a2/client.\n *\n * `createReact({ client })` is a factory (like createContext): call it\n * once in a `'use client'` module with a shared A2 client and export the\n * bound pair. Server components import `SessionProvider` from that module\n * as a client reference; client components import `useSession` from the\n * same file. The shared client also makes imperative pushes and provider\n * renders resolve the same live session. Everything is typed by the\n * reducer value — no type arguments, and nothing here ever touches the\n * machine module.\n *\n * The standalone `useSession(client, sessionId, options?)` is the\n * provider-less primitive for client-first apps: identity-mapped\n * handles, one leased stream per session, and an app-owned hydration\n * input — the hook holds the stream until the app hands it a\n * `{ state, index }` fold.\n */\n\nimport {\n createContext,\n createElement,\n useContext,\n useEffect,\n useMemo,\n useSyncExternalStore,\n type ReactElement,\n type ReactNode,\n} from 'react'\nimport {\n createClient,\n type A2Client,\n type Connection,\n type HistoryState,\n type LoadHistoryOptions,\n type PushResult,\n type SessionClient,\n type SessionClientPresence,\n type SessionSnapshot,\n} from './client.ts'\nimport type {\n AppendInput,\n ContractEvent,\n EventDefs,\n PresenceDefs,\n PresenceMap,\n PresencePatch,\n WithPresence,\n} from './contract.ts'\nimport type { Reducer } from './reducer.ts'\n\nexport type UseSessionOptions<S> = {\n /** Overrides the client's `participant` for this session — for apps\n * whose identity is only known at mount time. Bound once per\n * session handle. */\n participant?: string\n /**\n * The server fold this session mounts from: the `{ state, index }`\n * pair `session.state(reducer)` returns, fetched by the app through\n * its own route. Atomic on purpose — the fold and its frontier\n * travel together or not at all. While `undefined` (the app's fetch\n * has not landed), the hook holds the stream; when the value\n * arrives, the session hydrates through the ordinary re-hydration\n * seam and the stream connects at that frontier. To fold from the log's start\n * deliberately, hand the fold's true starting point:\n * `{ state: reducer.initialState, index: 0 }` — state at index 0 is\n * the reducer's seed by definition, so the explicit replay needs no\n * special vocabulary. There is no pending/ready echo on the result:\n * whether the fold has been handed over is this option — the\n * caller's own input — so the data layer's loading state IS the\n * pending state.\n */\n hydrate?: { state: S; index: number } | undefined\n}\n\nexport type SessionProviderProps<D extends EventDefs, S> = {\n /** Which session to subscribe to. */\n sessionId: string\n /** Base path of the route exposing GET (stream) and POST (push). */\n api: string\n /** The server-rendered fold — the first paint, no client JS needed. */\n initialState: S\n /** The fold's frontier — the stream resumes exactly there. */\n initialIndex: number\n /** Server-rendered event history through `initialIndex`. */\n initialEvents?: ContractEvent<D>[]\n /** Overrides the client's `participant` for this session — for apps\n * whose identity is only known at mount time. */\n participant?: string\n children?: ReactNode\n}\n\nexport type BoundSessionProviderProps<D extends EventDefs, S> = Omit<\n SessionProviderProps<D, S>,\n 'api'\n>\n\n/**\n * The presence members of the hook result — intersected in via\n * `WithPresence`, so they exist exactly when the contract declares\n * presence fields (the reducer is the client's typed handle on it).\n */\nexport type UseSessionPresence<P extends PresenceDefs> = {\n /** The replicated presence map, this client included (local echo). */\n presence: PresenceMap<P>\n /**\n * Fire-and-forget: validated locally, echoed into the map\n * immediately, coalesced on the wire to a fixed cadence (a leading\n * send immediately, then at most one merged send per interval;\n * later values win per field), stamped with the frontier at send\n * time as `seen`. Requires the provider's `participant`.\n */\n setPresence: (values: PresencePatch<P>['values']) => void\n}\n\nexport type UseSessionResult<\n D extends EventDefs,\n S,\n P extends PresenceDefs = Record<never, never>,\n> = WithPresence<P, UseSessionPresence<P>> & {\n /** The live view, folded through the shared reducer. */\n state: S\n /** The raw event feed — observed, seeded, or backscrolled. */\n events: ContractEvent<D>[]\n /** The stream frontier — `lastSeenIndex` for cancellation. */\n index: number\n /**\n * The connection, as a discriminated union — `error` exists only\n * while disconnected; \"reconnecting…\" is\n * `status === 'connecting' && reconnects > 0`.\n */\n connection: Connection\n /**\n * Typed optimistic append. Awaiting it gives the server ack;\n * `.confirmed` resolves when the live stream has delivered the batch\n * back. Rejects with the server's A2Error codes.\n */\n push: (...events: AppendInput<D>[]) => PushResult<D>\n /** Restart the live subscription without resetting its state or cursor. */\n reconnect: () => void\n /**\n * Backscroll: fetch a bounded slice of older events into `events`.\n * Defaults page backward 50 at a time from the oldest loaded event.\n * Display data only — `state` and the optimistic overlay never move.\n */\n loadHistory: (options?: LoadHistoryOptions) => Promise<ContractEvent<D>[]>\n /** Backscroll progress: `complete` means the feed reaches index 1. */\n history: HistoryState\n}\n\nexport type A2React<\n D extends EventDefs,\n S,\n P extends PresenceDefs = Record<never, never>,\n> = {\n SessionProvider: (props: SessionProviderProps<D, S>) => ReactElement\n useSession: () => UseSessionResult<D, S, P>\n}\n\nexport type BoundA2React<\n D extends EventDefs,\n S,\n P extends PresenceDefs = Record<never, never>,\n> = {\n SessionProvider: (props: BoundSessionProviderProps<D, S>) => ReactElement\n useSession: () => UseSessionResult<D, S, P>\n}\n\nexport function createReact<\n D extends EventDefs,\n S,\n P extends PresenceDefs = Record<never, never>,\n>(options: { client: A2Client<D, S, P> }): BoundA2React<D, S, P>\nexport function createReact<\n D extends EventDefs,\n S,\n P extends PresenceDefs = Record<never, never>,\n>(options: { reducer: Reducer<D, S, P> }): A2React<D, S, P>\nexport function createReact<\n D extends EventDefs,\n S,\n P extends PresenceDefs = Record<never, never>,\n>(\n options: { client: A2Client<D, S, P> } | { reducer: Reducer<D, S, P> },\n): BoundA2React<D, S, P> | A2React<D, S, P> {\n const Context = createContext<SessionClient<D, S, P> | null>(null)\n const resolveSession: (\n sessionId: string,\n api: string | undefined,\n initialState: S,\n initialIndex: number,\n initialEvents: ContractEvent<D>[] | undefined,\n participant: string | undefined,\n ) => SessionClient<D, S, P> =\n 'client' in options\n ? (\n sessionId,\n _api,\n initialState,\n initialIndex,\n initialEvents,\n participant,\n ) =>\n options.client.session(sessionId, {\n initialState,\n initialIndex,\n ...(initialEvents === undefined ? {} : { initialEvents }),\n ...(participant === undefined ? {} : { participant }),\n })\n : (() => {\n const clients = new Map<string, A2Client<D, S, P>>()\n return (\n sessionId: string,\n api: string | undefined,\n initialState: S,\n initialIndex: number,\n initialEvents: ContractEvent<D>[] | undefined,\n participant: string | undefined,\n ) => {\n if (api === undefined) {\n throw new TypeError(\n 'SessionProvider requires api when createReact binds a reducer',\n )\n }\n let client = clients.get(api)\n if (!client) {\n client = createClient({ reducer: options.reducer, api })\n clients.set(api, client)\n }\n return client.session(sessionId, {\n initialState,\n initialIndex,\n ...(initialEvents === undefined ? {} : { initialEvents }),\n ...(participant === undefined ? {} : { participant }),\n })\n }\n })()\n\n function SessionProvider(\n props: SessionProviderProps<D, S> | BoundSessionProviderProps<D, S>,\n ): ReactElement {\n const {\n sessionId,\n initialState,\n initialIndex,\n initialEvents,\n participant,\n } = props\n const api = 'api' in props ? props.api : undefined\n const client = useMemo(\n () =>\n resolveSession(\n sessionId,\n api,\n initialState,\n initialIndex,\n initialEvents,\n participant,\n ),\n [sessionId, api, initialState, initialIndex, initialEvents, participant],\n )\n useSessionLifecycle(client, true)\n return createElement(Context.Provider, { value: client }, props.children)\n }\n\n function useBoundSession(): UseSessionResult<D, S, P> {\n const client = useContext(Context)\n if (!client) {\n throw new Error(\n 'useSession must be rendered inside its matching SessionProvider',\n )\n }\n return useSessionResult(client)\n }\n\n return { SessionProvider, useSession: useBoundSession }\n}\n\n// ── the shared session lifecycle ───────────────────────────────\n\n/**\n * Hold a stream lease while mounted and `live` — the client refcounts\n * leases per handle, so however many providers and hooks mount one\n * session, the first connects and the last release closes\n * (StrictMode-safe: the lease is retaken on remount). A standalone\n * hook without a `hydrate` value passes `live: false` and holds the\n * stream — connecting an unhydrated session would replay the whole\n * log, and the library never picks the expensive path silently.\n */\nfunction useSessionLifecycle<D extends EventDefs, S, P extends PresenceDefs>(\n session: SessionClient<D, S, P>,\n live: boolean,\n): void {\n useEffect(() => {\n if (!live) return\n return session.connect()\n }, [session, live])\n}\n\nfunction useSessionResult<D extends EventDefs, S, P extends PresenceDefs>(\n session: SessionClient<D, S, P>,\n): UseSessionResult<D, S, P> {\n const snapshot: SessionSnapshot<D, S, P> = useSyncExternalStore(\n session.subscribe,\n session.getSnapshot,\n session.getSnapshot,\n )\n return useMemo(() => {\n // Runtime mirror of the WithPresence surface: the client attaches\n // setPresence (and the snapshot carries presence) exactly when the\n // reducer declares presence fields — no runtime-inert members.\n const { setPresence } = session as Partial<SessionClientPresence<P>>\n const { presence } = snapshot as Partial<{ presence: PresenceMap<P> }>\n return {\n state: snapshot.state,\n events: snapshot.events,\n index: snapshot.index,\n connection: snapshot.connection,\n push: session.push,\n reconnect: session.reconnect,\n loadHistory: session.loadHistory,\n history: snapshot.history,\n ...(setPresence && presence ? { presence, setPresence } : {}),\n } as UseSessionResult<D, S, P>\n }, [snapshot, session])\n}\n\n/**\n * The standalone, provider-less hook — for apps whose components reach\n * sessions ad hoc (a sidebar of channel sessions, a user session read\n * from a menu). Takes the shared client and a session id; the handle\n * is identity-mapped, so every hook and provider mounting the same\n * session shares one runtime and one leased stream. Hydration is\n * app-owned: pass `hydrate` when your fetch lands; until then the\n * stream is held, and your data layer's loading state is the pending\n * state.\n */\nexport function useSession<\n D extends EventDefs,\n S,\n P extends PresenceDefs = Record<never, never>,\n>(\n client: A2Client<D, S, P>,\n sessionId: string,\n options?: UseSessionOptions<S>,\n): UseSessionResult<D, S, P> {\n const { participant, hydrate } = options ?? {}\n const session = useMemo(\n () =>\n client.session(sessionId, {\n ...(hydrate === undefined\n ? {}\n : { initialState: hydrate.state, initialIndex: hydrate.index }),\n ...(participant === undefined ? {} : { participant }),\n }),\n [client, sessionId, hydrate, participant],\n )\n useSessionLifecycle(session, hydrate !== undefined)\n return useSessionResult(session)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAmLA,SAAgB,YAKd,SAC0C;CAC1C,MAAM,UAAU,cAA6C,IAAI;CACjE,MAAM,iBAQJ,YAAY,WAEN,WACA,MACA,cACA,cACA,eACA,gBAEA,QAAQ,OAAO,QAAQ,WAAW;EAChC;EACA;EACA,GAAI,kBAAkB,KAAA,IAAY,CAAC,IAAI,EAAE,cAAc;EACvD,GAAI,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY;CACrD,CAAC,WACI;EACL,MAAM,0BAAU,IAAI,IAA+B;EACnD,QACE,WACA,KACA,cACA,cACA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;GAChB,QAAQ,SAAS;GACjB,OAAO,SAAS;GAChB,YAAY,SAAS;GACrB,MAAM,QAAQ;GACd,WAAW,QAAQ;GACnB,aAAa,QAAQ;GACrB,SAAS,SAAS;GAClB,GAAI,eAAe,WAAW;IAAE;IAAU;GAAY,IAAI,CAAC;EAC7D;CACF,GAAG,CAAC,UAAU,OAAO,CAAC;AACxB;;;;;;;;;;;AAYA,SAAgB,WAKd,QACA,WACA,SAC2B;CAC3B,MAAM,EAAE,aAAa,YAAY,WAAW,CAAC;CAC7C,MAAM,UAAU,cAEZ,OAAO,QAAQ,WAAW;EACxB,GAAI,YAAY,KAAA,IACZ,CAAC,IACD;GAAE,cAAc,QAAQ;GAAO,cAAc,QAAQ;EAAM;EAC/D,GAAI,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY;CACrD,CAAC,GACH;EAAC;EAAQ;EAAW;EAAS;CAAW,CAC1C;CACA,oBAAoB,SAAS,YAAY,KAAA,CAAS;CAClD,OAAO,iBAAiB,OAAO;AACjC"}
@@ -1,5 +1,5 @@
1
- import { r as Clock } from "./store-DGHeBtIQ.js";
2
- import { T as SchedulerTask, t as A2Scheduler } from "./server-CKY3_lbw.js";
1
+ import { r as Clock } from "./store-DtDOWLSn.js";
2
+ import { T as SchedulerTask, t as A2Scheduler } from "./server-DwPrMqHB.js";
3
3
  //#region src/scheduler-qstash.d.ts
4
4
  type QStashStoreOutage = {
5
5
  version: 1;
@@ -1,6 +1,7 @@
1
1
  import { t as A2Error } from "./errors-DCk6ch5n.js";
2
- import { d as classifySchedulerSendFailure, g as serverInternals, t as DRAIN_TIMINGS, u as assertSchedulerTargets } from "./internal-DRXJ56EI.js";
3
- import { n as deliverSchedulerAppend, o as platformVercelOidcToken } from "./server-CBET-jSz.js";
2
+ import { d as classifySchedulerSendFailure, g as serverInternals, t as DRAIN_TIMINGS, u as assertSchedulerTargets } from "./internal-Dq2qYxou.js";
3
+ import { n as platformVercelOidcToken } from "./platform-B4TnJtWu.js";
4
+ import { n as deliverSchedulerAppend } from "./server-Dkz2a84E.js";
4
5
  import { t as retryableLazy } from "./retryable-lazy-DZWmHpii.js";
5
6
  import { n as SYSTEM_CLOCK } from "./store-N8PXxDAS.js";
6
7
  import { t as normalizeSchedulerTask } from "./scheduler-task-BpzhPnRS.js";
@@ -1 +1 @@
1
- {"version":3,"file":"scheduler-qstash.js","names":[],"sources":["../src/scheduler-qstash.ts"],"sourcesContent":["/**\n * experimental-a2/scheduler-qstash — HTTP scheduler over Upstash QStash.\n *\n * QStash publishes one signed HTTP delivery per scheduler task. Drain tasks\n * use an absolute, whole-second `notBefore` and a fixed-size deduplication id;\n * append tasks hash their stable task id with the callback URL.\n * Store-outage successors carry a signed private generation and back off to\n * one day without deriving their deduplication identity from the local clock.\n * `handler(...servers)` verifies the signature over the raw request body\n * before parsing it, then applies the same drain protocol as the Vercel\n * scheduler adapter.\n *\n * `@upstash/qstash` is an optional peer dependency, imported lazily. The\n * structural `transport` option keeps its types out of A2's public surface and\n * gives tests a provider-faithful injection seam.\n */\n\nimport {\n assertSchedulerTargets,\n classifySchedulerSendFailure,\n DRAIN_TIMINGS,\n serverInternals,\n type DrainResult,\n} from './internal.ts'\nimport { A2Error } from './errors.ts'\nimport { platformVercelOidcToken } from './platform.ts'\nimport { retryableLazy } from './retryable-lazy.ts'\nimport { normalizeSchedulerTask, type SchedulerTask } from './scheduler-task.ts'\nimport {\n deliverSchedulerAppend,\n type A2Scheduler,\n type DrainableServer,\n} from './server.ts'\nimport { SYSTEM_CLOCK, type Clock } from './store.ts'\n\ntype QStashStoreOutage = {\n version: 1\n /** Zero is the first successor created for a store outage. */\n generation: number\n /** The first failing drain task's due time. Append identity lives on the task. */\n rootDueAt?: number\n}\n\ntype QStashMessage = SchedulerTask & {\n /** Provider-private state authenticated as part of QStash's signed body. */\n _a2QStash?: QStashStoreOutage\n}\n\nexport type QStashPublishRequest = {\n url: string\n body: QStashMessage\n /** Headers the transport must deliver to the callback. */\n headers?: Readonly<Record<string, string>>\n /** Header names the transport must redact from provider dashboard/API views. */\n redact?: {\n header: readonly string[]\n }\n /** Whole-second Unix timestamp. Omitted for an immediate delivery. */\n notBefore?: number\n deduplicationId: string\n /** Delivery retries after the initial attempt. */\n retries?: number\n}\n\n/** The request shape passed to an injected `@upstash/qstash` client. */\nexport type QStashClientPublishRequest = Omit<\n QStashPublishRequest,\n 'headers' | 'redact'\n> & {\n headers?: Record<string, string>\n redact?: {\n header: string[]\n }\n}\n\n/** The outbound part of `@upstash/qstash` used by the built-in transport. */\nexport type QStashPublishingClient = {\n publishJSON(request: QStashClientPublishRequest): Promise<unknown>\n}\n\nexport type QStashVerifyRequest = {\n signature: string\n /** The untouched request body covered by the signature. */\n body: string\n /** Exact destination URL, checked against the signature subject. */\n url: string\n upstashRegion?: string\n}\n\n/** The small part of `@upstash/qstash` this adapter needs. */\nexport type QStashTransport = {\n publish(request: QStashPublishRequest): Promise<unknown>\n verify(request: QStashVerifyRequest): Promise<boolean>\n}\n\nexport type QStashSchedulerOptions = {\n /** Exact URL mounted with `scheduler.handler(...)`. Inferred in local dev and on Vercel. */\n url?: string\n /** QStash API token. Default: `QSTASH_TOKEN`. */\n token?: string\n /** QStash signing key. Default: `QSTASH_CURRENT_SIGNING_KEY`. */\n currentSigningKey?: string\n /** Next QStash signing key. Default: `QSTASH_NEXT_SIGNING_KEY`. */\n nextSigningKey?: string\n /** Delivery retries after the initial attempt. Default: provider default. */\n retries?: number\n /** Maximum callback body and outbound task with outage headroom. Default 1 MiB. */\n maxBodyBytes?: number\n /** Static callback headers. QStash receives them; A2 requests dashboard/API redaction. */\n headers?: Readonly<Record<string, string>>\n /** Injectable publishing client. The built-in receiver still verifies callbacks. */\n client?: QStashPublishingClient\n /** Injectable transport (tests). Default: `@upstash/qstash`. */\n transport?: QStashTransport\n /** Injectable clock for due-time calculations (tests). */\n clock?: Clock\n}\n\nconst qstashTransport = async (\n options: Pick<\n QStashSchedulerOptions,\n 'token' | 'currentSigningKey' | 'nextSigningKey' | 'client'\n >,\n developmentMode: boolean | undefined,\n): Promise<QStashTransport> => {\n const sdk = await import('@upstash/qstash').catch(() => {\n throw classifySchedulerSendFailure(\n new Error(\n \"experimental-a2/scheduler-qstash needs the '@upstash/qstash' package (optional peer dependency) — install it, or inject a transport\",\n ),\n 'terminal',\n )\n })\n const developmentOverride =\n developmentMode === undefined ? {} : { devMode: developmentMode }\n const client: QStashPublishingClient =\n options.client ??\n new sdk.Client({\n ...(options.token === undefined ? {} : { token: options.token }),\n ...developmentOverride,\n })\n const receiver = new sdk.Receiver({\n ...(options.currentSigningKey === undefined\n ? {}\n : { currentSigningKey: options.currentSigningKey }),\n ...(options.nextSigningKey === undefined\n ? {}\n : { nextSigningKey: options.nextSigningKey }),\n ...developmentOverride,\n })\n return {\n publish: (request) => {\n const clientRequest: QStashClientPublishRequest = {\n url: request.url,\n body: request.body,\n ...(request.headers === undefined\n ? {}\n : { headers: { ...request.headers } }),\n ...(request.redact === undefined\n ? {}\n : { redact: { header: [...request.redact.header] } }),\n deduplicationId: request.deduplicationId,\n ...(request.retries === undefined ? {} : { retries: request.retries }),\n ...(request.notBefore === undefined\n ? {}\n : { notBefore: request.notBefore }),\n }\n return client.publishJSON(clientRequest)\n },\n verify: (request) => receiver.verify(request),\n }\n}\n\nconst digestId = async (\n parts: readonly (string | number)[],\n): Promise<string> => {\n const digest = await crypto.subtle.digest(\n 'SHA-256',\n new TextEncoder().encode(JSON.stringify(parts)),\n )\n const hex = Array.from(new Uint8Array(digest), (byte) =>\n byte.toString(16).padStart(2, '0'),\n ).join('')\n return `a2_${hex}`\n}\n\ntype ParsedQStashMessage = {\n task: SchedulerTask\n outage?: QStashStoreOutage\n}\n\nconst recordOf = (value: unknown): Record<string, unknown> | null =>\n value !== null && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null\n\nconst TRUSTED_SOURCE_HEADER = 'x-vercel-trusted-oidc-idp-token'\nconst TRUSTED_SOURCE_DELIVERY_MARGIN_MS = 60_000\nconst RESERVED_CALLBACK_HEADERS = new Set([\n 'connection',\n 'content-length',\n 'host',\n 'keep-alive',\n 'proxy-authenticate',\n 'proxy-authorization',\n 'te',\n 'trailer',\n 'transfer-encoding',\n 'upgrade',\n 'x-vercel-oidc-token',\n TRUSTED_SOURCE_HEADER,\n])\n\nconst callbackHeaders = (\n value: Readonly<Record<string, string>> | undefined,\n): Readonly<Record<string, string>> | undefined => {\n if (value === undefined) return undefined\n\n let entries: [string, string][]\n try {\n entries = Object.entries(value)\n } catch {\n throw new TypeError('qstash() headers must be an HTTP header record')\n }\n\n const normalized: [string, string][] = []\n const seen = new Set<string>()\n for (const [name, headerValue] of entries) {\n if (typeof headerValue !== 'string') {\n throw new TypeError('qstash() header values must be strings')\n }\n let entry: [string, string] | undefined\n try {\n entry = [...new Headers([[name, headerValue]]).entries()][0]\n } catch {\n throw new TypeError(\n 'qstash() headers must contain valid HTTP header names and values',\n )\n }\n if (entry === undefined) {\n throw new TypeError(\n 'qstash() headers must contain valid HTTP header names and values',\n )\n }\n const [normalizedName, normalizedValue] = entry\n if (seen.has(normalizedName)) {\n throw new TypeError(\n `qstash() headers contain duplicate name '${normalizedName}'`,\n )\n }\n if (\n normalizedName.startsWith('upstash-') ||\n normalizedName.startsWith('content-type') ||\n RESERVED_CALLBACK_HEADERS.has(normalizedName)\n ) {\n throw new TypeError(\n `qstash() headers cannot set reserved header '${normalizedName}'`,\n )\n }\n seen.add(normalizedName)\n normalized.push([normalizedName, normalizedValue])\n }\n\n return normalized.length === 0\n ? undefined\n : Object.freeze(Object.fromEntries(normalized))\n}\n\nconst publishHeaders = (\n configured: Readonly<Record<string, string>> | undefined,\n generated: Pick<QStashPublishRequest, 'headers' | 'redact'> | undefined,\n): Pick<QStashPublishRequest, 'headers' | 'redact'> | undefined => {\n if (configured === undefined && generated === undefined) return undefined\n\n const headers = new Headers()\n const redacted = new Set<string>()\n for (const [name, value] of Object.entries(configured ?? {})) {\n headers.set(name, value)\n redacted.add(name)\n }\n for (const [name, value] of Object.entries(generated?.headers ?? {})) {\n headers.set(name, value)\n redacted.add(name)\n }\n for (const name of generated?.redact?.header ?? []) {\n const normalized = [...new Headers([[name, 'redacted']]).keys()][0]\n if (normalized === undefined) {\n throw new TypeError('qstash generated an invalid redaction header')\n }\n redacted.add(normalized)\n }\n\n const headerEntries = [...headers.entries()]\n return {\n ...(headerEntries.length === 0\n ? {}\n : { headers: Object.fromEntries(headerEntries) }),\n ...(redacted.size === 0\n ? {}\n : { redact: { header: [...redacted].toSorted() } }),\n }\n}\n\nconst jwtExpirationMs = (token: string): number | null => {\n const parts = token.split('.')\n const payloadPart = parts.length === 3 ? parts[1] : undefined\n if (\n payloadPart === undefined ||\n payloadPart.length === 0 ||\n !/^[A-Za-z0-9_-]+$/.test(payloadPart) ||\n payloadPart.length % 4 === 1\n ) {\n return null\n }\n\n try {\n const decode = globalThis.atob\n if (typeof decode !== 'function') return null\n const base64 = payloadPart\n .replaceAll('-', '+')\n .replaceAll('_', '/')\n .padEnd(payloadPart.length + ((4 - (payloadPart.length % 4)) % 4), '=')\n const binary = decode(base64)\n const bytes = Uint8Array.from(binary, (character) =>\n character.charCodeAt(0),\n )\n const payload = recordOf(JSON.parse(new TextDecoder().decode(bytes)))\n const expiration = payload?.['exp']\n if (\n typeof expiration !== 'number' ||\n !Number.isSafeInteger(expiration) ||\n expiration <= 0 ||\n expiration > Number.MAX_SAFE_INTEGER / 1_000\n ) {\n return null\n }\n return expiration * 1_000\n } catch {\n return null\n }\n}\n\nconst previewTrustedSource = (\n firstDeliveryAt: number,\n): Pick<QStashPublishRequest, 'headers' | 'redact'> | undefined => {\n const token = platformVercelOidcToken()\n if (token === null) return undefined\n const expiration = jwtExpirationMs(token)\n if (\n expiration === null ||\n firstDeliveryAt + TRUSTED_SOURCE_DELIVERY_MARGIN_MS > expiration\n ) {\n return undefined\n }\n return {\n headers: { [TRUSTED_SOURCE_HEADER]: token },\n redact: { header: [TRUSTED_SOURCE_HEADER] },\n }\n}\n\nconst RETRYABLE_HTTP_CLIENT_STATUSES = new Set([408, 409, 425, 429])\n\nconst httpStatusOf = (error: unknown): number | undefined => {\n try {\n const record = recordOf(error)\n if (!record) return undefined\n const response = recordOf(record['response'])\n const statuses = [\n record['status'],\n record['statusCode'],\n response?.['status'],\n ].filter(\n (value): value is number =>\n typeof value === 'number' &&\n Number.isInteger(value) &&\n value >= 100 &&\n value <= 599,\n )\n const [status] = statuses\n if (status === undefined) return undefined\n return statuses.every((candidate) => candidate === status)\n ? status\n : undefined\n } catch {\n return undefined\n }\n}\n\nconst classifyQStashPublishFailure = (error: unknown): unknown => {\n const status = httpStatusOf(error)\n const terminal =\n status !== undefined &&\n status >= 400 &&\n status < 500 &&\n !RETRYABLE_HTTP_CLIENT_STATUSES.has(status)\n return classifySchedulerSendFailure(\n error,\n terminal ? 'terminal' : 'retryable',\n )\n}\n\nconst parseTask = (body: string): ParsedQStashMessage | null => {\n let value: unknown\n try {\n value = JSON.parse(body)\n } catch {\n return null\n }\n const task = normalizeSchedulerTask(value)\n const record = recordOf(value)\n if (!task || !record) return null\n\n const encodedOutage = record['_a2QStash']\n if (encodedOutage === undefined) return { task }\n const outage = recordOf(encodedOutage)\n const generation = outage?.['generation']\n if (\n !outage ||\n outage['version'] !== 1 ||\n typeof generation !== 'number' ||\n !Number.isSafeInteger(generation) ||\n generation < 0 ||\n generation >= Number.MAX_SAFE_INTEGER\n ) {\n return null\n }\n\n const rootDueAt = outage['rootDueAt']\n if (task.kind === 'drain') {\n if (\n typeof rootDueAt !== 'number' ||\n !Number.isInteger(rootDueAt) ||\n rootDueAt % 1_000 !== 0\n ) {\n return null\n }\n } else if (rootDueAt !== undefined) {\n return null\n }\n\n return {\n task,\n outage: {\n version: 1,\n generation,\n ...(rootDueAt === undefined ? {} : { rootDueAt }),\n },\n }\n}\n\nconst DEFAULT_MAX_BODY_BYTES = 1024 * 1024\nconst STORE_OUTAGE_BASE_DELAY_MS = 30_000\nconst STORE_OUTAGE_MAX_DELAY_MS = 24 * 60 * 60 * 1_000\n\nconst readBoundedBody = async (\n request: Request,\n maxBytes: number,\n): Promise<string | null> => {\n const declared = request.headers.get('content-length')\n if (\n declared !== null &&\n /^\\d+$/.test(declared) &&\n Number(declared) > maxBytes\n ) {\n return null\n }\n\n if (request.body === null) return ''\n const reader = request.body.getReader()\n const chunks: Uint8Array[] = []\n let length = 0\n try {\n for (;;) {\n // oxlint-disable-next-line no-await-in-loop\n const { done, value } = await reader.read()\n if (done) break\n length += value.byteLength\n if (length > maxBytes) {\n // oxlint-disable-next-line no-await-in-loop\n await reader.cancel().catch(() => {})\n return null\n }\n chunks.push(value)\n }\n } finally {\n reader.releaseLock()\n }\n\n const bytes = new Uint8Array(length)\n let offset = 0\n for (const chunk of chunks) {\n bytes.set(chunk, offset)\n offset += chunk.byteLength\n }\n return new TextDecoder().decode(bytes)\n}\n\nconst storeUnavailable = (error: unknown): error is A2Error =>\n error instanceof A2Error && error.code === 'STORE_UNAVAILABLE'\n\nconst response = {\n ok: (): Response => new Response('ok'),\n unauthorized: (): Response => new Response('unauthorized', { status: 401 }),\n malformed: (): Response =>\n new Response('invalid a2 scheduler message', {\n status: 489,\n headers: { 'Upstash-NonRetryable-Error': 'true' },\n }),\n tooLarge: (): Response =>\n new Response('a2 scheduler message is too large', {\n status: 489,\n headers: { 'Upstash-NonRetryable-Error': 'true' },\n }),\n}\n\nconst CALLBACK_PATH = '/api/a2/scheduler'\nconst DEFAULT_DEVELOPMENT_PORT = 3_000\n\nconst developmentCallbackUrl = (portValue: string | undefined): string => {\n const port =\n portValue === undefined || portValue === ''\n ? DEFAULT_DEVELOPMENT_PORT\n : Number(portValue)\n if (\n !Number.isSafeInteger(port) ||\n port < 1 ||\n port > 65_535 ||\n (portValue !== undefined && portValue !== '' && !/^\\d+$/.test(portValue))\n ) {\n throw new TypeError(\n 'qstash() could not infer url: PORT must be an integer from 1 to 65535 for local development',\n )\n }\n return `http://localhost:${String(port)}${CALLBACK_PATH}`\n}\n\ntype CallbackResolution = {\n callbackUrl: string\n /** An SDK override. Undefined preserves the SDK's environment behavior. */\n developmentMode?: boolean\n inferredVercelPreview?: true\n}\n\nconst inferCallbackUrl = (): CallbackResolution => {\n const env = typeof process === 'undefined' ? undefined : process.env\n const vercelEnv = env?.['VERCEL_ENV']\n const variable =\n env?.['VERCEL'] !== '1'\n ? null\n : vercelEnv === 'production'\n ? 'VERCEL_PROJECT_PRODUCTION_URL'\n : vercelEnv === 'preview'\n ? 'VERCEL_BRANCH_URL'\n : null\n if (variable !== null) {\n const host = env?.[variable]\n if (!host) {\n throw new TypeError(\n `qstash() could not infer url: ${variable} is missing`,\n )\n }\n let origin: URL\n try {\n origin = new URL(`https://${host}`)\n } catch {\n throw new TypeError(\n `qstash() could not infer url: ${variable} must be a hostname`,\n )\n }\n if (\n origin.host !== host ||\n origin.pathname !== '/' ||\n origin.search !== '' ||\n origin.hash !== '' ||\n origin.username !== '' ||\n origin.password !== '' ||\n origin.port !== ''\n ) {\n throw new TypeError(\n `qstash() could not infer url: ${variable} must be a hostname`,\n )\n }\n return {\n callbackUrl: new URL(CALLBACK_PATH, origin).toString(),\n developmentMode: false,\n ...(vercelEnv === 'preview' ? { inferredVercelPreview: true } : {}),\n }\n }\n\n if (env === undefined) {\n throw new TypeError(\n 'qstash() needs url when the runtime cannot identify local development',\n )\n }\n\n if (env['NODE_ENV'] === 'production') {\n throw new TypeError(\n 'qstash() needs url in production outside a Vercel production or preview deployment',\n )\n }\n\n return {\n callbackUrl: developmentCallbackUrl(env['PORT']),\n developmentMode: true,\n }\n}\n\nexport function qstash(options: QStashSchedulerOptions = {}): A2Scheduler {\n const env = typeof process === 'undefined' ? undefined : process.env\n const resolution: CallbackResolution =\n options.url === undefined\n ? inferCallbackUrl()\n : {\n callbackUrl: options.url,\n ...(env?.['NODE_ENV'] === 'production'\n ? { developmentMode: false }\n : {}),\n }\n const { callbackUrl, developmentMode, inferredVercelPreview } = resolution\n let parsedUrl: URL\n try {\n parsedUrl = new URL(callbackUrl)\n } catch {\n throw new TypeError('qstash() needs an absolute callback url')\n }\n if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {\n throw new TypeError('qstash() callback url must use http or https')\n }\n if (options.client !== undefined && options.transport !== undefined) {\n throw new TypeError('qstash() cannot combine client and transport')\n }\n if (options.client !== undefined && options.token !== undefined) {\n throw new TypeError('qstash() cannot combine client and token')\n }\n const url = parsedUrl.toString()\n const configuredHeaders = callbackHeaders(options.headers)\n const { retries } = options\n if (\n retries !== undefined &&\n (!Number.isSafeInteger(retries) || retries < 0)\n ) {\n throw new TypeError('qstash() retries must be a non-negative integer')\n }\n const maxBodyBytes = options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES\n if (!Number.isSafeInteger(maxBodyBytes) || maxBodyBytes < 1) {\n throw new TypeError('qstash() maxBodyBytes must be a positive integer')\n }\n const clock = options.clock ?? SYSTEM_CLOCK\n\n // Lazy: construction does no I/O and does not require the optional peer.\n const transport = retryableLazy(() =>\n options.transport\n ? Promise.resolve(options.transport)\n : qstashTransport(options, developmentMode),\n ).get\n\n const storeOutageDeduplicationId = (\n task: SchedulerTask,\n outage: QStashStoreOutage,\n ): Promise<string> => {\n if (task.kind === 'append') {\n return digestId([\n 'a2:scheduler-qstash:store-outage:append:v1',\n url,\n task.contract,\n task.sessionId,\n task.id,\n outage.generation,\n ])\n }\n const { rootDueAt } = outage\n if (rootDueAt === undefined) {\n throw new TypeError('qstash store-outage drain needs a root dueAt')\n }\n return digestId([\n 'a2:scheduler-qstash:store-outage:drain:v1',\n url,\n task.contract,\n task.sessionId,\n rootDueAt,\n outage.generation,\n ])\n }\n\n const sendTask = async (\n task: SchedulerTask,\n outage?: QStashStoreOutage,\n ): Promise<void> => {\n const nowMs = clock.now().getTime()\n const requestedDueAt = task.dueAt\n if (!Number.isFinite(requestedDueAt)) {\n throw classifySchedulerSendFailure(\n new TypeError('qstash scheduler dueAt must be a finite number'),\n 'terminal',\n )\n }\n const dueAt =\n requestedDueAt <= nowMs\n ? Math.floor(nowMs / 1_000) * 1_000\n : Math.ceil(requestedDueAt / 1_000) * 1_000\n const normalizedTask: SchedulerTask =\n task.kind === 'append'\n ? {\n version: 1,\n kind: 'append',\n id: task.id,\n contract: task.contract,\n sessionId: task.sessionId,\n dueAt,\n events: task.events,\n }\n : {\n version: 1,\n kind: 'drain',\n contract: task.contract,\n sessionId: task.sessionId,\n dueAt,\n }\n const message: QStashMessage = {\n ...normalizedTask,\n ...(outage === undefined ? {} : { _a2QStash: outage }),\n }\n const sizeCheckedMessage: QStashMessage =\n outage === undefined\n ? {\n ...normalizedTask,\n _a2QStash:\n normalizedTask.kind === 'append'\n ? { version: 1, generation: Number.MAX_SAFE_INTEGER }\n : {\n version: 1,\n generation: Number.MAX_SAFE_INTEGER,\n rootDueAt: dueAt,\n },\n }\n : message\n let bodyBytes: number\n try {\n bodyBytes = new TextEncoder().encode(\n JSON.stringify(sizeCheckedMessage),\n ).byteLength\n } catch (error) {\n throw classifySchedulerSendFailure(error, 'terminal')\n }\n if (bodyBytes > maxBodyBytes) {\n throw classifySchedulerSendFailure(\n new RangeError('qstash scheduler message exceeds maxBodyBytes'),\n 'terminal',\n )\n }\n const deduplicationId =\n outage !== undefined\n ? await storeOutageDeduplicationId(task, outage)\n : task.kind === 'append'\n ? await digestId(['a2:scheduler-qstash:append:v1', url, task.id])\n : await digestId([\n 'a2:scheduler-qstash:v1',\n url,\n task.contract,\n task.sessionId,\n dueAt,\n ])\n const trustedSource =\n inferredVercelPreview === true\n ? previewTrustedSource(Math.max(nowMs, dueAt))\n : undefined\n const deliveryHeaders = publishHeaders(configuredHeaders, trustedSource)\n const t = await transport()\n try {\n await t.publish({\n url,\n body: message,\n ...deliveryHeaders,\n ...(dueAt <= nowMs ? {} : { notBefore: dueAt / 1_000 }),\n deduplicationId,\n ...(retries === undefined ? {} : { retries }),\n })\n } catch (error) {\n throw classifyQStashPublishFailure(error)\n }\n }\n\n const sendStoreOutageSuccessor = async (\n task: SchedulerTask,\n outage?: QStashStoreOutage,\n ): Promise<void> => {\n const generation = (outage?.generation ?? -1) + 1\n const exponent = Math.min(generation, 6)\n const delayMs = Math.min(\n STORE_OUTAGE_MAX_DELAY_MS,\n STORE_OUTAGE_BASE_DELAY_MS * 4 ** exponent,\n )\n const nowMs = clock.now().getTime()\n const dueAt = Math.ceil((nowMs + delayMs) / 1_000) * 1_000\n const nextOutage: QStashStoreOutage =\n task.kind === 'append'\n ? { version: 1, generation }\n : { version: 1, generation, rootDueAt: outage?.rootDueAt ?? task.dueAt }\n await sendTask({ ...task, dueAt }, nextOutage)\n }\n\n const successorDueAt = (message: { dueAt: number }): number => {\n const minimumDueAt =\n clock.now().getTime() +\n DRAIN_TIMINGS.claimTtlMs +\n DRAIN_TIMINGS.watchdogGraceMs\n const beats = Math.max(\n 1,\n Math.ceil(\n (minimumDueAt - message.dueAt) / DRAIN_TIMINGS.claimHeartbeatMs,\n ),\n )\n return message.dueAt + beats * DRAIN_TIMINGS.claimHeartbeatMs\n }\n\n return {\n async schedule(task) {\n await sendTask(task)\n },\n\n handler(...servers: DrainableServer[]) {\n assertSchedulerTargets(servers)\n const byContract = new Map<string, DrainableServer>()\n for (const server of servers) {\n byContract.set(server.contract.name, server)\n }\n return async (req: Request): Promise<Response> => {\n const signature = req.headers.get('upstash-signature')\n if (!signature) return response.unauthorized()\n\n const body = await readBoundedBody(req, maxBodyBytes)\n if (body === null) return response.tooLarge()\n const upstashRegion = req.headers.get('upstash-region')\n const t = await transport()\n try {\n const valid = await t.verify({\n signature,\n body,\n url,\n ...(upstashRegion === null ? {} : { upstashRegion }),\n })\n if (!valid) return response.unauthorized()\n } catch {\n return response.unauthorized()\n }\n\n const parsed = parseTask(body)\n if (!parsed) return response.malformed()\n const { task, outage } = parsed\n\n const server = byContract.get(task.contract)\n if (!server) {\n throw new Error(\n `a2 scheduler: no server for contract '${task.contract}' — pass it to scheduler.handler(...)`,\n )\n }\n const internals = serverInternals.get(server)\n if (task.kind === 'append') {\n try {\n await deliverSchedulerAppend(server, task)\n } catch (error) {\n if (!storeUnavailable(error)) throw error\n await sendStoreOutageSuccessor(task, outage)\n }\n return response.ok()\n }\n\n const nextDueAt = successorDueAt(task)\n let result: DrainResult | { settled: boolean; outcome: 'unknown' }\n try {\n result = internals\n ? await internals.schedulerDrain(task.sessionId, {\n watchdogDueAt: nextDueAt,\n })\n : {\n ...(await server.drain(task.sessionId)),\n outcome: 'unknown' as const,\n }\n } catch (error) {\n if (!storeUnavailable(error)) throw error\n await sendStoreOutageSuccessor(task, outage)\n return response.ok()\n }\n if (result.settled) return response.ok()\n\n if (result.outcome === 'busy') {\n if (result.schedulerArm) await result.schedulerArm\n else {\n await sendTask({\n version: 1,\n kind: 'drain',\n contract: task.contract,\n sessionId: task.sessionId,\n dueAt: nextDueAt,\n })\n }\n return response.ok()\n }\n\n // QStash's per-message retry default can be lower than A2's failure\n // budget. Hand stalled work to a fresh durable message so recovery\n // continues until the store reports success or dead-letter. If this\n // publish fails, the throw keeps the current delivery retryable.\n await sendTask({\n version: 1,\n kind: 'drain',\n contract: task.contract,\n sessionId: task.sessionId,\n dueAt: nextDueAt,\n })\n return response.ok()\n }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAsHA,MAAM,kBAAkB,OACtB,SAIA,oBAC6B;CAC7B,MAAM,MAAM,MAAM,OAAO,kBAAkB,CAAC,YAAY;EACtD,MAAM,6CACJ,IAAI,MACF,qIACF,GACA,UACF;CACF,CAAC;CACD,MAAM,sBACJ,oBAAoB,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,gBAAgB;CAClE,MAAM,SACJ,QAAQ,UACR,IAAI,IAAI,OAAO;EACb,GAAI,QAAQ,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,QAAQ,MAAM;EAC9D,GAAG;CACL,CAAC;CACH,MAAM,WAAW,IAAI,IAAI,SAAS;EAChC,GAAI,QAAQ,sBAAsB,KAAA,IAC9B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;AACF"}
1
+ {"version":3,"file":"scheduler-qstash.js","names":[],"sources":["../src/scheduler-qstash.ts"],"sourcesContent":["/**\n * experimental-a2/scheduler-qstash — HTTP scheduler over Upstash QStash.\n *\n * QStash publishes one signed HTTP delivery per scheduler task. Drain tasks\n * use an absolute, whole-second `notBefore` and a fixed-size deduplication id;\n * append tasks hash their stable task id with the callback URL.\n * Store-outage successors carry a signed private generation and back off to\n * one day without deriving their deduplication identity from the local clock.\n * `handler(...servers)` verifies the signature over the raw request body\n * before parsing it, then applies the same drain protocol as the Vercel\n * scheduler adapter.\n *\n * `@upstash/qstash` is an optional peer dependency, imported lazily. The\n * structural `transport` option keeps its types out of A2's public surface and\n * gives tests a provider-faithful injection seam.\n */\n\nimport {\n assertSchedulerTargets,\n classifySchedulerSendFailure,\n DRAIN_TIMINGS,\n serverInternals,\n type DrainResult,\n} from './internal.ts'\nimport { A2Error } from './errors.ts'\nimport { platformVercelOidcToken } from './platform.ts'\nimport { retryableLazy } from './retryable-lazy.ts'\nimport { normalizeSchedulerTask, type SchedulerTask } from './scheduler-task.ts'\nimport {\n deliverSchedulerAppend,\n type A2Scheduler,\n type DrainableServer,\n} from './server.ts'\nimport { SYSTEM_CLOCK, type Clock } from './store.ts'\n\ntype QStashStoreOutage = {\n version: 1\n /** Zero is the first successor created for a store outage. */\n generation: number\n /** The first failing drain task's due time. Append identity lives on the task. */\n rootDueAt?: number\n}\n\ntype QStashMessage = SchedulerTask & {\n /** Provider-private state authenticated as part of QStash's signed body. */\n _a2QStash?: QStashStoreOutage\n}\n\nexport type QStashPublishRequest = {\n url: string\n body: QStashMessage\n /** Headers the transport must deliver to the callback. */\n headers?: Readonly<Record<string, string>>\n /** Header names the transport must redact from provider dashboard/API views. */\n redact?: {\n header: readonly string[]\n }\n /** Whole-second Unix timestamp. Omitted for an immediate delivery. */\n notBefore?: number\n deduplicationId: string\n /** Delivery retries after the initial attempt. */\n retries?: number\n}\n\n/** The request shape passed to an injected `@upstash/qstash` client. */\nexport type QStashClientPublishRequest = Omit<\n QStashPublishRequest,\n 'headers' | 'redact'\n> & {\n headers?: Record<string, string>\n redact?: {\n header: string[]\n }\n}\n\n/** The outbound part of `@upstash/qstash` used by the built-in transport. */\nexport type QStashPublishingClient = {\n publishJSON(request: QStashClientPublishRequest): Promise<unknown>\n}\n\nexport type QStashVerifyRequest = {\n signature: string\n /** The untouched request body covered by the signature. */\n body: string\n /** Exact destination URL, checked against the signature subject. */\n url: string\n upstashRegion?: string\n}\n\n/** The small part of `@upstash/qstash` this adapter needs. */\nexport type QStashTransport = {\n publish(request: QStashPublishRequest): Promise<unknown>\n verify(request: QStashVerifyRequest): Promise<boolean>\n}\n\nexport type QStashSchedulerOptions = {\n /** Exact URL mounted with `scheduler.handler(...)`. Inferred in local dev and on Vercel. */\n url?: string\n /** QStash API token. Default: `QSTASH_TOKEN`. */\n token?: string\n /** QStash signing key. Default: `QSTASH_CURRENT_SIGNING_KEY`. */\n currentSigningKey?: string\n /** Next QStash signing key. Default: `QSTASH_NEXT_SIGNING_KEY`. */\n nextSigningKey?: string\n /** Delivery retries after the initial attempt. Default: provider default. */\n retries?: number\n /** Maximum callback body and outbound task with outage headroom. Default 1 MiB. */\n maxBodyBytes?: number\n /** Static callback headers. QStash receives them; A2 requests dashboard/API redaction. */\n headers?: Readonly<Record<string, string>>\n /** Injectable publishing client. The built-in receiver still verifies callbacks. */\n client?: QStashPublishingClient\n /** Injectable transport (tests). Default: `@upstash/qstash`. */\n transport?: QStashTransport\n /** Injectable clock for due-time calculations (tests). */\n clock?: Clock\n}\n\nconst qstashTransport = async (\n options: Pick<\n QStashSchedulerOptions,\n 'token' | 'currentSigningKey' | 'nextSigningKey' | 'client'\n >,\n developmentMode: boolean | undefined,\n): Promise<QStashTransport> => {\n const sdk = await import('@upstash/qstash').catch(() => {\n throw classifySchedulerSendFailure(\n new Error(\n \"experimental-a2/scheduler-qstash needs the '@upstash/qstash' package (optional peer dependency) — install it, or inject a transport\",\n ),\n 'terminal',\n )\n })\n const developmentOverride =\n developmentMode === undefined ? {} : { devMode: developmentMode }\n const client: QStashPublishingClient =\n options.client ??\n new sdk.Client({\n ...(options.token === undefined ? {} : { token: options.token }),\n ...developmentOverride,\n })\n const receiver = new sdk.Receiver({\n ...(options.currentSigningKey === undefined\n ? {}\n : { currentSigningKey: options.currentSigningKey }),\n ...(options.nextSigningKey === undefined\n ? {}\n : { nextSigningKey: options.nextSigningKey }),\n ...developmentOverride,\n })\n return {\n publish: (request) => {\n const clientRequest: QStashClientPublishRequest = {\n url: request.url,\n body: request.body,\n ...(request.headers === undefined\n ? {}\n : { headers: { ...request.headers } }),\n ...(request.redact === undefined\n ? {}\n : { redact: { header: [...request.redact.header] } }),\n deduplicationId: request.deduplicationId,\n ...(request.retries === undefined ? {} : { retries: request.retries }),\n ...(request.notBefore === undefined\n ? {}\n : { notBefore: request.notBefore }),\n }\n return client.publishJSON(clientRequest)\n },\n verify: (request) => receiver.verify(request),\n }\n}\n\nconst digestId = async (\n parts: readonly (string | number)[],\n): Promise<string> => {\n const digest = await crypto.subtle.digest(\n 'SHA-256',\n new TextEncoder().encode(JSON.stringify(parts)),\n )\n const hex = Array.from(new Uint8Array(digest), (byte) =>\n byte.toString(16).padStart(2, '0'),\n ).join('')\n return `a2_${hex}`\n}\n\ntype ParsedQStashMessage = {\n task: SchedulerTask\n outage?: QStashStoreOutage\n}\n\nconst recordOf = (value: unknown): Record<string, unknown> | null =>\n value !== null && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null\n\nconst TRUSTED_SOURCE_HEADER = 'x-vercel-trusted-oidc-idp-token'\nconst TRUSTED_SOURCE_DELIVERY_MARGIN_MS = 60_000\nconst RESERVED_CALLBACK_HEADERS = new Set([\n 'connection',\n 'content-length',\n 'host',\n 'keep-alive',\n 'proxy-authenticate',\n 'proxy-authorization',\n 'te',\n 'trailer',\n 'transfer-encoding',\n 'upgrade',\n 'x-vercel-oidc-token',\n TRUSTED_SOURCE_HEADER,\n])\n\nconst callbackHeaders = (\n value: Readonly<Record<string, string>> | undefined,\n): Readonly<Record<string, string>> | undefined => {\n if (value === undefined) return undefined\n\n let entries: [string, string][]\n try {\n entries = Object.entries(value)\n } catch {\n throw new TypeError('qstash() headers must be an HTTP header record')\n }\n\n const normalized: [string, string][] = []\n const seen = new Set<string>()\n for (const [name, headerValue] of entries) {\n if (typeof headerValue !== 'string') {\n throw new TypeError('qstash() header values must be strings')\n }\n let entry: [string, string] | undefined\n try {\n entry = [...new Headers([[name, headerValue]]).entries()][0]\n } catch {\n throw new TypeError(\n 'qstash() headers must contain valid HTTP header names and values',\n )\n }\n if (entry === undefined) {\n throw new TypeError(\n 'qstash() headers must contain valid HTTP header names and values',\n )\n }\n const [normalizedName, normalizedValue] = entry\n if (seen.has(normalizedName)) {\n throw new TypeError(\n `qstash() headers contain duplicate name '${normalizedName}'`,\n )\n }\n if (\n normalizedName.startsWith('upstash-') ||\n normalizedName.startsWith('content-type') ||\n RESERVED_CALLBACK_HEADERS.has(normalizedName)\n ) {\n throw new TypeError(\n `qstash() headers cannot set reserved header '${normalizedName}'`,\n )\n }\n seen.add(normalizedName)\n normalized.push([normalizedName, normalizedValue])\n }\n\n return normalized.length === 0\n ? undefined\n : Object.freeze(Object.fromEntries(normalized))\n}\n\nconst publishHeaders = (\n configured: Readonly<Record<string, string>> | undefined,\n generated: Pick<QStashPublishRequest, 'headers' | 'redact'> | undefined,\n): Pick<QStashPublishRequest, 'headers' | 'redact'> | undefined => {\n if (configured === undefined && generated === undefined) return undefined\n\n const headers = new Headers()\n const redacted = new Set<string>()\n for (const [name, value] of Object.entries(configured ?? {})) {\n headers.set(name, value)\n redacted.add(name)\n }\n for (const [name, value] of Object.entries(generated?.headers ?? {})) {\n headers.set(name, value)\n redacted.add(name)\n }\n for (const name of generated?.redact?.header ?? []) {\n const normalized = [...new Headers([[name, 'redacted']]).keys()][0]\n if (normalized === undefined) {\n throw new TypeError('qstash generated an invalid redaction header')\n }\n redacted.add(normalized)\n }\n\n const headerEntries = [...headers.entries()]\n return {\n ...(headerEntries.length === 0\n ? {}\n : { headers: Object.fromEntries(headerEntries) }),\n ...(redacted.size === 0\n ? {}\n : { redact: { header: [...redacted].toSorted() } }),\n }\n}\n\nconst jwtExpirationMs = (token: string): number | null => {\n const parts = token.split('.')\n const payloadPart = parts.length === 3 ? parts[1] : undefined\n if (\n payloadPart === undefined ||\n payloadPart.length === 0 ||\n !/^[A-Za-z0-9_-]+$/.test(payloadPart) ||\n payloadPart.length % 4 === 1\n ) {\n return null\n }\n\n try {\n const decode = globalThis.atob\n if (typeof decode !== 'function') return null\n const base64 = payloadPart\n .replaceAll('-', '+')\n .replaceAll('_', '/')\n .padEnd(payloadPart.length + ((4 - (payloadPart.length % 4)) % 4), '=')\n const binary = decode(base64)\n const bytes = Uint8Array.from(binary, (character) =>\n character.charCodeAt(0),\n )\n const payload = recordOf(JSON.parse(new TextDecoder().decode(bytes)))\n const expiration = payload?.['exp']\n if (\n typeof expiration !== 'number' ||\n !Number.isSafeInteger(expiration) ||\n expiration <= 0 ||\n expiration > Number.MAX_SAFE_INTEGER / 1_000\n ) {\n return null\n }\n return expiration * 1_000\n } catch {\n return null\n }\n}\n\nconst previewTrustedSource = (\n firstDeliveryAt: number,\n): Pick<QStashPublishRequest, 'headers' | 'redact'> | undefined => {\n const token = platformVercelOidcToken()\n if (token === null) return undefined\n const expiration = jwtExpirationMs(token)\n if (\n expiration === null ||\n firstDeliveryAt + TRUSTED_SOURCE_DELIVERY_MARGIN_MS > expiration\n ) {\n return undefined\n }\n return {\n headers: { [TRUSTED_SOURCE_HEADER]: token },\n redact: { header: [TRUSTED_SOURCE_HEADER] },\n }\n}\n\nconst RETRYABLE_HTTP_CLIENT_STATUSES = new Set([408, 409, 425, 429])\n\nconst httpStatusOf = (error: unknown): number | undefined => {\n try {\n const record = recordOf(error)\n if (!record) return undefined\n const response = recordOf(record['response'])\n const statuses = [\n record['status'],\n record['statusCode'],\n response?.['status'],\n ].filter(\n (value): value is number =>\n typeof value === 'number' &&\n Number.isInteger(value) &&\n value >= 100 &&\n value <= 599,\n )\n const [status] = statuses\n if (status === undefined) return undefined\n return statuses.every((candidate) => candidate === status)\n ? status\n : undefined\n } catch {\n return undefined\n }\n}\n\nconst classifyQStashPublishFailure = (error: unknown): unknown => {\n const status = httpStatusOf(error)\n const terminal =\n status !== undefined &&\n status >= 400 &&\n status < 500 &&\n !RETRYABLE_HTTP_CLIENT_STATUSES.has(status)\n return classifySchedulerSendFailure(\n error,\n terminal ? 'terminal' : 'retryable',\n )\n}\n\nconst parseTask = (body: string): ParsedQStashMessage | null => {\n let value: unknown\n try {\n value = JSON.parse(body)\n } catch {\n return null\n }\n const task = normalizeSchedulerTask(value)\n const record = recordOf(value)\n if (!task || !record) return null\n\n const encodedOutage = record['_a2QStash']\n if (encodedOutage === undefined) return { task }\n const outage = recordOf(encodedOutage)\n const generation = outage?.['generation']\n if (\n !outage ||\n outage['version'] !== 1 ||\n typeof generation !== 'number' ||\n !Number.isSafeInteger(generation) ||\n generation < 0 ||\n generation >= Number.MAX_SAFE_INTEGER\n ) {\n return null\n }\n\n const rootDueAt = outage['rootDueAt']\n if (task.kind === 'drain') {\n if (\n typeof rootDueAt !== 'number' ||\n !Number.isInteger(rootDueAt) ||\n rootDueAt % 1_000 !== 0\n ) {\n return null\n }\n } else if (rootDueAt !== undefined) {\n return null\n }\n\n return {\n task,\n outage: {\n version: 1,\n generation,\n ...(rootDueAt === undefined ? {} : { rootDueAt }),\n },\n }\n}\n\nconst DEFAULT_MAX_BODY_BYTES = 1024 * 1024\nconst STORE_OUTAGE_BASE_DELAY_MS = 30_000\nconst STORE_OUTAGE_MAX_DELAY_MS = 24 * 60 * 60 * 1_000\n\nconst readBoundedBody = async (\n request: Request,\n maxBytes: number,\n): Promise<string | null> => {\n const declared = request.headers.get('content-length')\n if (\n declared !== null &&\n /^\\d+$/.test(declared) &&\n Number(declared) > maxBytes\n ) {\n return null\n }\n\n if (request.body === null) return ''\n const reader = request.body.getReader()\n const chunks: Uint8Array[] = []\n let length = 0\n try {\n for (;;) {\n // oxlint-disable-next-line no-await-in-loop\n const { done, value } = await reader.read()\n if (done) break\n length += value.byteLength\n if (length > maxBytes) {\n // oxlint-disable-next-line no-await-in-loop\n await reader.cancel().catch(() => {})\n return null\n }\n chunks.push(value)\n }\n } finally {\n reader.releaseLock()\n }\n\n const bytes = new Uint8Array(length)\n let offset = 0\n for (const chunk of chunks) {\n bytes.set(chunk, offset)\n offset += chunk.byteLength\n }\n return new TextDecoder().decode(bytes)\n}\n\nconst storeUnavailable = (error: unknown): error is A2Error =>\n error instanceof A2Error && error.code === 'STORE_UNAVAILABLE'\n\nconst response = {\n ok: (): Response => new Response('ok'),\n unauthorized: (): Response => new Response('unauthorized', { status: 401 }),\n malformed: (): Response =>\n new Response('invalid a2 scheduler message', {\n status: 489,\n headers: { 'Upstash-NonRetryable-Error': 'true' },\n }),\n tooLarge: (): Response =>\n new Response('a2 scheduler message is too large', {\n status: 489,\n headers: { 'Upstash-NonRetryable-Error': 'true' },\n }),\n}\n\nconst CALLBACK_PATH = '/api/a2/scheduler'\nconst DEFAULT_DEVELOPMENT_PORT = 3_000\n\nconst developmentCallbackUrl = (portValue: string | undefined): string => {\n const port =\n portValue === undefined || portValue === ''\n ? DEFAULT_DEVELOPMENT_PORT\n : Number(portValue)\n if (\n !Number.isSafeInteger(port) ||\n port < 1 ||\n port > 65_535 ||\n (portValue !== undefined && portValue !== '' && !/^\\d+$/.test(portValue))\n ) {\n throw new TypeError(\n 'qstash() could not infer url: PORT must be an integer from 1 to 65535 for local development',\n )\n }\n return `http://localhost:${String(port)}${CALLBACK_PATH}`\n}\n\ntype CallbackResolution = {\n callbackUrl: string\n /** An SDK override. Undefined preserves the SDK's environment behavior. */\n developmentMode?: boolean\n inferredVercelPreview?: true\n}\n\nconst inferCallbackUrl = (): CallbackResolution => {\n const env = typeof process === 'undefined' ? undefined : process.env\n const vercelEnv = env?.['VERCEL_ENV']\n const variable =\n env?.['VERCEL'] !== '1'\n ? null\n : vercelEnv === 'production'\n ? 'VERCEL_PROJECT_PRODUCTION_URL'\n : vercelEnv === 'preview'\n ? 'VERCEL_BRANCH_URL'\n : null\n if (variable !== null) {\n const host = env?.[variable]\n if (!host) {\n throw new TypeError(\n `qstash() could not infer url: ${variable} is missing`,\n )\n }\n let origin: URL\n try {\n origin = new URL(`https://${host}`)\n } catch {\n throw new TypeError(\n `qstash() could not infer url: ${variable} must be a hostname`,\n )\n }\n if (\n origin.host !== host ||\n origin.pathname !== '/' ||\n origin.search !== '' ||\n origin.hash !== '' ||\n origin.username !== '' ||\n origin.password !== '' ||\n origin.port !== ''\n ) {\n throw new TypeError(\n `qstash() could not infer url: ${variable} must be a hostname`,\n )\n }\n return {\n callbackUrl: new URL(CALLBACK_PATH, origin).toString(),\n developmentMode: false,\n ...(vercelEnv === 'preview' ? { inferredVercelPreview: true } : {}),\n }\n }\n\n if (env === undefined) {\n throw new TypeError(\n 'qstash() needs url when the runtime cannot identify local development',\n )\n }\n\n if (env['NODE_ENV'] === 'production') {\n throw new TypeError(\n 'qstash() needs url in production outside a Vercel production or preview deployment',\n )\n }\n\n return {\n callbackUrl: developmentCallbackUrl(env['PORT']),\n developmentMode: true,\n }\n}\n\nexport function qstash(options: QStashSchedulerOptions = {}): A2Scheduler {\n const env = typeof process === 'undefined' ? undefined : process.env\n const resolution: CallbackResolution =\n options.url === undefined\n ? inferCallbackUrl()\n : {\n callbackUrl: options.url,\n ...(env?.['NODE_ENV'] === 'production'\n ? { developmentMode: false }\n : {}),\n }\n const { callbackUrl, developmentMode, inferredVercelPreview } = resolution\n let parsedUrl: URL\n try {\n parsedUrl = new URL(callbackUrl)\n } catch {\n throw new TypeError('qstash() needs an absolute callback url')\n }\n if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {\n throw new TypeError('qstash() callback url must use http or https')\n }\n if (options.client !== undefined && options.transport !== undefined) {\n throw new TypeError('qstash() cannot combine client and transport')\n }\n if (options.client !== undefined && options.token !== undefined) {\n throw new TypeError('qstash() cannot combine client and token')\n }\n const url = parsedUrl.toString()\n const configuredHeaders = callbackHeaders(options.headers)\n const { retries } = options\n if (\n retries !== undefined &&\n (!Number.isSafeInteger(retries) || retries < 0)\n ) {\n throw new TypeError('qstash() retries must be a non-negative integer')\n }\n const maxBodyBytes = options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES\n if (!Number.isSafeInteger(maxBodyBytes) || maxBodyBytes < 1) {\n throw new TypeError('qstash() maxBodyBytes must be a positive integer')\n }\n const clock = options.clock ?? SYSTEM_CLOCK\n\n // Lazy: construction does no I/O and does not require the optional peer.\n const transport = retryableLazy(() =>\n options.transport\n ? Promise.resolve(options.transport)\n : qstashTransport(options, developmentMode),\n ).get\n\n const storeOutageDeduplicationId = (\n task: SchedulerTask,\n outage: QStashStoreOutage,\n ): Promise<string> => {\n if (task.kind === 'append') {\n return digestId([\n 'a2:scheduler-qstash:store-outage:append:v1',\n url,\n task.contract,\n task.sessionId,\n task.id,\n outage.generation,\n ])\n }\n const { rootDueAt } = outage\n if (rootDueAt === undefined) {\n throw new TypeError('qstash store-outage drain needs a root dueAt')\n }\n return digestId([\n 'a2:scheduler-qstash:store-outage:drain:v1',\n url,\n task.contract,\n task.sessionId,\n rootDueAt,\n outage.generation,\n ])\n }\n\n const sendTask = async (\n task: SchedulerTask,\n outage?: QStashStoreOutage,\n ): Promise<void> => {\n const nowMs = clock.now().getTime()\n const requestedDueAt = task.dueAt\n if (!Number.isFinite(requestedDueAt)) {\n throw classifySchedulerSendFailure(\n new TypeError('qstash scheduler dueAt must be a finite number'),\n 'terminal',\n )\n }\n const dueAt =\n requestedDueAt <= nowMs\n ? Math.floor(nowMs / 1_000) * 1_000\n : Math.ceil(requestedDueAt / 1_000) * 1_000\n const normalizedTask: SchedulerTask =\n task.kind === 'append'\n ? {\n version: 1,\n kind: 'append',\n id: task.id,\n contract: task.contract,\n sessionId: task.sessionId,\n dueAt,\n events: task.events,\n }\n : {\n version: 1,\n kind: 'drain',\n contract: task.contract,\n sessionId: task.sessionId,\n dueAt,\n }\n const message: QStashMessage = {\n ...normalizedTask,\n ...(outage === undefined ? {} : { _a2QStash: outage }),\n }\n const sizeCheckedMessage: QStashMessage =\n outage === undefined\n ? {\n ...normalizedTask,\n _a2QStash:\n normalizedTask.kind === 'append'\n ? { version: 1, generation: Number.MAX_SAFE_INTEGER }\n : {\n version: 1,\n generation: Number.MAX_SAFE_INTEGER,\n rootDueAt: dueAt,\n },\n }\n : message\n let bodyBytes: number\n try {\n bodyBytes = new TextEncoder().encode(\n JSON.stringify(sizeCheckedMessage),\n ).byteLength\n } catch (error) {\n throw classifySchedulerSendFailure(error, 'terminal')\n }\n if (bodyBytes > maxBodyBytes) {\n throw classifySchedulerSendFailure(\n new RangeError('qstash scheduler message exceeds maxBodyBytes'),\n 'terminal',\n )\n }\n const deduplicationId =\n outage !== undefined\n ? await storeOutageDeduplicationId(task, outage)\n : task.kind === 'append'\n ? await digestId(['a2:scheduler-qstash:append:v1', url, task.id])\n : await digestId([\n 'a2:scheduler-qstash:v1',\n url,\n task.contract,\n task.sessionId,\n dueAt,\n ])\n const trustedSource =\n inferredVercelPreview === true\n ? previewTrustedSource(Math.max(nowMs, dueAt))\n : undefined\n const deliveryHeaders = publishHeaders(configuredHeaders, trustedSource)\n const t = await transport()\n try {\n await t.publish({\n url,\n body: message,\n ...deliveryHeaders,\n ...(dueAt <= nowMs ? {} : { notBefore: dueAt / 1_000 }),\n deduplicationId,\n ...(retries === undefined ? {} : { retries }),\n })\n } catch (error) {\n throw classifyQStashPublishFailure(error)\n }\n }\n\n const sendStoreOutageSuccessor = async (\n task: SchedulerTask,\n outage?: QStashStoreOutage,\n ): Promise<void> => {\n const generation = (outage?.generation ?? -1) + 1\n const exponent = Math.min(generation, 6)\n const delayMs = Math.min(\n STORE_OUTAGE_MAX_DELAY_MS,\n STORE_OUTAGE_BASE_DELAY_MS * 4 ** exponent,\n )\n const nowMs = clock.now().getTime()\n const dueAt = Math.ceil((nowMs + delayMs) / 1_000) * 1_000\n const nextOutage: QStashStoreOutage =\n task.kind === 'append'\n ? { version: 1, generation }\n : { version: 1, generation, rootDueAt: outage?.rootDueAt ?? task.dueAt }\n await sendTask({ ...task, dueAt }, nextOutage)\n }\n\n const successorDueAt = (message: { dueAt: number }): number => {\n const minimumDueAt =\n clock.now().getTime() +\n DRAIN_TIMINGS.claimTtlMs +\n DRAIN_TIMINGS.watchdogGraceMs\n const beats = Math.max(\n 1,\n Math.ceil(\n (minimumDueAt - message.dueAt) / DRAIN_TIMINGS.claimHeartbeatMs,\n ),\n )\n return message.dueAt + beats * DRAIN_TIMINGS.claimHeartbeatMs\n }\n\n return {\n async schedule(task) {\n await sendTask(task)\n },\n\n handler(...servers: DrainableServer[]) {\n assertSchedulerTargets(servers)\n const byContract = new Map<string, DrainableServer>()\n for (const server of servers) {\n byContract.set(server.contract.name, server)\n }\n return async (req: Request): Promise<Response> => {\n const signature = req.headers.get('upstash-signature')\n if (!signature) return response.unauthorized()\n\n const body = await readBoundedBody(req, maxBodyBytes)\n if (body === null) return response.tooLarge()\n const upstashRegion = req.headers.get('upstash-region')\n const t = await transport()\n try {\n const valid = await t.verify({\n signature,\n body,\n url,\n ...(upstashRegion === null ? {} : { upstashRegion }),\n })\n if (!valid) return response.unauthorized()\n } catch {\n return response.unauthorized()\n }\n\n const parsed = parseTask(body)\n if (!parsed) return response.malformed()\n const { task, outage } = parsed\n\n const server = byContract.get(task.contract)\n if (!server) {\n throw new Error(\n `a2 scheduler: no server for contract '${task.contract}' — pass it to scheduler.handler(...)`,\n )\n }\n const internals = serverInternals.get(server)\n if (task.kind === 'append') {\n try {\n await deliverSchedulerAppend(server, task)\n } catch (error) {\n if (!storeUnavailable(error)) throw error\n await sendStoreOutageSuccessor(task, outage)\n }\n return response.ok()\n }\n\n const nextDueAt = successorDueAt(task)\n let result: DrainResult | { settled: boolean; outcome: 'unknown' }\n try {\n result = internals\n ? await internals.schedulerDrain(task.sessionId, {\n watchdogDueAt: nextDueAt,\n })\n : {\n ...(await server.drain(task.sessionId)),\n outcome: 'unknown' as const,\n }\n } catch (error) {\n if (!storeUnavailable(error)) throw error\n await sendStoreOutageSuccessor(task, outage)\n return response.ok()\n }\n if (result.settled) return response.ok()\n\n if (result.outcome === 'busy') {\n if (result.schedulerArm) await result.schedulerArm\n else {\n await sendTask({\n version: 1,\n kind: 'drain',\n contract: task.contract,\n sessionId: task.sessionId,\n dueAt: nextDueAt,\n })\n }\n return response.ok()\n }\n\n // QStash's per-message retry default can be lower than A2's failure\n // budget. Hand stalled work to a fresh durable message so recovery\n // continues until the store reports success or dead-letter. If this\n // publish fails, the throw keeps the current delivery retryable.\n await sendTask({\n version: 1,\n kind: 'drain',\n contract: task.contract,\n sessionId: task.sessionId,\n dueAt: nextDueAt,\n })\n return response.ok()\n }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAsHA,MAAM,kBAAkB,OACtB,SAIA,oBAC6B;CAC7B,MAAM,MAAM,MAAM,OAAO,kBAAkB,CAAC,YAAY;EACtD,MAAM,6CACJ,IAAI,MACF,qIACF,GACA,UACF;CACF,CAAC;CACD,MAAM,sBACJ,oBAAoB,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,gBAAgB;CAClE,MAAM,SACJ,QAAQ,UACR,IAAI,IAAI,OAAO;EACb,GAAI,QAAQ,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,QAAQ,MAAM;EAC9D,GAAG;CACL,CAAC;CACH,MAAM,WAAW,IAAI,IAAI,SAAS;EAChC,GAAI,QAAQ,sBAAsB,KAAA,IAC9B,CAAC,IACD,EAAE,mBAAmB,QAAQ,kBAAkB;EACnD,GAAI,QAAQ,mBAAmB,KAAA,IAC3B,CAAC,IACD,EAAE,gBAAgB,QAAQ,eAAe;EAC7C,GAAG;CACL,CAAC;CACD,OAAO;EACL,UAAU,YAAY;GACpB,MAAM,gBAA4C;IA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MAAM,SAAS,WAAW,IAAI,KAAK,QAAQ;IAC3C,IAAI,CAAC,QACH,MAAM,IAAI,MACR,yCAAyC,KAAK,SAAS,sCACzD;IAEF,MAAM,YAAY,gBAAgB,IAAI,MAAM;IAC5C,IAAI,KAAK,SAAS,UAAU;KAC1B,IAAI;MACF,MAAM,uBAAuB,QAAQ,IAAI;KAC3C,SAAS,OAAO;MACd,IAAI,CAAC,iBAAiB,KAAK,GAAG,MAAM;MACpC,MAAM,yBAAyB,MAAM,MAAM;KAC7C;KACA,OAAO,SAAS,GAAG;IACrB;IAEA,MAAM,YAAY,eAAe,IAAI;IACrC,IAAI;IACJ,IAAI;KACF,SAAS,YACL,MAAM,UAAU,eAAe,KAAK,WAAW,EAC7C,eAAe,UACjB,CAAC,IACD;MACE,GAAI,MAAM,OAAO,MAAM,KAAK,SAAS;MACrC,SAAS;KACX;IACN,SAAS,OAAO;KACd,IAAI,CAAC,iBAAiB,KAAK,GAAG,MAAM;KACpC,MAAM,yBAAyB,MAAM,MAAM;KAC3C,OAAO,SAAS,GAAG;IACrB;IACA,IAAI,OAAO,SAAS,OAAO,SAAS,GAAG;IAEvC,IAAI,OAAO,YAAY,QAAQ;KAC7B,IAAI,OAAO,cAAc,MAAM,OAAO;UAEpC,MAAM,SAAS;MACb,SAAS;MACT,MAAM;MACN,UAAU,KAAK;MACf,WAAW,KAAK;MAChB,OAAO;KACT,CAAC;KAEH,OAAO,SAAS,GAAG;IACrB;IAMA,MAAM,SAAS;KACb,SAAS;KACT,MAAM;KACN,UAAU,KAAK;KACf,WAAW,KAAK;KAChB,OAAO;IACT,CAAC;IACD,OAAO,SAAS,GAAG;GACrB;EACF;CACF;AACF"}
@@ -1,5 +1,5 @@
1
- import { r as Clock } from "./store-DGHeBtIQ.js";
2
- import { T as SchedulerTask, t as A2Scheduler } from "./server-CKY3_lbw.js";
1
+ import { r as Clock } from "./store-DtDOWLSn.js";
2
+ import { T as SchedulerTask, t as A2Scheduler } from "./server-DwPrMqHB.js";
3
3
  //#region src/scheduler-vercel.d.ts
4
4
  /**
5
5
  * The "not settled yet" signal for a stalled handler — an expected state,
@@ -1,5 +1,5 @@
1
- import { d as classifySchedulerSendFailure, g as serverInternals, t as DRAIN_TIMINGS, u as assertSchedulerTargets } from "./internal-DRXJ56EI.js";
2
- import { n as deliverSchedulerAppend } from "./server-CBET-jSz.js";
1
+ import { d as classifySchedulerSendFailure, g as serverInternals, t as DRAIN_TIMINGS, u as assertSchedulerTargets } from "./internal-Dq2qYxou.js";
2
+ import { n as deliverSchedulerAppend } from "./server-Dkz2a84E.js";
3
3
  import { t as retryableLazy } from "./retryable-lazy-DZWmHpii.js";
4
4
  import { n as SYSTEM_CLOCK } from "./store-N8PXxDAS.js";
5
5
  import { t as normalizeSchedulerTask } from "./scheduler-task-BpzhPnRS.js";