@fantastic.dev/better-stripe 0.97.0 → 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 (74) hide show
  1. package/CHANGELOG.md +12 -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/material/classifiers.d.ts +11 -0
  8. package/dist/client/billing/renewalAttach/internal/material/classifiers.d.ts.map +1 -1
  9. package/dist/client/billing/renewalAttach/internal/material/classifiers.js +57 -22
  10. package/dist/client/billing/renewalAttach/internal/material/classifiers.js.map +1 -1
  11. package/dist/client/billing/renewalAttach/internal/operations/fixedTransport.d.ts +54 -0
  12. package/dist/client/billing/renewalAttach/internal/operations/fixedTransport.d.ts.map +1 -1
  13. package/dist/client/billing/renewalAttach/internal/operations/fixedTransport.js +44 -37
  14. package/dist/client/billing/renewalAttach/internal/operations/fixedTransport.js.map +1 -1
  15. package/dist/client/billing/renewalAttach/internal/operations/initialActorData.d.ts +21 -0
  16. package/dist/client/billing/renewalAttach/internal/operations/initialActorData.d.ts.map +1 -0
  17. package/dist/client/billing/renewalAttach/internal/operations/initialActorData.js +36 -0
  18. package/dist/client/billing/renewalAttach/internal/operations/initialActorData.js.map +1 -0
  19. package/dist/client/billing/renewalAttach/internal/operations/initialAttach.d.ts +3 -0
  20. package/dist/client/billing/renewalAttach/internal/operations/initialAttach.d.ts.map +1 -1
  21. package/dist/client/billing/renewalAttach/internal/operations/initialAttach.js +71 -46
  22. package/dist/client/billing/renewalAttach/internal/operations/initialAttach.js.map +1 -1
  23. package/dist/client/billing/renewalAttach/internal/operations/ownedAwait.d.ts +1 -0
  24. package/dist/client/billing/renewalAttach/internal/operations/ownedAwait.d.ts.map +1 -1
  25. package/dist/client/billing/renewalAttach/internal/operations/ownedAwait.js +17 -5
  26. package/dist/client/billing/renewalAttach/internal/operations/ownedAwait.js.map +1 -1
  27. package/dist/client/billing/renewalAttach/internal/operations/transportCapture.d.ts +35 -0
  28. package/dist/client/billing/renewalAttach/internal/operations/transportCapture.d.ts.map +1 -0
  29. package/dist/client/billing/renewalAttach/internal/operations/transportCapture.js +46 -0
  30. package/dist/client/billing/renewalAttach/internal/operations/transportCapture.js.map +1 -0
  31. package/dist/client/billing/renewalAttach/internal/producer/invocationProducer.d.ts +8 -0
  32. package/dist/client/billing/renewalAttach/internal/producer/invocationProducer.d.ts.map +1 -1
  33. package/dist/client/billing/renewalAttach/internal/producer/invocationProducer.js +21 -0
  34. package/dist/client/billing/renewalAttach/internal/producer/invocationProducer.js.map +1 -1
  35. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.d.ts +1 -0
  36. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.d.ts.map +1 -1
  37. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.js +3 -0
  38. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.js.map +1 -1
  39. package/dist/client/billing/renewalAttach/internal/producer/operationFactory.d.ts +65 -0
  40. package/dist/client/billing/renewalAttach/internal/producer/operationFactory.d.ts.map +1 -0
  41. package/dist/client/billing/renewalAttach/internal/producer/operationFactory.js +161 -0
  42. package/dist/client/billing/renewalAttach/internal/producer/operationFactory.js.map +1 -0
  43. package/dist/client/billing/renewalAttach/internal/producer/stockDelegateFactory.d.ts +4 -0
  44. package/dist/client/billing/renewalAttach/internal/producer/stockDelegateFactory.d.ts.map +1 -1
  45. package/dist/client/billing/renewalAttach/internal/producer/stockDelegateFactory.js +24 -3
  46. package/dist/client/billing/renewalAttach/internal/producer/stockDelegateFactory.js.map +1 -1
  47. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +32 -32
  48. package/dist/client/connect/payoutSyncTestHelpers.d.ts +16 -16
  49. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  50. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  51. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  52. package/dist/component/earnings/triggers.d.ts +16 -16
  53. package/dist/component/payoutRelease/queries.d.ts +2 -2
  54. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  55. package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
  56. package/dist/component/usage/allowance.fixtures.d.ts +16 -16
  57. package/docs/renewal-context-reads.md +35 -4
  58. package/package.json +1 -1
  59. package/src/client/billing/renewalAttach/internal/acquisition/ownedAcquisition.ts +42 -0
  60. package/src/client/billing/renewalAttach/internal/material/classifiers.ts +64 -22
  61. package/src/client/billing/renewalAttach/internal/operations/fixedTransport.ts +55 -48
  62. package/src/client/billing/renewalAttach/internal/operations/initialActorData.ts +41 -0
  63. package/src/client/billing/renewalAttach/internal/operations/initialAttach.ts +91 -55
  64. package/src/client/billing/renewalAttach/internal/operations/ownedAwait.ts +23 -5
  65. package/src/client/billing/renewalAttach/internal/operations/transportCapture.ts +60 -0
  66. package/src/client/billing/renewalAttach/internal/producer/invocationProducer.ts +25 -0
  67. package/src/client/billing/renewalAttach/internal/producer/lineageAuthority.ts +3 -0
  68. package/src/client/billing/renewalAttach/internal/producer/operationFactory.ts +175 -0
  69. package/src/client/billing/renewalAttach/internal/producer/producerAcquisition.integration.test.ts +240 -0
  70. package/src/client/billing/renewalAttach/internal/producer/producerActor.integration.test.ts +526 -0
  71. package/src/client/billing/renewalAttach/internal/producer/producerMaterial.integration.test.ts +251 -0
  72. package/src/client/billing/renewalAttach/internal/producer/producerTransport.integration.test.ts +440 -0
  73. package/src/client/billing/renewalAttach/internal/producer/stockDelegateFactory.ts +29 -5
  74. package/src/client/billing/renewalAttach/internal/test-fixtures/producerInitialOperation.ts +100 -11
