@fantastic.dev/better-stripe 0.97.1 → 0.98.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 (68) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/renewalAttach/internal/acquisition/ownedAcquisition.d.ts +5 -0
  4. package/dist/client/billing/renewalAttach/internal/acquisition/ownedAcquisition.d.ts.map +1 -1
  5. package/dist/client/billing/renewalAttach/internal/acquisition/ownedAcquisition.js +38 -0
  6. package/dist/client/billing/renewalAttach/internal/acquisition/ownedAcquisition.js.map +1 -1
  7. package/dist/client/billing/renewalAttach/internal/operations/fixedTransport.d.ts +54 -0
  8. package/dist/client/billing/renewalAttach/internal/operations/fixedTransport.d.ts.map +1 -1
  9. package/dist/client/billing/renewalAttach/internal/operations/fixedTransport.js +44 -37
  10. package/dist/client/billing/renewalAttach/internal/operations/fixedTransport.js.map +1 -1
  11. package/dist/client/billing/renewalAttach/internal/operations/initialActorData.d.ts +21 -0
  12. package/dist/client/billing/renewalAttach/internal/operations/initialActorData.d.ts.map +1 -0
  13. package/dist/client/billing/renewalAttach/internal/operations/initialActorData.js +36 -0
  14. package/dist/client/billing/renewalAttach/internal/operations/initialActorData.js.map +1 -0
  15. package/dist/client/billing/renewalAttach/internal/operations/initialAttach.d.ts +3 -0
  16. package/dist/client/billing/renewalAttach/internal/operations/initialAttach.d.ts.map +1 -1
  17. package/dist/client/billing/renewalAttach/internal/operations/initialAttach.js +71 -46
  18. package/dist/client/billing/renewalAttach/internal/operations/initialAttach.js.map +1 -1
  19. package/dist/client/billing/renewalAttach/internal/operations/ownedAwait.d.ts +1 -0
  20. package/dist/client/billing/renewalAttach/internal/operations/ownedAwait.d.ts.map +1 -1
  21. package/dist/client/billing/renewalAttach/internal/operations/ownedAwait.js +17 -5
  22. package/dist/client/billing/renewalAttach/internal/operations/ownedAwait.js.map +1 -1
  23. package/dist/client/billing/renewalAttach/internal/operations/transportCapture.d.ts +35 -0
  24. package/dist/client/billing/renewalAttach/internal/operations/transportCapture.d.ts.map +1 -0
  25. package/dist/client/billing/renewalAttach/internal/operations/transportCapture.js +46 -0
  26. package/dist/client/billing/renewalAttach/internal/operations/transportCapture.js.map +1 -0
  27. package/dist/client/billing/renewalAttach/internal/producer/invocationProducer.d.ts +6 -0
  28. package/dist/client/billing/renewalAttach/internal/producer/invocationProducer.d.ts.map +1 -1
  29. package/dist/client/billing/renewalAttach/internal/producer/invocationProducer.js +19 -0
  30. package/dist/client/billing/renewalAttach/internal/producer/invocationProducer.js.map +1 -1
  31. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.d.ts +1 -0
  32. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.d.ts.map +1 -1
  33. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.js +3 -0
  34. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.js.map +1 -1
  35. package/dist/client/billing/renewalAttach/internal/producer/operationFactory.d.ts +65 -0
  36. package/dist/client/billing/renewalAttach/internal/producer/operationFactory.d.ts.map +1 -0
  37. package/dist/client/billing/renewalAttach/internal/producer/operationFactory.js +161 -0
  38. package/dist/client/billing/renewalAttach/internal/producer/operationFactory.js.map +1 -0
  39. package/dist/client/billing/renewalAttach/internal/producer/stockDelegateFactory.d.ts +4 -0
  40. package/dist/client/billing/renewalAttach/internal/producer/stockDelegateFactory.d.ts.map +1 -1
  41. package/dist/client/billing/renewalAttach/internal/producer/stockDelegateFactory.js +24 -3
  42. package/dist/client/billing/renewalAttach/internal/producer/stockDelegateFactory.js.map +1 -1
  43. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +32 -32
  44. package/dist/client/connect/payoutSyncTestHelpers.d.ts +16 -16
  45. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  46. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  47. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  48. package/dist/component/earnings/triggers.d.ts +16 -16
  49. package/dist/component/payoutRelease/queries.d.ts +2 -2
  50. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  51. package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
  52. package/dist/component/usage/allowance.fixtures.d.ts +16 -16
  53. package/docs/renewal-context-reads.md +26 -6
  54. package/package.json +1 -1
  55. package/src/client/billing/renewalAttach/internal/acquisition/ownedAcquisition.ts +42 -0
  56. package/src/client/billing/renewalAttach/internal/operations/fixedTransport.ts +55 -48
  57. package/src/client/billing/renewalAttach/internal/operations/initialActorData.ts +41 -0
  58. package/src/client/billing/renewalAttach/internal/operations/initialAttach.ts +91 -55
  59. package/src/client/billing/renewalAttach/internal/operations/ownedAwait.ts +23 -5
  60. package/src/client/billing/renewalAttach/internal/operations/transportCapture.ts +60 -0
  61. package/src/client/billing/renewalAttach/internal/producer/invocationProducer.ts +22 -0
  62. package/src/client/billing/renewalAttach/internal/producer/lineageAuthority.ts +3 -0
  63. package/src/client/billing/renewalAttach/internal/producer/operationFactory.ts +175 -0
  64. package/src/client/billing/renewalAttach/internal/producer/producerAcquisition.integration.test.ts +240 -0
  65. package/src/client/billing/renewalAttach/internal/producer/producerActor.integration.test.ts +526 -0
  66. package/src/client/billing/renewalAttach/internal/producer/producerTransport.integration.test.ts +440 -0
  67. package/src/client/billing/renewalAttach/internal/producer/stockDelegateFactory.ts +29 -5
  68. package/src/client/billing/renewalAttach/internal/test-fixtures/producerInitialOperation.ts +69 -11
