@fantastic.dev/better-stripe 0.93.0 → 0.95.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 (57) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/renewalAttach/internal/operationJournal.d.ts +47 -0
  4. package/dist/client/billing/renewalAttach/internal/operationJournal.d.ts.map +1 -0
  5. package/dist/client/billing/renewalAttach/internal/operationJournal.js +388 -0
  6. package/dist/client/billing/renewalAttach/internal/operationJournal.js.map +1 -0
  7. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.d.ts +24 -5
  8. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.d.ts.map +1 -1
  9. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.js +182 -4
  10. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.js.map +1 -1
  11. package/dist/client/billing/renewalAttach/internal/producer/invocationProducer.d.ts +13 -0
  12. package/dist/client/billing/renewalAttach/internal/producer/invocationProducer.d.ts.map +1 -0
  13. package/dist/client/billing/renewalAttach/internal/producer/invocationProducer.js +43 -0
  14. package/dist/client/billing/renewalAttach/internal/producer/invocationProducer.js.map +1 -0
  15. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.d.ts +32 -0
  16. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.d.ts.map +1 -0
  17. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.js +105 -0
  18. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.js.map +1 -0
  19. package/dist/client/billing/renewalAttach/internal/producer/ownedAwaitFactory.d.ts +3 -0
  20. package/dist/client/billing/renewalAttach/internal/producer/ownedAwaitFactory.d.ts.map +1 -0
  21. package/dist/client/billing/renewalAttach/internal/producer/ownedAwaitFactory.js +59 -0
  22. package/dist/client/billing/renewalAttach/internal/producer/ownedAwaitFactory.js.map +1 -0
  23. package/dist/client/billing/renewalAttach/internal/producer/ownerFactory.d.ts +11 -0
  24. package/dist/client/billing/renewalAttach/internal/producer/ownerFactory.d.ts.map +1 -0
  25. package/dist/client/billing/renewalAttach/internal/producer/ownerFactory.js +121 -0
  26. package/dist/client/billing/renewalAttach/internal/producer/ownerFactory.js.map +1 -0
  27. package/dist/client/billing/renewalAttach/internal/producer/stockDelegateFactory.d.ts +6 -0
  28. package/dist/client/billing/renewalAttach/internal/producer/stockDelegateFactory.d.ts.map +1 -0
  29. package/dist/client/billing/renewalAttach/internal/producer/stockDelegateFactory.js +16 -0
  30. package/dist/client/billing/renewalAttach/internal/producer/stockDelegateFactory.js.map +1 -0
  31. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +32 -32
  32. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +16 -16
  33. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  34. package/dist/component/balanceFunding/mutations.d.ts +43 -43
  35. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  36. package/dist/component/financialObservations/settlementHelpers.d.ts +3 -3
  37. package/dist/component/usageCredits/accounting.fixtures.d.ts +16 -16
  38. package/docs/renewal-context-reads.md +57 -5
  39. package/package.json +1 -1
  40. package/src/client/billing/renewalAttach/internal/operationJournal.acknowledgement.integration.test.ts +500 -0
  41. package/src/client/billing/renewalAttach/internal/operationJournal.c10.integration.test.ts +560 -0
  42. package/src/client/billing/renewalAttach/internal/operationJournal.controls.integration.test.ts +356 -0
  43. package/src/client/billing/renewalAttach/internal/operationJournal.integration.test.ts +181 -1
  44. package/src/client/billing/renewalAttach/internal/operationJournal.methods.integration.test.ts +534 -0
  45. package/src/client/billing/renewalAttach/internal/operationJournal.ts +573 -0
  46. package/src/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.ts +246 -8
  47. package/src/client/billing/renewalAttach/internal/producer/invocationProducer.ts +58 -0
  48. package/src/client/billing/renewalAttach/internal/producer/lineageAuthority.ts +161 -0
  49. package/src/client/billing/renewalAttach/internal/producer/ownedAwaitFactory.ts +54 -0
  50. package/src/client/billing/renewalAttach/internal/producer/ownerFactory.ts +124 -0
  51. package/src/client/billing/renewalAttach/internal/producer/producerGuards.integration.test.ts +323 -0
  52. package/src/client/billing/renewalAttach/internal/producer/producerInitial.integration.test.ts +301 -0
  53. package/src/client/billing/renewalAttach/internal/producer/producerIsolation.integration.test.ts +531 -0
  54. package/src/client/billing/renewalAttach/internal/producer/producerOwner.integration.test.ts +457 -0
  55. package/src/client/billing/renewalAttach/internal/producer/stockDelegateFactory.ts +23 -0
  56. package/src/client/billing/renewalAttach/internal/test-fixtures/producerInitialDeclarations.ts +5 -0
  57. package/src/client/billing/renewalAttach/internal/test-fixtures/producerInitialOperation.ts +80 -0