@@ -1,6 +1,6 @@
1
1
  import { admitInitialOutput } from "../recovery/material.js";
2
2
  import { types } from "node:util";
3
- import { OWNER } from "../originalOwner.js";
3
+ import { OWNER as LEGACY_OWNER } from "../originalOwner.js";
4
4
  import {
5
5
  prepareRenewalPriceReplacementV2 as c1,
6
6
  prepareRenewalScheduleAttachmentV2 as c2,
@@ -18,7 +18,7 @@ import {
18
18
  type FailureControl,
19
19
  } from "./types.js";
20
20
  import { equal } from "../../../renewalAggregate/shared.js";
21
- import { owned } from "./ownedAwait.js";
21
+ import { owned as legacyOwned, ownedForInitialLineage } from "./ownedAwait.js";
22
22
  import type { Diagnostics } from "./providerFailure.js";
23
23
  import { bindRawAcquisitionFromSource } from "../acquisition/ownedAcquisition.js";
24
24
  import { createAttachEventCompiler } from "../c10/attachEvents.js";
@@ -29,46 +29,19 @@ import {
29
29
  } from "./sourceOperations.js";
30
30
  import { createInitialOwnedTransportWithAttemptCapability as createPair } from "./fixedTransport.js";
31
31
 
32
+ import { sourceMethod, stop, need, seven, refuse } from "./initialActorData.js";
33
+ import { ownerForInitialLineage } from "../producer/ownerFactory.js";
34
+ import { readInitialLineage } from "../producer/lineageAuthority.js";
35
+ import {
36
+ operationForInitialLineage,
37
+ retainInitialReceiptForLineage,
38
+ } from "../producer/operationFactory.js";
39
+ import { createInitialTransportForLineage } from "./fixedTransport.js";
40
+ import { createInitialMaterialClassifiers } from "../material/classifiers.js";
41
+ import { acquisitionForInitialLineage } from "../acquisition/ownedAcquisition.js";
42
+ import { createInitialAttachEventCompiler } from "../c10/attachEvents.js";
32
43
  type Pair = ReturnType<typeof createPair>;
33
44
 
34
- function sourceMethod(object: unknown, name: string): SourceMethod {
35
- need(object !== null && typeof object === "object" && !types.isProxy(object));
36
- const d = Object.getOwnPropertyDescriptor(object, name);
37
- need(
38
- d &&
39
- d.enumerable &&
40
- "value" in d &&
41
- typeof d.value === "function" &&
42
- !types.isProxy(d.value),
43
- );
44
- return d.value as SourceMethod;
45
- }
46
- const stop = (): never => {
47
- throw Error("INITIAL_ACTOR_STOP");
48
- };
49
- function need(value: unknown): asserts value {
50
- if (!value) stop();
51
- }
52
- function seven(request: AttachRequest) {
53
- const { scope, apiVersion, method, path, payload, key, firstDispatchedAt } =
54
- request;
55
- return Object.freeze({
56
- scope,
57
- apiVersion,
58
- method,
59
- path,
60
- payload,
61
- key,
62
- firstDispatchedAt,
63
- });
64
- }
65
-
66
- const refuse = (reason: string) =>
67
- Object.freeze({
68
- status: "not_dispatched",
69
- reason,
70
- operationalAuthority: false,
71
- });
72
45
  /** Internal single-use actor. Empty class registry precedes every Source side effect. */
73
46
  export function captureInitialAttach() {
74
47
  need(arguments.length === 0);
@@ -76,6 +49,20 @@ export function captureInitialAttach() {
76
49
  }
77
50
  export function captureOwnedInitialAttachV2() {
78
51
  need(arguments.length === 0);
52
+ return initialKernel(null);
53
+ }
54
+ const actors = new WeakMap<object, ReturnType<typeof initialKernel>>();
55
+ export function captureInitialAttachForLineage(token: object) {
56
+ need(arguments.length === 1);
57
+ readInitialLineage(token);
58
+ let actor = actors.get(token);
59
+ if (!actor) {
60
+ actor = initialKernel(token);
61
+ actors.set(token, actor);
62
+ }
63
+ return actor;
64
+ }
65
+ function initialKernel(token: object | null) {
79
66
  let consumed = false;
80
67
  return Object.freeze({
81
68
  async invoke() {
@@ -84,6 +71,31 @@ export function captureOwnedInitialAttachV2() {
84
71
  consumed = true;
85
72
  need(!types.isProxy(ENTRIES) && Array.isArray(ENTRIES));
86
73
  if (ENTRIES.length === 0) return refuse("no_qualified_native_class");
74
+
75
+ const OWNER =
76
+ token === null ? LEGACY_OWNER : ownerForInitialLineage(token);
77
+ const owned =
78
+ token === null ? legacyOwned : ownedForInitialLineage(token);
79
+ const classifyRetained =
80
+ token === null
81
+ ? classifyOwnedRetainedInitialAttachment
82
+ : (_raw: unknown) =>
83
+ createInitialMaterialClassifiers(token).retained();
84
+ const classifyFresh =
85
+ token === null
86
+ ? classifyOwnedInitialAttachment
87
+ : (raw: unknown) => {
88
+ const input = closed(raw, [
89
+ "attachRequest",
90
+ "originalBundle",
91
+ "currentBundle",
92
+ "observedAt",
93
+ ]);
94
+ return createInitialMaterialClassifiers(token).fresh(
95
+ input.currentBundle,
96
+ input.observedAt,
97
+ );
98
+ };
87
99
  let pair: Pair | null = null,
88
100
  failureControl: FailureControl | null = null,
89
101
  postEligible = false;
@@ -105,7 +117,10 @@ export function captureOwnedInitialAttachV2() {
105
117
  };
106
118
  try {
107
119
  OWNER.check();
108
- const live = loadFixedInitialOperation();
120
+ const live =
121
+ token === null
122
+ ? loadFixedInitialOperation()
123
+ : (await owned(() => operationForInitialLineage(token))).operation;
109
124
  OWNER.check();
110
125
  if (live === null) return refuse("original_slot_unbound");
111
126
  const op = closed(live, [
@@ -121,7 +136,10 @@ export function captureOwnedInitialAttachV2() {
121
136
  op.originAssociation !== null &&
122
137
  typeof op.originAssociation === "object" &&
123
138
  !types.isProxy(op.originAssociation) &&
124
- op.originAssociation === ORIGINAL_ORIGIN_ASSOCIATION,
139
+ op.originAssociation ===
140
+ (token === null
141
+ ? ORIGINAL_ORIGIN_ASSOCIATION
142
+ : readInitialLineage(token).originAssociation),
125
143
  );
126
144
  const takeOnce = sourceMethod(op.slot, "takeOnce");
127
145
  OWNER.check();
@@ -146,9 +164,7 @@ export function captureOwnedInitialAttachV2() {
146
164
  }),
147
165
  );
148
166
  OWNER.check();
149
- const retained = await owned(() =>
150
- classifyOwnedRetainedInitialAttachment(original),
151
- );
167
+ const retained = await owned(() => classifyRetained(original));
152
168
  OWNER.check();
153
169
  if (retained.status !== "classified")
154
170
  return refuse("retained_material_unsupported");
@@ -169,7 +185,10 @@ export function captureOwnedInitialAttachV2() {
169
185
  if (matches.length !== 1) return refuse("retained_class_not_unique");
170
186
  const entry = matches[0];
171
187
  OWNER.check();
172
- pair = createPair();
188
+ pair =
189
+ token === null
190
+ ? createPair()
191
+ : await owned(() => createInitialTransportForLineage(token));
173
192
  OWNER.check();
174
193
  need(
175
194
  pair.capability.assertSourceOperationBinding(
@@ -342,10 +361,20 @@ export function captureOwnedInitialAttachV2() {
342
361
  })();
343
362
  OWNER.check();
344
363
  failureControl = control;
345
- const reader = bindRawAcquisitionFromSource(
346
- OWNER,
347
- activePair.transport.readTransport,
348
- );
364
+ const reader =
365
+ token === null
366
+ ? bindRawAcquisitionFromSource(
367
+ OWNER,
368
+ activePair.transport.readTransport,
369
+ )
370
+ : {
371
+ async acquire(_expected: unknown) {
372
+ const reader = await owned(() =>
373
+ acquisitionForInitialLineage(token),
374
+ );
375
+ return reader.acquire();
376
+ },
377
+ };
349
378
  OWNER.check();
350
379
  let acquiredOnce = false;
351
380
  const acquire = async () => {
@@ -370,7 +399,7 @@ export function captureOwnedInitialAttachV2() {
370
399
  if (!acquired.ok) return refuse("current_read_unsupported");
371
400
 
372
401
  const fresh = await owned(() =>
373
- classifyOwnedInitialAttachment({
402
+ classifyFresh({
374
403
  attachRequest: raw,
375
404
  originalBundle: original.originalBundle,
376
405
  currentBundle: acquired.bundle,
@@ -441,10 +470,13 @@ export function captureOwnedInitialAttachV2() {
441
470
  OWNER.check();
442
471
  return Reflect.apply(send, op.sink, [record, ack]);
443
472
  };
444
- const compiler = createAttachEventCompiler(raw, {
445
- send: sourceSend,
446
- timeoutMs: 5000,
447
- });
473
+ const compiler =
474
+ token === null
475
+ ? createAttachEventCompiler(raw, {
476
+ send: sourceSend,
477
+ timeoutMs: 5000,
478
+ })
479
+ : createInitialAttachEventCompiler(token);
448
480
  OWNER.check();
449
481
  await owned(() =>
450
482
  compiler.dispatch({ event: "dispatch", stage: "attach", request }),
@@ -489,6 +521,10 @@ export function captureOwnedInitialAttachV2() {
489
521
  }),
490
522
  );
491
523
  OWNER.check();
524
+ if (token !== null) {
525
+ await owned(() => retainInitialReceiptForLineage(token, receipt));
526
+ OWNER.check();
527
+ }
492
528
  await owned(() =>
493
529
  compiler.receipt({
494
530
  event: "receipt",
@@ -1,4 +1,5 @@
1
1
  import { OWNER } from "../originalOwner.js";
2
+ import { ownerForInitialLineage } from "../producer/ownerFactory.js";
2
3
 
3
4
  export interface FailureForwarder {
4
5
  forward(error: unknown): object | null;
@@ -8,7 +9,24 @@ export function owned<T>(
8
9
  work: () => T | PromiseLike<T>,
9
10
  failureControl: FailureForwarder | null = null,
10
11
  ): Promise<T> {
11
- OWNER.check();
12
+ return runOwned(OWNER, work, failureControl);
13
+ }
14
+ export function ownedForInitialLineage(token: object) {
15
+ if (arguments.length !== 1) throw Error("INITIAL_ACTOR_STOP");
16
+ const owner = ownerForInitialLineage(token);
17
+ return function owned<T>(
18
+ work: () => T | PromiseLike<T>,
19
+ control: FailureForwarder | null = null,
20
+ ): Promise<T> {
21
+ return runOwned(owner, work, control);
22
+ };
23
+ }
24
+ function runOwned<T>(
25
+ owner: Pick<typeof OWNER, "check" | "subscribe">,
26
+ work: () => T | PromiseLike<T>,
27
+ failureControl: FailureForwarder | null,
28
+ ): Promise<T> {
29
+ owner.check();
12
30
  return new Promise((resolve, reject) => {
13
31
  let done = false,
14
32
  remove: (() => void) | null = null;
@@ -20,14 +38,14 @@ export function owned<T>(
20
38
  else reject(value);
21
39
  };
22
40
  const retire = () => finish(false, Error("INITIAL_ACTOR_STOP"));
23
- remove = OWNER.subscribe(retire);
41
+ remove = owner.subscribe(retire);
24
42
  if (done) {
25
43
  remove();
26
44
  return;
27
45
  }
28
46
  let pending: T | PromiseLike<T>;
29
47
  try {
30
- OWNER.check();
48
+ owner.check();
31
49
  pending = work();
32
50
  } catch {
33
51
  finish(false, Error("INITIAL_ACTOR_STOP"));
@@ -37,7 +55,7 @@ export function owned<T>(
37
55
  (value) => {
38
56
  if (done) return;
39
57
  try {
40
- OWNER.check();
58
+ owner.check();
41
59
  finish(true, value);
42
60
  } catch {
43
61
  retire();
@@ -46,7 +64,7 @@ export function owned<T>(
46
64
  (error: unknown) => {
47
65
  if (done) return;
48
66
  try {
49
- OWNER.check();
67
+ owner.check();
50
68
  const forwarded = failureControl
51
69
  ? failureControl.forward(error)
52
70
  : null;
@@ -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
+ }
@@ -4,6 +4,13 @@ import { ownedAwaitForInitialLineage } from "./ownedAwaitFactory.js";
4
4
  import { stockDelegateForInitialLineage } from "./stockDelegateFactory.js";
5
5
  import type { createClassActionOperationJournal } from "../operationJournal.js";
6
6
  import { createInitialAttachEventCompiler } from "../c10/attachEvents.js";
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";
7
14
 
8
15
  export type InitialInvocationCore = Readonly<{
9
16
  owner: InitialOwner;
@@ -11,6 +18,10 @@ export type InitialInvocationCore = Readonly<{
11
18
  delegate: ReturnType<typeof stockDelegateForInitialLineage>;
12
19
  owned<T>(work: () => T | PromiseLike<T>): Promise<T>;
13
20
  attachEvents(): ReturnType<typeof createInitialAttachEventCompiler>;
21
+ material: ReturnType<typeof createInitialMaterialClassifiers>;
22
+ transport(): ReturnType<typeof createInitialTransportForLineage>;
23
+ acquire(): Promise<RawAcquisitionResult>;
24
+ initialAttach(): ReturnType<typeof captureInitialAttachForLineage>;
14
25
  operationalAuthority: false;
15
26
  }>;
16
27
 
@@ -59,6 +70,20 @@ export async function captureInitialInvocationCore(
59
70
  if (arguments.length !== 0) throw Error("INITIAL_CHANNEL_UNBOUND");
60
71
  return createInitialAttachEventCompiler(token);
61
72
  },
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
+ },
62
87
  operationalAuthority: false,
63
88
  });
64
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
+ }