@@ -0,0 +1,60 @@
1
+ import { types } from "node:util";
2
+ import { OWNER } from "../originalOwner.js";
3
+ import { ownerForInitialLineage } from "../producer/ownerFactory.js";
4
+ import {
5
+ closed,
6
+ captureRequestAndReads,
7
+ need,
8
+ type SourceMethod,
9
+ } from "./types.js";
10
+
11
+ function sourceFunction(
12
+ service: unknown,
13
+ name: string,
14
+ ): { receiver: object; method: SourceMethod } {
15
+ need(service && typeof service === "object" && !types.isProxy(service));
16
+ const d = Object.getOwnPropertyDescriptor(service, name);
17
+ need(d && "value" in d && typeof d.value === "function");
18
+ // The function is selected once from validated own data, preserving its receiver.
19
+ return { receiver: service, method: d.value as SourceMethod };
20
+ }
21
+
22
+ /** Internal fixed attach profile: 43 reads and one POST, never a 44-GET profile. */
23
+ function captureSource(raw: unknown, expectedOwner: typeof OWNER) {
24
+ const b = closed(raw, ["owner", "request", "readPlan", "delegate"]);
25
+ need(b.owner === expectedOwner);
26
+ const owner = sourceFunction(b.owner, "check"),
27
+ delegate = sourceFunction(b.delegate, "rawRequest");
28
+ const { request, plan } = captureRequestAndReads(b.request, b.readPlan);
29
+ return Object.freeze({
30
+ owner: owner.receiver,
31
+ check: owner.method,
32
+ delegate: delegate.receiver,
33
+ send: delegate.method,
34
+ request,
35
+ plan: Object.freeze(plan),
36
+ });
37
+ }
38
+
39
+ export function captureLegacyTransportSource(raw: unknown) {
40
+ return captureSource(raw, OWNER);
41
+ }
42
+ export function captureInitialTransportSource(token: object, raw: unknown) {
43
+ return captureSource(raw, ownerForInitialLineage(token));
44
+ }
45
+
46
+ export function checkTransportOwnerResult(value: unknown) {
47
+ const x = closed(value, ["wallMs", "ns", "nowSeconds", "retired"]);
48
+ need(
49
+ typeof x.wallMs === "number" &&
50
+ Number.isSafeInteger(x.wallMs) &&
51
+ x.wallMs >= 0 &&
52
+ typeof x.ns === "bigint" &&
53
+ x.ns >= 0n &&
54
+ x.ns <= 18446744073709551615n &&
55
+ typeof x.nowSeconds === "number" &&
56
+ Number.isSafeInteger(x.nowSeconds) &&
57
+ x.nowSeconds === Math.floor(x.wallMs / 1000) &&
58
+ x.retired === false,
59
+ );
60
+ }
@@ -5,6 +5,12 @@ import { stockDelegateForInitialLineage } from "./stockDelegateFactory.js";
5
5
  import type { createClassActionOperationJournal } from "../operationJournal.js";