@@ -1,11 +1,10 @@
1
1
  import type { GenericActionCtx, GenericDataModel } from "convex/server";
2
- import type { Id } from "../../../../../component/_generated/dataModel.js";
3
2
  import type { Component } from "../../../../helpers.js";
4
3
  import { RenewalContextClient } from "../../../../renewalContextClient.js";
5
4
 
6
5
  export type ClassActionInput = Readonly<{
7
6
  actualActionCtx: GenericActionCtx<GenericDataModel>;
8
- operationId: Id<"renewalOperations">;
7
+ operationId: string;
9
8
  }>;
10
9
  type Bootstrap = Readonly<{
11
10
  prototype: object;
@@ -131,7 +130,7 @@ export function finishClassRoot(actualRoot: object, raw: Bootstrap): void {
131
130
  }
132
131
  }
133
132
 
134
- /** EMPTY profiles refuse before entry, client selection or Action reflection. */
133
+ /** Operational EMPTY profiles refuse before entry, selector or Action reflection. */
135
134
  export async function captureMaintainedActionSelection(
136
135
  actualRoot: object,
137
136
  _input: ClassActionInput,
@@ -146,10 +145,249 @@ export async function captureMaintainedActionSelection(
146
145
  throw Error("CLASS_ACTION_PROFILE_UNBOUND");
147
146
  }
148
147
 
149
- /** Positive per-Action admission is not implemented by the inert bootstrap. */
148
+ type ReadyRoot = Extract<RootCell, { phase: "ready" }>;
149
+ type ActionContext = ClassActionInput["actualActionCtx"];
150
+ type JournalRPC = Readonly<{
151
+ receiver: ActionContext;
152
+ component: Component;
153
+ operationId: string;
154
+ metaReceiver: ActionContext["meta"];
155
+ getMetadata: ActionContext["meta"]["getFunctionMetadata"];
156
+ runQuery: ActionContext["runQuery"];
157
+ runMutation: ActionContext["runMutation"];
158
+ tag: object;
159
+ }>;
160
+ type PendingJournal = {
161
+ root: object;
162
+ cell: ReadyRoot;
163
+ input: ClassActionInput;
164
+ entered: boolean;
165
+ binding: object | null;
166
+ };
167
+ type JournalState = Readonly<{
168
+ root: object;
169
+ cell: ReadyRoot;
170
+ rpc: JournalRPC;
171
+ configuration: readonly (PropertyDescriptor | undefined)[];
172
+ }>;
173
+ const configurationKeys = ["_apiKey", "stripeApiVersion"] as const;
174
+ const pendingJournalEntries = new WeakMap<object, PendingJournal>();
175
+ const journalBindings = new WeakMap<object, JournalState>();
176
+ const closedJournalBindings = new WeakSet<object>();
177
+ function journalUnbound(): never {
178
+ throw Error("CLASS_ACTION_JOURNAL_UNBOUND");
179
+ }
180
+ function journalPointersMatch(state: JournalState): boolean {
181
+ const { root, cell, rpc } = state;
182
+ return (
183
+ roots.get(root) === cell &&
184
+ Object.getPrototypeOf(root) === cell.bootstrap.prototype &&
185
+ rpc.receiver.meta === rpc.metaReceiver &&
186
+ rpc.metaReceiver.getFunctionMetadata === rpc.getMetadata &&
187
+ rpc.receiver.runQuery === rpc.runQuery &&
188
+ rpc.receiver.runMutation === rpc.runMutation
189
+ );
190
+ }
191
+
192
+ /** Checked private bookkeeping identity only; never an operational selection. */
193
+ export function readCheckedJournalActionRPC(binding: unknown): JournalRPC {
194
+ if (typeof binding !== "object" || binding === null) journalUnbound();
195
+ const state = journalBindings.get(binding);
196
+ if (!state || closedJournalBindings.has(binding)) journalUnbound();
197
+ try {
198
+ if (!journalPointersMatch(state)) journalUnbound();
199
+ } catch {
200
+ closedJournalBindings.add(binding);
201
+ journalUnbound();
202
+ }
203
+ return state.rpc;
204
+ }
205
+
206
+ /** Fixed class entry for journal DATA, independent of operational qualification. */
207
+ export async function captureMaintainedJournalBinding(
208
+ actualRoot: object,
209
+ input: ClassActionInput,
210
+ ): Promise<object> {
211
+ const cell = roots.get(actualRoot);
212
+ if (
213
+ !cell ||
214
+ cell.phase !== "ready" ||
215
+ Object.getPrototypeOf(actualRoot) !== cell.bootstrap.prototype
216
+ )
217
+ rootUnbound();
218
+ const keys = Reflect.ownKeys(input);
219
+ const context = Object.getOwnPropertyDescriptor(input, "actualActionCtx");
220
+ const operation = Object.getOwnPropertyDescriptor(input, "operationId");
221
+ if (
222
+ keys.length !== 2 ||
223
+ !keys.every((key) => key === "actualActionCtx" || key === "operationId") ||
224
+ !context ||
225
+ !("value" in context) ||
226
+ !context.enumerable ||
227
+ !operation ||
228
+ !("value" in operation) ||
229
+ !operation.enumerable ||
230
+ typeof operation.value !== "string" ||
231
+ operation.value.length === 0
232
+ )
233
+ journalUnbound();
234
+ const entryInput: ClassActionInput = Object.freeze({
235
+ actualActionCtx: context.value,
236
+ operationId: operation.value,
237
+ });
238
+ const entry: PendingJournal = {
239
+ root: actualRoot,
240
+ cell,
241
+ input: entryInput,
242
+ entered: false,
243
+ binding: null,
244
+ };
245
+ pendingJournalEntries.set(entryInput, entry);
246
+ try {
247
+ const result: unknown = await Reflect.apply(
248
+ cell.bootstrap.enter,
249
+ actualRoot,
250
+ [entryInput],
251
+ );
252
+ if (
253
+ typeof result !== "object" ||
254
+ result === null ||
255
+ result !== entry.binding ||
256
+ pendingJournalEntries.get(entryInput) !== entry ||
257
+ !entry.entered
258
+ )
259
+ journalUnbound();
260
+ const state = journalBindings.get(result);
261
+ if (
262
+ !state ||
263
+ state.root !== actualRoot ||
264
+ state.cell !== cell ||
265
+ state.rpc.operationId !== entryInput.operationId
266
+ )
267
+ journalUnbound();
268
+ readCheckedJournalActionRPC(result);
269
+ return result;
270
+ } catch (error) {
271
+ if (entry.binding) closedJournalBindings.add(entry.binding);
272
+ throw error;
273
+ } finally {
274
+ pendingJournalEntries.delete(entryInput);
275
+ }
276
+ }
277
+
278
+ /** Only the actual constructor-captured private entry can complete pending DATA. */
150
279
  export async function beginClassAction(
151
- _actualRoot: object,
152
- _input: ClassActionInput,
153
- ): Promise<never> {
154
- return rootUnbound();
280
+ actualRoot: object,
281
+ input: ClassActionInput,
282
+ ): Promise<object> {
283
+ const entry = pendingJournalEntries.get(input);
284
+ if (
285
+ !entry ||
286
+ entry.root !== actualRoot ||
287
+ entry.input !== input ||
288
+ entry.entered ||
289
+ roots.get(actualRoot) !== entry.cell
290
+ )
291
+ return rootUnbound();
292
+ entry.entered = true;
293
+ const receiver = input.actualActionCtx;
294
+ if (typeof receiver !== "object" || receiver === null) journalUnbound();
295
+ const metaReceiver = receiver.meta;
296
+ const getMetadata = metaReceiver?.getFunctionMetadata;
297
+ const runQuery = receiver.runQuery;
298
+ const runMutation = receiver.runMutation;
299
+ if (
300
+ typeof getMetadata !== "function" ||
301
+ typeof runQuery !== "function" ||
302
+ typeof runMutation !== "function"
303
+ )
304
+ journalUnbound();
305
+ const rpc: JournalRPC = Object.freeze({
306
+ receiver,
307
+ component: entry.cell.component,
308
+ operationId: input.operationId,
309
+ metaReceiver,
310
+ getMetadata,
311
+ runQuery,
312
+ runMutation,
313
+ tag: Object.freeze({}),
314
+ });
315
+ const metadata = await getMetadata.call(metaReceiver);
316
+ const state: JournalState = Object.freeze({
317
+ root: actualRoot,
318
+ cell: entry.cell,
319
+ rpc,
320
+ configuration: Object.freeze(
321
+ configurationKeys.map((key) =>
322
+ Object.getOwnPropertyDescriptor(actualRoot, key),
323
+ ),
324
+ ),
325
+ });
326
+ if (
327
+ metadata.type !== "action" ||
328
+ typeof metadata.name !== "string" ||
329
+ metadata.name.length === 0 ||
330
+ typeof metadata.componentPath !== "string" ||
331
+ (metadata.visibility !== "public" && metadata.visibility !== "internal") ||
332
+ pendingJournalEntries.get(input) !== entry ||
333
+ entry.binding !== null ||
334
+ !journalPointersMatch(state)
335
+ )
336
+ journalUnbound();
337
+ const binding = Object.freeze({});
338
+ journalBindings.set(binding, state);
339
+ entry.binding = binding;
340
+ return binding;
341
+ }
342
+
343
+ /** Private construction snapshot; journal DATA alone never calls this selector. */
344
+ export function captureInitialJournalSelection(
345
+ binding: object,
346
+ apiVersion: string,
347
+ ) {
348
+ readCheckedJournalActionRPC(binding);
349
+ const state = journalBindings.get(binding);
350
+ if (!state) journalUnbound();
351
+ const captured = state;
352
+ function check() {
353
+ readCheckedJournalActionRPC(binding);
354
+ for (let index = 0; index < configurationKeys.length; index++) {
355
+ const before = captured.configuration[index];
356
+ const after = Object.getOwnPropertyDescriptor(
357
+ captured.root,
358
+ configurationKeys[index],
359
+ );
360
+ if (
361
+ !before ||
362
+ !after ||
363
+ !("value" in before) ||
364
+ !("value" in after) ||
365
+ before.value !== after.value ||
366
+ before.writable !== after.writable ||
367
+ before.enumerable !== after.enumerable ||
368
+ before.configurable !== after.configurable
369
+ )
370
+ journalUnbound();
371
+ }
372
+ if (
373
+ typeof captured.configuration[0]?.value !== "string" ||
374
+ captured.configuration[0].value.length === 0 ||
375
+ captured.configuration[1]?.value !== apiVersion
376
+ )
377
+ journalUnbound();
378
+ }
379
+ check();
380
+ return Object.freeze({
381
+ check,
382
+ select() {
383
+ check();
384
+ const client: unknown = Reflect.apply(
385
+ captured.cell.bootstrap.select,
386
+ captured.root,
387
+ [],
388
+ );
389
+ check();
390
+ return client;
391
+ },
392
+ });
155
393
  }
@@ -0,0 +1,58 @@
1
+ import { mintInitialLineage, readInitialLineage } from "./lineageAuthority.js";
2
+ import { ownerForInitialLineage, type InitialOwner } from "./ownerFactory.js";
3
+ import { ownedAwaitForInitialLineage } from "./ownedAwaitFactory.js";
4
+ import { stockDelegateForInitialLineage } from "./stockDelegateFactory.js";
5
+ import type { createClassActionOperationJournal } from "../operationJournal.js";
6
+
7
+ export type InitialInvocationCore = Readonly<{
8
+ owner: InitialOwner;
9
+ basisJSON: string;
10
+ delegate: ReturnType<typeof stockDelegateForInitialLineage>;
11
+ owned<T>(work: () => T | PromiseLike<T>): Promise<T>;
12
+ operationalAuthority: false;
13
+ }>;
14
+
15
+ /** Node-only private construction. Does not admit an operational runtime profile. */
16
+ export async function captureInitialInvocationCore(
17
+ call: unknown,
18
+ journal: Awaited<ReturnType<typeof createClassActionOperationJournal>>,
19
+ ): Promise<InitialInvocationCore> {
20
+ const token = mintInitialLineage(call, journal, arguments.length);
21
+ const lineage = readInitialLineage(token);
22
+ const owner = ownerForInitialLineage(token);
23
+ try {
24
+ const owned = ownedAwaitForInitialLineage(token);
25
+ const reservation = lineage.reservation;
26
+ if (!("timingPolicyJSON" in reservation))
27
+ throw Error("INITIAL_LINEAGE_UNBOUND");
28
+ const bound = await owned(() =>
29
+ journal.bindInitialBasis({
30
+ attemptId: reservation.attemptId,
31
+ policyJSON: reservation.timingPolicyJSON,
32
+ basisJSON: lineage.basisJSON,
33
+ }),
34
+ );
35
+ if (
36
+ bound.status !== "bound" ||
37
+ bound.operationId !== reservation.operationId ||
38
+ bound.initialBasis.attemptId !== reservation.attemptId ||
39
+ bound.initialBasis.sourcePayloadId !== reservation.payloadId ||
40
+ bound.initialBasis.basisJSON !== lineage.basisJSON ||
41
+ bound.initialBasis.policyJSON !== reservation.timingPolicyJSON ||
42
+ bound.initialBasis.stage !== "attach" ||
43
+ bound.initialBasis.version !== 1
44
+ )
45
+ throw Error("INITIAL_LINEAGE_UNBOUND");
46
+ owner.check();
47
+ return Object.freeze({
48
+ owner,
49
+ basisJSON: lineage.basisJSON,
50
+ owned,
51
+ delegate: stockDelegateForInitialLineage(token),
52
+ operationalAuthority: false,
53
+ });
54
+ } catch (error) {
55
+ owner.retire();
56
+ throw error;
57
+ }
58
+ }
@@ -0,0 +1,161 @@
1
+ import Stripe from "stripe";
2
+ import { types } from "node:util";
3
+ import { consumeInitialClassReservation } from "../operationJournal.js";
4
+ import { captureInitialJournalSelection } from "./classOwnedActionRoot.js";
5
+ import { canonicalInitialBasis } from "../../../../../shared/renewalOperationJournal.js";
6
+
7
+ const method = Object.getOwnPropertyDescriptor(
8
+ Stripe.prototype,
9
+ "rawRequest",
10
+ )?.value;
11
+ const u64 = 18446744073709551615n;
12
+ const timerLimit = 2147483647;
13
+ function stop(): never {
14
+ throw Error("INITIAL_LINEAGE_UNBOUND");
15
+ }
16
+ const ms = (value: number) => Number.isSafeInteger(value) && value >= 0;
17
+
18
+ // Only this module mints identities. Retained journal DATA cannot construct one.
19
+ class InitialLineage {}
20
+ type Lineage = Readonly<{
21
+ reservation: ReturnType<typeof consumeInitialClassReservation>["reservation"];
22
+ selection: ReturnType<typeof captureInitialJournalSelection>;
23
+ client: Stripe;
24
+ method: Stripe["rawRequest"];
25
+ basis: Readonly<{
26
+ startWallMs: number;
27
+ startNs: bigint;
28
+ workEndWallMs: number;
29
+ workEndNs: bigint;
30
+ endWallMs: number;
31
+ endNs: bigint;
32
+ }>;
33
+ basisJSON: string;
34
+ initialHighNs: bigint;
35
+ policy: Readonly<{
36
+ firstDispatchedAt: number;
37
+ periodStart: number;
38
+ periodEnd: number;
39
+ }>;
40
+ wall: () => number;
41
+ monotonic: () => bigint;
42
+ }>;
43
+ const lineages = new WeakMap<object, Lineage>();
44
+
45
+ /** Consumes original CAS custody before any selector, runtime clock or Owner. */
46
+ export function mintInitialLineage(
47
+ call: unknown,
48
+ journal: unknown,
49
+ arity: number,
50
+ ): object {
51
+ const { reservation, binding } = consumeInitialClassReservation(
52
+ call,
53
+ journal,
54
+ );
55
+ if (arity !== 2) stop();
56
+ if (
57
+ !("recordVersion" in reservation) ||
58
+ reservation.recordVersion !== 2 ||
59
+ reservation.stage !== "attach" ||
60
+ !("timingPolicyJSON" in reservation)
61
+ )
62
+ stop();
63
+ const selection = captureInitialJournalSelection(
64
+ binding,
65
+ reservation.apiVersion,
66
+ );
67
+ const client = selection.select();
68
+ if (
69
+ !client ||
70
+ typeof client !== "object" ||
71
+ types.isProxy(client) ||
72
+ Object.getPrototypeOf(client) !== Stripe.prototype ||
73
+ Object.prototype.hasOwnProperty.call(client, "rawRequest") ||
74
+ typeof method !== "function" ||
75
+ Object.getOwnPropertyDescriptor(Stripe.prototype, "rawRequest")?.value !==
76
+ method
77
+ )
78
+ stop();
79
+ selection.check();
80
+ const policy = JSON.parse(reservation.timingPolicyJSON) as {
81
+ firstDispatchedAt: number;
82
+ periodStart: number;
83
+ periodEnd: number;
84
+ workEndWallMs: number;
85
+ endWallMs: number;
86
+ };
87
+ const wall = Date.now;
88
+ const monotonic = process.hrtime.bigint;
89
+ const lo = monotonic();
90
+ const startWallMs = wall();
91
+ const hi = monotonic();
92
+ if (
93
+ !ms(startWallMs) ||
94
+ lo < 0n ||
95
+ hi < lo ||
96
+ hi > u64 ||
97
+ hi - lo > 1000000n ||
98
+ startWallMs >= policy.workEndWallMs ||
99
+ policy.endWallMs - startWallMs > timerLimit
100
+ )
101
+ stop();
102
+ const basis = Object.freeze({
103
+ startWallMs,
104
+ startNs: lo,
105
+ workEndWallMs: policy.workEndWallMs,
106
+ workEndNs:
107
+ lo + (BigInt(policy.workEndWallMs) - BigInt(startWallMs)) * 1000000n,
108
+ endWallMs: policy.endWallMs,
109
+ endNs: lo + (BigInt(policy.endWallMs) - BigInt(startWallMs)) * 1000000n,
110
+ });
111
+ if (basis.endNs > u64) stop();
112
+ const rawBasisJSON = JSON.stringify({
113
+ startWallMs,
114
+ startNsDecimal: lo.toString(),
115
+ workEndWallMs: basis.workEndWallMs,
116
+ workEndNsDecimal: basis.workEndNs.toString(),
117
+ endWallMs: basis.endWallMs,
118
+ endNsDecimal: basis.endNs.toString(),
119
+ });
120
+ const { basisJSON } = canonicalInitialBasis(
121
+ reservation.timingPolicyJSON,
122
+ rawBasisJSON,
123
+ );
124
+ selection.check();
125
+ const token = Object.freeze(new InitialLineage());
126
+ lineages.set(
127
+ token,
128
+ Object.freeze({
129
+ reservation,
130
+ selection,
131
+ client: client as Stripe,
132
+ method: method as Stripe["rawRequest"],
133
+ basis,
134
+ basisJSON,
135
+ initialHighNs: hi,
136
+ policy: Object.freeze({
137
+ firstDispatchedAt: policy.firstDispatchedAt,
138
+ periodStart: policy.periodStart,
139
+ periodEnd: policy.periodEnd,
140
+ }),
141
+ wall,
142
+ monotonic,
143
+ }),
144
+ );
145
+ return token;
146
+ }
147
+
148
+ /** Opaque private identity required by every invocation kernel. */
149
+ export function readInitialLineage(token: object): Lineage {
150
+ const lineage = lineages.get(token);
151
+ if (!lineage) stop();
152
+ lineage.selection.check();
153
+ if (
154
+ Object.getOwnPropertyDescriptor(Stripe.prototype, "rawRequest")?.value !==
155
+ lineage.method ||
156
+ Object.prototype.hasOwnProperty.call(lineage.client, "rawRequest") ||
157
+ Object.getPrototypeOf(lineage.client) !== Stripe.prototype
158
+ )
159
+ stop();
160
+ return lineage;
161
+ }
@@ -0,0 +1,54 @@
1
+ import { ownerForInitialLineage } from "./ownerFactory.js";
2
+
3
+ /** Each continuation retains its own canonical Owner, with no ambient switch. */
4
+ export function ownedAwaitForInitialLineage(token: object) {
5
+ const owner = ownerForInitialLineage(token);
6
+ return function owned<T>(work: () => T | PromiseLike<T>): Promise<T> {
7
+ owner.check();
8
+ return new Promise((resolve, reject) => {
9
+ let settled = false;
10
+ let remove: (() => void) | null = null;
11
+ function finish(ok: boolean, value: unknown) {
12
+ if (settled) return;
13
+ settled = true;
14
+ remove?.();
15
+ if (ok) resolve(value as T);
16
+ else reject(value);
17
+ }
18
+ const retire = () => finish(false, Error("INITIAL_OWNER_STOP"));
19
+ remove = owner.subscribe(retire);
20
+ if (settled) {
21
+ remove();
22
+ return;
23
+ }
24
+ let pending: T | PromiseLike<T>;
25
+ try {
26
+ owner.check();
27
+ pending = work();
28
+ } catch (error) {
29
+ finish(false, error);
30
+ return;
31
+ }
32
+ void Promise.resolve(pending).then(
33
+ (value) => {
34
+ if (settled) return;
35
+ try {
36
+ owner.check();
37
+ finish(true, value);
38
+ } catch {
39
+ retire();
40
+ }
41
+ },
42
+ (error: unknown) => {
43
+ if (settled) return;
44
+ try {
45
+ owner.check();
46
+ finish(false, error);
47
+ } catch {
48
+ retire();
49
+ }
50
+ },
51
+ );
52
+ });
53
+ };
54
+ }
@@ -0,0 +1,124 @@
1
+ import { readInitialLineage } from "./lineageAuthority.js";
2
+ import { types } from "node:util";
3
+ import type { OriginalBasis, OriginalSample } from "../originalOwner.js";
4
+
5
+ export type InitialOwner = Readonly<{
6
+ basis: Readonly<OriginalBasis>;
7
+ check(): Readonly<OriginalSample>;
8
+ sample(): Readonly<OriginalSample>;
9
+ subscribe(fn: () => void): () => void;
10
+ retire(): void;
11
+ }>;
12
+
13
+ const owners = new WeakMap<object, InitialOwner>();
14
+ function stop(): never {
15
+ throw Error("INITIAL_OWNER_STOP");
16
+ }
17
+ /** One canonical, independently retired Owner per original private lineage. */
18
+ export function ownerForInitialLineage(token: object): InitialOwner {
19
+ const existing = owners.get(token);
20
+ if (existing) return existing;
21
+ const lineage = readInitialLineage(token);
22
+ const { basis, policy } = lineage;
23
+ let closed = false;
24
+ let checking = false;
25
+ let last: Readonly<OriginalSample> | null = null;
26
+ const listeners = new Set<{ fn: () => void; active: boolean }>();
27
+ let timer: ReturnType<typeof setTimeout> | undefined;
28
+ function retire() {
29
+ if (closed) return;
30
+ closed = true;
31
+ if (timer !== undefined) clearTimeout(timer);
32
+ const active = [...listeners];
33
+ listeners.clear();
34
+ for (const listener of active) {
35
+ if (!listener.active) continue;
36
+ listener.active = false;
37
+ try {
38
+ Reflect.apply(listener.fn, undefined, []);
39
+ } catch {
40
+ /* Retirement cannot be reversed by a waiter. */
41
+ }
42
+ }
43
+ }
44
+ function check(): Readonly<OriginalSample> {
45
+ if (closed || checking) {
46
+ retire();
47
+ stop();
48
+ }
49
+ checking = true;
50
+ try {
51
+ if (readInitialLineage(token) !== lineage) stop();
52
+ const wallMs = lineage.wall();
53
+ const ns = lineage.monotonic();
54
+ const nowSeconds = Math.floor(wallMs / 1000);
55
+ if (
56
+ !Number.isSafeInteger(wallMs) ||
57
+ wallMs < basis.startWallMs ||
58
+ wallMs >= basis.workEndWallMs ||
59
+ wallMs >= basis.endWallMs ||
60
+ ns < lineage.initialHighNs ||
61
+ ns >= basis.workEndNs ||
62
+ ns >= basis.endNs ||
63
+ (last && (wallMs < last.wallMs || ns < last.ns)) ||
64
+ nowSeconds < policy.firstDispatchedAt ||
65
+ nowSeconds - policy.firstDispatchedAt >= 86400 ||
66
+ nowSeconds < policy.periodStart ||
67
+ nowSeconds >= policy.periodEnd ||
68
+ closed
69
+ )
70
+ stop();
71
+ last = Object.freeze({ wallMs, ns, nowSeconds, retired: false });
72
+ return last;
73
+ } catch {
74
+ retire();
75
+ return stop();
76
+ } finally {
77
+ checking = false;
78
+ }
79
+ }
80
+ const owner: InitialOwner = Object.freeze({
81
+ get basis() {
82
+ if (closed) stop();
83
+ return basis;
84
+ },
85
+ check,
86
+ sample: check,
87
+ retire,
88
+ subscribe(listener: () => void) {
89
+ if (typeof listener !== "function" || types.isProxy(listener)) {
90
+ retire();
91
+ stop();
92
+ }
93
+ if (closed) {
94
+ try {
95
+ listener();
96
+ } catch {
97
+ /* Already retired. */
98
+ }
99
+ return () => {};
100
+ }
101
+ const record = { fn: listener, active: true };
102
+ listeners.add(record);
103
+ return () => {
104
+ record.active = false;
105
+ listeners.delete(record);
106
+ };
107
+ },
108
+ });
109
+ owners.set(token, owner);
110
+ try {
111
+ check();
112
+ // Absolute original cutoff, never a new budget when a continuation resumes.
113
+ timer = setTimeout(
114
+ retire,
115
+ Math.max(0, basis.workEndWallMs - lineage.wall()),
116
+ );
117
+ timer.unref?.();
118
+ check();
119
+ return owner;
120
+ } catch (error) {
121
+ retire();
122
+ throw error;
123
+ }
124
+ }