6
6
  import { createInitialAttachEventCompiler } from "../c10/attachEvents.js";
7
7
  import { createInitialMaterialClassifiers } from "../material/classifiers.js";
8
+ import { createInitialTransportForLineage } from "../operations/fixedTransport.js";
9
+ import {
10
+ acquisitionForInitialLineage,
11
+ type RawAcquisitionResult,
12
+ } from "../acquisition/ownedAcquisition.js";
13
+ import { captureInitialAttachForLineage } from "../operations/initialAttach.js";
8
14
 
9
15
  export type InitialInvocationCore = Readonly<{
10
16
  owner: InitialOwner;
@@ -13,6 +19,9 @@ export type InitialInvocationCore = Readonly<{
13
19
  owned<T>(work: () => T | PromiseLike<T>): Promise<T>;
14
20
  attachEvents(): ReturnType<typeof createInitialAttachEventCompiler>;
15
21
  material: ReturnType<typeof createInitialMaterialClassifiers>;
22
+ transport(): ReturnType<typeof createInitialTransportForLineage>;
23
+ acquire(): Promise<RawAcquisitionResult>;
24
+ initialAttach(): ReturnType<typeof captureInitialAttachForLineage>;
16
25
  operationalAuthority: false;
17
26
  }>;
18
27
 
@@ -62,6 +71,19 @@ export async function captureInitialInvocationCore(
62
71
  return createInitialAttachEventCompiler(token);
63
72
  },
64
73
  material: createInitialMaterialClassifiers(token),
74
+ async transport() {
75
+ if (arguments.length !== 0) throw Error("INITIAL_OPERATION_UNBOUND");
76
+ return owned(() => createInitialTransportForLineage(token));
77
+ },
78
+ async acquire() {
79
+ if (arguments.length !== 0) throw Error("INITIAL_OPERATION_UNBOUND");
80
+ const reader = await owned(() => acquisitionForInitialLineage(token));
81
+ return owned(() => reader.acquire());
82
+ },
83
+ initialAttach() {
84
+ if (arguments.length !== 0) throw Error("INITIAL_OPERATION_UNBOUND");
85
+ return captureInitialAttachForLineage(token);
86
+ },
65
87
  operationalAuthority: false,
66
88
  });
67
89
  } catch (error) {
@@ -16,7 +16,9 @@ const ms = (value: number) => Number.isSafeInteger(value) && value >= 0;
16
16
 
17
17
  // Only this module mints identities. Retained journal DATA cannot construct one.
18
18
  class InitialLineage {}
19
+ class InitialOrigin {}
19
20
  type Lineage = Readonly<{
21
+ originAssociation: object;
20
22
  journal: ReturnType<typeof consumeInitialClassReservation>["journal"];
21
23
  reservation: ReturnType<typeof consumeInitialClassReservation>["reservation"];
22
24
  selection: ReturnType<typeof captureInitialJournalSelection>;
@@ -125,6 +127,7 @@ export function mintInitialLineage(
125
127
  lineages.set(
126
128
  token,
127
129
  Object.freeze({
130
+ originAssociation: Object.freeze(new InitialOrigin()),
128
131
  journal: originalJournal,
129
132
  reservation,
130
133
  selection,
@@ -0,0 +1,175 @@
1
+ import { readInitialLineage } from "./lineageAuthority.js";
2
+ import { ownerForInitialLineage } from "./ownerFactory.js";
3
+ import { ownedAwaitForInitialLineage } from "./ownedAwaitFactory.js";
4
+ import { captureInitialStockRawDelegate } from "./stockDelegateFactory.js";
5
+ import { createInitialMaterialClassifiers } from "../material/classifiers.js";
6
+ import { captureRetainedInput } from "../material/capture.js";
7
+ import { captureAttachReceipt } from "../c10/eventCapture.js";
8
+ import { field, scalar } from "../c10/ownData.js";
9
+ import { materialize } from "../c10/eventCodec.js";
10
+
11
+ function stop(): never {
12
+ throw Error("INITIAL_OPERATION_UNBOUND");
13
+ }
14
+ const operations = new WeakMap<object, ReturnType<typeof construct>>();
15
+
16
+ async function construct(token: object) {
17
+ const lineage = readInitialLineage(token);
18
+ const owner = ownerForInitialLineage(token);
19
+ const owned = ownedAwaitForInitialLineage(token);
20
+ const classified = await createInitialMaterialClassifiers(token).retained();
21
+ owner.check();
22
+ if (classified.status !== "classified") stop();
23
+ const retained = JSON.parse(lineage.reservation.recordJSON);
24
+ const original = captureRetainedInput({
25
+ attachRequest: retained.attachRequest,
26
+ originalBundle: retained.originalBundle,
27
+ });
28
+ const request = classified.material.completeRequest;
29
+ const customer = classified.material.billingCustomer;
30
+ if (!customer || typeof customer.id !== "string") stop();
31
+ const query = String(
32
+ new URLSearchParams(
33
+ ["discounts", "items.data.discounts", "items.data.price"].map(
34
+ (value, index) => ["expand[" + index + "]", value],
35
+ ),
36
+ ),
37
+ );
38
+ const rows = [
39
+ {
40
+ resource: "subscription",
41
+ path:
42
+ "/v1/subscriptions/" + request.payload.from_subscription + "?" + query,
43
+ },
44
+ {
45
+ resource: "price",
46
+ path: "/v1/prices/" + classified.material.targetPrice.id,
47
+ },
48
+ { resource: "customer", path: "/v1/customers/" + customer.id },
49
+ ...original.originalBundle.couponReads.map((row) => {
50
+ if (typeof row.couponId !== "string") stop();
51
+ return {
52
+ resource: "coupon",
53
+ path: "/v1/coupons/" + encodeURIComponent(row.couponId),
54
+ };
55
+ }),
56
+ ];
57
+ const readPlan = Object.freeze(
58
+ rows.map((row, index) =>
59
+ Object.freeze({
60
+ ...row,
61
+ ordinal: index + 1,
62
+ method: "GET",
63
+ body: undefined,
64
+ options: Object.freeze({
65
+ apiVersion: request.apiVersion,
66
+ maxNetworkRetries: 0,
67
+ }),
68
+ }),
69
+ ),
70
+ );
71
+ const delegate = captureInitialStockRawDelegate(token);
72
+ const send = lineage.journal.createC10Send(lineage.reservation);
73
+ let spent = false;
74
+ const slot = Object.freeze({
75
+ takeOnce(...args: unknown[]) {
76
+ if (spent) return null;
77
+ spent = true;
78
+ if (args.length !== 1 || args[0] !== owner) return null;
79
+ owner.check();
80
+ return Object.freeze({
81
+ rawAttachRequest: original.attachRequest,
82
+ originalBundle: original.originalBundle,
83
+ });
84
+ },
85
+ });
86
+ const sink = Object.freeze({
87
+ send(record: Parameters<typeof send>[0], ack: Parameters<typeof send>[1]) {
88
+ return owned(() =>
89
+ send(record, (value) => {
90
+ owner.check();
91
+ ack(value);
92
+ owner.check();
93
+ }),
94
+ );
95
+ },
96
+ });
97
+ owner.check();
98
+ return Object.freeze({
99
+ request,
100
+ expected: classified.material.originalPrepared.expected,
101
+ operation: Object.freeze({
102
+ owner,
103
+ originAssociation: lineage.originAssociation,
104
+ slot,
105
+ readPlan,
106
+ delegate,
107
+ sink,
108
+ }),
109
+ });
110
+ }
111
+
112
+ /** One construction and origin per original winning call; failures cannot remint. */
113
+ export function operationForInitialLineage(token: object) {
114
+ if (arguments.length !== 1) stop();
115
+ const owner = ownerForInitialLineage(token);
116
+ owner.check();
117
+ const owned = ownedAwaitForInitialLineage(token);
118
+ let pending = operations.get(token);
119
+ if (!pending) {
120
+ pending = owned(async () => {
121
+ try {
122
+ return await construct(token);
123
+ } catch (error) {
124
+ owner.retire();
125
+ throw error;
126
+ }
127
+ });
128
+ operations.set(token, pending);
129
+ }
130
+ const captured = pending;
131
+ return owned(() => captured);
132
+ }
133
+
134
+ /** Persist the fully captured C3 DATA before receipt3 or a returned ACK. */
135
+ export async function retainInitialReceiptForLineage(
136
+ token: object,
137
+ receipt: unknown,
138
+ ) {
139
+ if (arguments.length !== 2) stop();
140
+ const owner = ownerForInitialLineage(token);
141
+ owner.check();
142
+ const lineage = readInitialLineage(token);
143
+ const owned = ownedAwaitForInitialLineage(token);
144
+ const frame = await owned(() => operationForInitialLineage(token));
145
+ const captured = captureAttachReceipt({
146
+ event: "receipt",
147
+ stage: "attach",
148
+ request: frame.request,
149
+ receipt,
150
+ });
151
+ owner.check();
152
+ const receiptNode = field(captured, "receipt");
153
+ const binding = scalar(field(receiptNode, "binding"));
154
+ if (typeof binding !== "string") stop();
155
+ const receiptJSON = JSON.stringify(materialize(receiptNode));
156
+ const retained = await owned(() =>
157
+ lineage.journal.retainProviderAcknowledgement({
158
+ attemptId: lineage.reservation.attemptId,
159
+ expectedSequence: 2,
160
+ receiptJSON,
161
+ }),
162
+ );
163
+ owner.check();
164
+ if (
165
+ retained.status !== "retained" ||
166
+ retained.schemaVersion !== 1 ||
167
+ retained.stage !== "attach" ||
168
+ retained.operationId !== lineage.reservation.operationId ||
169
+ retained.attemptId !== lineage.reservation.attemptId ||
170
+ retained.sourcePayloadId !== lineage.reservation.payloadId ||
171
+ retained.receiptBinding !== binding
172
+ )
173
+ stop();
174
+ return retained;
175
+ }
@@ -0,0 +1,240 @@
1
+ import assert from "node:assert/strict";
2
+ import { afterEach, beforeEach, expect, it, vi } from "vitest";
3
+ import { initialOperations } from "../test-fixtures/producerInitialOperation.js";
4
+ import { declaredInputs } from "../test-fixtures/attachEntries.js";
5
+ import { INITIAL_NS } from "../test-fixtures/producerInitialDeclarations.js";
6
+ import { captureInitialInvocationCore } from "./invocationProducer.js";
7
+
8
+ const legacy = vi.hoisted(() => ({ touched: 0 }));
9
+ vi.mock("../originalOwner.js", () => ({
10
+ OWNER: Object.freeze({
11
+ get basis() {
12
+ legacy.touched++;
13
+ throw Error("LEGACY_OWNER_POISON");
14
+ },
15
+ check() {
16
+ legacy.touched++;
17
+ throw Error("LEGACY_OWNER_POISON");
18
+ },
19
+ sample() {
20
+ legacy.touched++;
21
+ throw Error("LEGACY_OWNER_POISON");
22
+ },
23
+ subscribe() {
24
+ legacy.touched++;
25
+ throw Error("LEGACY_OWNER_POISON");
26
+ },
27
+ retire() {
28
+ legacy.touched++;
29
+ throw Error("LEGACY_OWNER_POISON");
30
+ },
31
+ }),
32
+ }));
33
+ function declaration() {
34
+ const source = declaredInputs("INITIAL-ACK").original;
35
+ return {
36
+ source,
37
+ workEndWallMs: (source.attachRequest.firstDispatchedAt + 4) * 1000,
38
+ endWallMs: (source.attachRequest.firstDispatchedAt + 5) * 1000,
39
+ };
40
+ }
41
+ function responses(options: ReturnType<typeof declaration>) {
42
+ const b = options.source.originalBundle;
43
+ const expected = options.source.attachRequest.preparation.expected;
44
+ const rows: [string, unknown][] = [
45
+ ["/v1/subscriptions/" + expected.subscriptionId, b.wireSubscription],
46
+ ["/v1/prices/" + expected.targetPriceId, b.wireTargetPrice],
47
+ ["/v1/customers/" + b.wireBillingCustomer.id, b.wireBillingCustomer],
48
+ ];
49
+ for (const row of b.couponReads) {
50
+ assert(typeof row.couponId === "string");
51
+ rows.push([
52
+ "/v1/coupons/" + encodeURIComponent(row.couponId),
53
+ row.wireCoupon,
54
+ ]);
55
+ }
56
+ return new Map(rows);
57
+ }
58
+ beforeEach(() => {
59
+ legacy.touched = 0;
60
+ vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] });
61
+ vi.setSystemTime(
62
+ (declaration().source.attachRequest.firstDispatchedAt + 1) * 1000,
63
+ );
64
+ vi.spyOn(process.hrtime, "bigint").mockReturnValue(INITIAL_NS);
65
+ });
66
+ afterEach(() => {
67
+ vi.useRealTimers();
68
+ vi.unstubAllGlobals();
69
+ vi.restoreAllMocks();
70
+ });
71
+
72
+ it("acquires complete raw Coupon material through its exact maintained SDK and bounded plan", async () => {
73
+ const options = declaration();
74
+ const bodies = responses(options);
75
+ await initialOperations(
76
+ async ({ fresh, journal, sdk }) => {
77
+ const calls: string[] = [];
78
+ vi.stubGlobal(
79
+ "fetch",
80
+ async (input: RequestInfo | URL, init?: RequestInit) => {
81
+ const url = new URL(String(input));
82
+ assert.equal(url.origin, "https://api.stripe.com");
83
+ assert.equal(init?.method, "GET");
84
+ assert.equal(init?.redirect, "error");
85
+ const headers = new Headers(init?.headers);
86
+ assert.equal(
87
+ headers.get("authorization"),
88
+ "Bearer sk_test_invalid_owner_core",
89
+ );
90
+ assert.equal(headers.get("stripe-version"), sdk.stripeApiVersion);
91
+ assert(bodies.has(url.pathname));
92
+ calls.push(url.pathname);
93
+ return new Response(JSON.stringify(bodies.get(url.pathname)), {
94
+ status: 200,
95
+ headers: {
96
+ "content-type": "application/json",
97
+ "request-id": "req_initial_acquisition",
98
+ },
99
+ });
100
+ },
101
+ );
102
+ const core = await captureInitialInvocationCore(fresh.call, journal);
103
+ try {
104
+ expect(typeof core.acquire).toBe("function");
105
+ const result = await core.acquire();
106
+ expect(result.ok).toBe(true);
107
+ assert(result.ok);
108
+ expect(result.bundle).toEqual(options.source.originalBundle);
109
+ expect(result.observedAt).toBe(
110
+ options.source.attachRequest.firstDispatchedAt + 1,
111
+ );
112
+ expect(result.sourceFulfillmentEstablished).toBe(false);
113
+ expect(result.clockProvenanceEstablished).toBe(false);
114
+ expect(result.operatorReady).toBe(false);
115
+ expect(calls).toEqual([...bodies.keys()]);
116
+ expect(
117
+ (await core.material.fresh(result.bundle, result.observedAt)).status,
118
+ ).toBe("classified");
119
+ expect((await core.acquire()).ok).toBe(false);
120
+ expect(calls).toEqual([...bodies.keys()]);
121
+ expect(legacy.touched).toBe(0);
122
+ } finally {
123
+ core.owner.retire();
124
+ }
125
+ },
126
+ 1,
127
+ options,
128
+ );
129
+ });
130
+
131
+ it("refuses replacement acquisition inputs before clocks or HTTP", async () => {
132
+ const options = declaration();
133
+ await initialOperations(
134
+ async ({ fresh, journal }) => {
135
+ let foreign = 0,
136
+ requests = 0;
137
+ vi.stubGlobal("fetch", () => {
138
+ requests++;
139
+ throw Error("UNEXPECTED_HTTP");
140
+ });
141
+ const core = await captureInitialInvocationCore(fresh.call, journal);
142
+ try {
143
+ expect(typeof core.acquire).toBe("function");
144
+ const input = {
145
+ get expected() {
146
+ foreign++;
147
+ throw Error("FOREIGN_EXPECTED");
148
+ },
149
+ };
150
+ const reads = vi.mocked(process.hrtime.bigint).mock.calls.length;
151
+ await expect(
152
+ Reflect.apply(core.acquire, undefined, [input]),
153
+ ).rejects.toThrow("INITIAL_OPERATION_UNBOUND");
154
+ expect(vi.mocked(process.hrtime.bigint).mock.calls.length).toBe(reads);
155
+ expect(foreign).toBe(0);
156
+ expect(requests).toBe(0);
157
+ expect(legacy.touched).toBe(0);
158
+ } finally {
159
+ core.owner.retire();
160
+ }
161
+ },
162
+ 1,
163
+ options,
164
+ );
165
+ });
166
+
167
+ it("two pending acquisitions retain separate read lifetimes and cannot resume a retired Owner", async () => {
168
+ const options = declaration();
169
+ const bodies = responses(options);
170
+ let first = () => {},
171
+ both = () => {},
172
+ retired = () => {},
173
+ release = () => {};
174
+ const firstRead = new Promise<void>((resolve) => {
175
+ first = resolve;
176
+ });
177
+ const bothReads = new Promise<void>((resolve) => {
178
+ both = resolve;
179
+ });
180
+ const firstRetired = new Promise<void>((resolve) => {
181
+ retired = resolve;
182
+ });
183
+ const gate = new Promise<void>((resolve) => {
184
+ release = resolve;
185
+ });
186
+ const calls: string[] = [];
187
+ await initialOperations(
188
+ async ({ fresh, journal, index }) => {
189
+ vi.stubGlobal(
190
+ "fetch",
191
+ async (input: RequestInfo | URL, init?: RequestInit) => {
192
+ const url = new URL(String(input));
193
+ assert.equal(url.origin, "https://api.stripe.com");
194
+ assert.equal(init?.method, "GET");
195
+ assert(bodies.has(url.pathname));
196
+ calls.push(url.pathname);
197
+ if (calls.length === 1) first();
198
+ if (calls.length === 2) both();
199
+ await gate;
200
+ return new Response(JSON.stringify(bodies.get(url.pathname)), {
201
+ status: 200,
202
+ headers: {
203
+ "content-type": "application/json",
204
+ "request-id": "req_pending_acquisition",
205
+ },
206
+ });
207
+ },
208
+ );
209
+ const core = await captureInitialInvocationCore(fresh.call, journal);
210
+ try {
211
+ expect(typeof core.acquire).toBe("function");
212
+ if (index === 1) await firstRead;
213
+ const observed = core.acquire().then(
214
+ (value) => ({ ok: true, value }),
215
+ (error: unknown) => ({ ok: false, error }),
216
+ );
217
+ await bothReads;
218
+ if (index === 0) {
219
+ core.owner.retire();
220
+ expect((await observed).ok).toBe(false);
221
+ retired();
222
+ } else {
223
+ await firstRetired;
224
+ release();
225
+ const result = await observed;
226
+ assert(result.ok && "value" in result && result.value.ok);
227
+ expect(result.value.bundle).toEqual(options.source.originalBundle);
228
+ expect(calls.length).toBe(bodies.size + 1);
229
+ expect(core.owner.check().retired).toBe(false);
230
+ }
231
+ expect(legacy.touched).toBe(0);
232
+ } finally {
233
+ release();
234
+ core.owner.retire();
235
+ }
236
+ },
237
+ 2,
238
+ options,
239
+ );
240
+ });