@fantastic.dev/better-stripe 0.107.0 → 0.109.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 (59) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/renewalAttach/internal/observation/freshActor.d.ts +31 -0
  4. package/dist/client/billing/renewalAttach/internal/observation/freshActor.d.ts.map +1 -0
  5. package/dist/client/billing/renewalAttach/internal/observation/freshActor.js +112 -0
  6. package/dist/client/billing/renewalAttach/internal/observation/freshActor.js.map +1 -0
  7. package/dist/client/billing/renewalAttach/internal/observation/freshTransport.d.ts +17 -0
  8. package/dist/client/billing/renewalAttach/internal/observation/freshTransport.d.ts.map +1 -0
  9. package/dist/client/billing/renewalAttach/internal/observation/freshTransport.js +191 -0
  10. package/dist/client/billing/renewalAttach/internal/observation/freshTransport.js.map +1 -0
  11. package/dist/client/billing/renewalAttach/internal/observation/invocation.d.ts +29 -0
  12. package/dist/client/billing/renewalAttach/internal/observation/invocation.d.ts.map +1 -0
  13. package/dist/client/billing/renewalAttach/internal/observation/invocation.js +205 -0
  14. package/dist/client/billing/renewalAttach/internal/observation/invocation.js.map +1 -0
  15. package/dist/client/billing/renewalAttach/internal/observation/profile.d.ts +1 -0
  16. package/dist/client/billing/renewalAttach/internal/observation/profile.d.ts.map +1 -1
  17. package/dist/client/billing/renewalAttach/internal/observation/profile.js +5 -1
  18. package/dist/client/billing/renewalAttach/internal/observation/profile.js.map +1 -1
  19. package/dist/client/billing/renewalAttach/internal/observation/reader.d.ts +10 -0
  20. package/dist/client/billing/renewalAttach/internal/observation/reader.d.ts.map +1 -0
  21. package/dist/client/billing/renewalAttach/internal/observation/reader.js +30 -0
  22. package/dist/client/billing/renewalAttach/internal/observation/reader.js.map +1 -0
  23. package/dist/client/billing/renewalAttach/internal/observation/readerAuthorization.d.ts +44 -0
  24. package/dist/client/billing/renewalAttach/internal/observation/readerAuthorization.d.ts.map +1 -0
  25. package/dist/client/billing/renewalAttach/internal/observation/readerAuthorization.js +145 -0
  26. package/dist/client/billing/renewalAttach/internal/observation/readerAuthorization.js.map +1 -0
  27. package/dist/client/billing/renewalAttach/internal/operations/sourceOperations.d.ts +9 -0
  28. package/dist/client/billing/renewalAttach/internal/operations/sourceOperations.d.ts.map +1 -1
  29. package/dist/client/billing/renewalAttach/internal/operations/sourceOperations.js +2 -0
  30. package/dist/client/billing/renewalAttach/internal/operations/sourceOperations.js.map +1 -1
  31. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.d.ts +2 -0
  32. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.d.ts.map +1 -1
  33. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.js +9 -0
  34. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.js.map +1 -1
  35. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +32 -32
  36. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +16 -16
  37. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  38. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  39. package/dist/component/financialObservations/settlementHelpers.d.ts +3 -3
  40. package/dist/component/usageCredits/accounting.fixtures.d.ts +16 -16
  41. package/docs/renewal-context-reads.md +107 -0
  42. package/package.json +1 -1
  43. package/src/client/billing/renewalAttach/internal/observation/freshActor.integration.test.ts +360 -0
  44. package/src/client/billing/renewalAttach/internal/observation/freshActor.ts +175 -0
  45. package/src/client/billing/renewalAttach/internal/observation/freshActorControls.integration.test.ts +442 -0
  46. package/src/client/billing/renewalAttach/internal/observation/freshTransport.ts +252 -0
  47. package/src/client/billing/renewalAttach/internal/observation/invocation.ts +299 -0
  48. package/src/client/billing/renewalAttach/internal/observation/profile.ts +9 -1
  49. package/src/client/billing/renewalAttach/internal/observation/reader.integration.test.ts +93 -0
  50. package/src/client/billing/renewalAttach/internal/observation/reader.ts +35 -0
  51. package/src/client/billing/renewalAttach/internal/observation/readerAuthorization.ts +179 -0
  52. package/src/client/billing/renewalAttach/internal/observation/readerControls.integration.test.ts +553 -0
  53. package/src/client/billing/renewalAttach/internal/operations/sourceOperations.ts +11 -0
  54. package/src/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.ts +12 -0
  55. package/src/client/billing/renewalAttach/internal/test-fixtures/freshObservation.ts +94 -0
  56. package/src/client/billing/renewalAttach/internal/test-fixtures/historySnapshot.ts +5 -1
  57. package/src/client/billing/renewalAttach/internal/test-fixtures/observationReader.ts +101 -0
  58. package/src/client/billing/renewalAttach/internal/test-fixtures/producerConfigureAdmission.ts +41 -4
  59. package/src/client/billing/renewalAttach/internal/test-fixtures/producerInitialOperation.ts +5 -1
@@ -0,0 +1,299 @@
1
+ import { types } from "node:util";
2
+ import {
3
+ getFunctionAddress,
4
+ type GenericActionCtx,
5
+ type GenericDataModel,
6
+ } from "convex/server";
7
+ import { COMPILED_OBSERVATION_HISTORY_ENTRIES } from "../operations/sourceOperations.js";
8
+ import {
9
+ readMaintainedRootComponent,
10
+ captureMaintainedJournalBinding,
11
+ readCheckedJournalActionRPC,
12
+ } from "../producer/classOwnedActionRoot.js";
13
+ import { closed, freeze } from "../c10/ownData.js";
14
+ import {
15
+ object,
16
+ matchConfigureDATA,
17
+ } from "../producer/configureJournalData.js";
18
+ import { captureRetainedObservationHistory } from "./history.js";
19
+ import {
20
+ readerNeed as need,
21
+ readerText as text,
22
+ readerStop,
23
+ captureReaderAuthorization,
24
+ createObservationReaderLifetime,
25
+ captureReaderQueryDATA,
26
+ } from "./readerAuthorization.js";
27
+
28
+ import type { ObservationHistorySourceEntry } from "./readerAuthorization.js";
29
+ type CapturedHistory = Readonly<{
30
+ history: Awaited<ReturnType<typeof captureRetainedObservationHistory>>;
31
+ authorization: ReturnType<typeof captureReaderAuthorization>;
32
+ }>;
33
+ export interface ObservationInvocationState {
34
+ readonly binding: object;
35
+ readonly historyEntry: ObservationHistorySourceEntry;
36
+ guard(): void;
37
+ check(): { wallMs: number; ns: bigint };
38
+ close(): void;
39
+ owned<T>(work: () => T | PromiseLike<T>, extra?: () => void): Promise<T>;
40
+ captureHistory(): Promise<CapturedHistory>;
41
+ authorizeUnchanged(): Promise<ReturnType<typeof captureReaderAuthorization>>;
42
+ readCaptured(): CapturedHistory;
43
+ }
44
+ const invocations = new WeakMap<object, ObservationInvocationState>();
45
+ /** Cleanup does not need a still-valid context and cannot mint or read authority. */
46
+ export function closeObservationInvocation(token: unknown): void {
47
+ if (token !== null && typeof token === "object")
48
+ invocations.get(token)?.close();
49
+ }
50
+ /** Actual private invocation identity only. DATA cannot register a grant. */
51
+ export function readObservationInvocation(
52
+ token: unknown,
53
+ ): ObservationInvocationState {
54
+ need(token !== null && typeof token === "object");
55
+ const state = invocations.get(token);
56
+ need(state);
57
+ state.guard();
58
+ return state;
59
+ }
60
+
61
+ /** One fresh lifetime and actual class/Action binding, shared by private wrappers. */
62
+ export async function captureObservationInvocation(
63
+ actualRoot: object,
64
+ raw: unknown,
65
+ ) {
66
+ need(arguments.length === 2);
67
+ if (COMPILED_OBSERVATION_HISTORY_ENTRIES.length === 0) readerStop();
68
+ const component = readMaintainedRootComponent(actualRoot);
69
+ const matches = COMPILED_OBSERVATION_HISTORY_ENTRIES.filter(
70
+ (e) => e.component === component,
71
+ );
72
+ need(matches.length === 1);
73
+ const entry = matches[0];
74
+ closed(entry, ["component", "componentScope", "authorizationQuery"]);
75
+ need(Object.isFrozen(entry));
76
+ need(!types.isProxy(raw));
77
+ const input = closed(raw, [
78
+ "actualActionCtx",
79
+ "operationId",
80
+ "parentOperationId",
81
+ ]);
82
+ const args = freeze({
83
+ componentScope: text(entry.componentScope),
84
+ operationId: text(input.operationId),
85
+ parentOperationId: text(input.parentOperationId),
86
+ });
87
+ need(args.operationId !== args.parentOperationId);
88
+ need(
89
+ input.actualActionCtx &&
90
+ typeof input.actualActionCtx === "object" &&
91
+ !types.isProxy(input.actualActionCtx),
92
+ );
93
+ const ctx = input.actualActionCtx as GenericActionCtx<GenericDataModel>;
94
+ const auth = ctx.auth,
95
+ getIdentity = auth?.getUserIdentity;
96
+ need(
97
+ auth &&
98
+ !types.isProxy(auth) &&
99
+ typeof getIdentity === "function" &&
100
+ !types.isProxy(getIdentity),
101
+ );
102
+ const captured = {
103
+ query: ctx.runQuery,
104
+ mutation: ctx.runMutation,
105
+ meta: ctx.meta,
106
+ metadata: ctx.meta?.getFunctionMetadata,
107
+ };
108
+ const q = component.renewalOperations.queries;
109
+ const references = () => {
110
+ const current = component.renewalOperations.queries;
111
+ return [
112
+ current.loadAuthorizedOperation,
113
+ current.readAttempt,
114
+ current.readStageEvent,
115
+ current.readProviderAcknowledgement,
116
+ ];
117
+ };
118
+ const refs = {
119
+ load: q.loadAuthorizedOperation,
120
+ attempt: q.readAttempt,
121
+ event: q.readStageEvent,
122
+ acknowledgement: q.readProviderAcknowledgement,
123
+ };
124
+ const addresses = references().map((ref) =>
125
+ JSON.stringify(getFunctionAddress(ref)),
126
+ );
127
+ const authAddress = JSON.stringify(
128
+ getFunctionAddress(entry.authorizationQuery),
129
+ );
130
+ const lifetime = createObservationReaderLifetime();
131
+ let binding: object | null = null;
132
+ let authorizedUntil: number | null = null;
133
+ function guard() {
134
+ if (authorizedUntil !== null)
135
+ need(lifetime.check().wallMs < authorizedUntil);
136
+ need(readMaintainedRootComponent(actualRoot) === component);
137
+ need(
138
+ COMPILED_OBSERVATION_HISTORY_ENTRIES.filter(
139
+ (e) => e.component === component,
140
+ ).length === 1 && COMPILED_OBSERVATION_HISTORY_ENTRIES.includes(entry),
141
+ );
142
+ need(
143
+ ctx.auth === auth &&
144
+ auth.getUserIdentity === getIdentity &&
145
+ ctx.runQuery === captured.query &&
146
+ ctx.runMutation === captured.mutation &&
147
+ ctx.meta === captured.meta &&
148
+ ctx.meta.getFunctionMetadata === captured.metadata,
149
+ );
150
+ need(
151
+ JSON.stringify(getFunctionAddress(entry.authorizationQuery)) ===
152
+ authAddress,
153
+ );
154
+ references().forEach((ref, index) =>
155
+ need(JSON.stringify(getFunctionAddress(ref)) === addresses[index]),
156
+ );
157
+ if (binding) {
158
+ const rpc = readCheckedJournalActionRPC(binding);
159
+ need(
160
+ rpc.receiver === ctx &&
161
+ rpc.component === component &&
162
+ rpc.operationId === args.operationId &&
163
+ rpc.runQuery === captured.query &&
164
+ rpc.runMutation === captured.mutation,
165
+ );
166
+ }
167
+ }
168
+ const owned = <T>(work: () => T | PromiseLike<T>) =>
169
+ lifetime.owned(work, guard);
170
+ try {
171
+ binding = await owned(() =>
172
+ captureMaintainedJournalBinding(actualRoot, {
173
+ actualActionCtx: ctx,
174
+ operationId: args.operationId,
175
+ }),
176
+ );
177
+ guard();
178
+ } catch (error) {
179
+ lifetime.close();
180
+ throw error;
181
+ }
182
+ async function authorize() {
183
+ const who = await owned(() => getIdentity.call(auth));
184
+ need(who && !types.isProxy(who));
185
+ const token = Object.getOwnPropertyDescriptor(who, "tokenIdentifier");
186
+ need(token && token.enumerable && "value" in token);
187
+ const tokenIdentifier = text(token.value, 2048);
188
+ const reply: unknown = await owned(() =>
189
+ captured.query.call(ctx, entry.authorizationQuery, args),
190
+ );
191
+ return captureReaderAuthorization(
192
+ reply,
193
+ args,
194
+ tokenIdentifier,
195
+ lifetime.check().wallMs,
196
+ );
197
+ }
198
+ async function stage(operationId: string) {
199
+ const operation: unknown = captureReaderQueryDATA(
200
+ await owned(() => captured.query.call(ctx, refs.load, { operationId })),
201
+ );
202
+ const load = object(operation),
203
+ active = object(load.activeAttempt);
204
+ const attemptId = text(active.attemptId);
205
+ const attempt: unknown = captureReaderQueryDATA(
206
+ await owned(() =>
207
+ captured.query.call(ctx, refs.attempt, { operationId, attemptId }),
208
+ ),
209
+ );
210
+ const manifest = closed(attempt, ["reservation", "events"]);
211
+ need(Array.isArray(manifest.events) && manifest.events.length <= 3);
212
+ const count = manifest.events.length;
213
+ const events = [];
214
+ for (let index = 0; index < count; index++) {
215
+ const sequence: 1 | 2 | 3 = index === 0 ? 1 : index === 1 ? 2 : 3;
216
+ events.push(
217
+ captureReaderQueryDATA(
218
+ await owned(() =>
219
+ captured.query.call(ctx, refs.event, {
220
+ operationId,
221
+ attemptId,
222
+ sequence,
223
+ }),
224
+ ),
225
+ ),
226
+ );
227
+ }
228
+ const acknowledgement: unknown = captureReaderQueryDATA(
229
+ await owned(() =>
230
+ captured.query.call(ctx, refs.acknowledgement, { operationId }),
231
+ ),
232
+ );
233
+ return { operation, attempt, events, acknowledgement };
234
+ }
235
+ let capturedHistory: CapturedHistory | null = null;
236
+ let used = false;
237
+ async function captureHistory(): Promise<CapturedHistory> {
238
+ need(!used);
239
+ used = true;
240
+ lifetime.check();
241
+ guard();
242
+ const authorization = await authorize();
243
+ authorizedUntil = authorization.expiresAtMs;
244
+ const parent = await stage(args.parentOperationId),
245
+ configure = await stage(args.operationId);
246
+ const history = await owned(() =>
247
+ captureRetainedObservationHistory({ parent, configure }),
248
+ );
249
+ const receipt = history.attachmentReceipt;
250
+ matchConfigureDATA(authorization.providerScope, {
251
+ mode: "platform",
252
+ stripeAccount: null,
253
+ livemode: receipt.livemode,
254
+ customerAccountId: receipt.customerAccountId,
255
+ subscriptionId: receipt.subscriptionId,
256
+ scheduleId: receipt.scheduleId,
257
+ });
258
+ capturedHistory = Object.freeze({ history, authorization });
259
+ return capturedHistory;
260
+ }
261
+ async function authorizeUnchanged() {
262
+ need(capturedHistory);
263
+ const final = await authorize();
264
+ matchConfigureDATA(final, capturedHistory.authorization);
265
+ need(lifetime.check().wallMs < capturedHistory.authorization.expiresAtMs);
266
+ guard();
267
+ return final;
268
+ }
269
+ need(binding);
270
+ const token = Object.freeze({});
271
+ invocations.set(
272
+ token,
273
+ Object.freeze({
274
+ binding,
275
+ historyEntry: entry,
276
+ guard() {
277
+ lifetime.check();
278
+ guard();
279
+ },
280
+ check: lifetime.check,
281
+ close: lifetime.close,
282
+ owned<T>(work: () => T | PromiseLike<T>, extra?: () => void) {
283
+ return lifetime.owned(work, () => {
284
+ guard();
285
+ extra?.();
286
+ });
287
+ },
288
+ captureHistory,
289
+ authorizeUnchanged,
290
+ readCaptured() {
291
+ lifetime.check();
292
+ guard();
293
+ need(capturedHistory);
294
+ return capturedHistory;
295
+ },
296
+ }),
297
+ );
298
+ return token;
299
+ }
@@ -123,7 +123,7 @@ function soleItem(subscription: unknown) {
123
123
  resourceID(own(item, "id"), "si");
124
124
  return item;
125
125
  }
126
- export function validateBaseRouting(
126
+ export function validateObservationIdentityRouting(
127
127
  record: ObservationRecord,
128
128
  reads: ObservationReads,
129
129
  ) {
@@ -171,6 +171,14 @@ export function validateBaseRouting(
171
171
  reference(sub.schedule, "sub_sched", "subscription_schedule", p) ===
172
172
  p.schedule,
173
173
  );
174
+ }
175
+ export function validateBaseRouting(
176
+ record: ObservationRecord,
177
+ reads: ObservationReads,
178
+ ) {
179
+ validateObservationIdentityRouting(record, reads);
180
+ const p = ids(record),
181
+ sub = object(reads.subscription);
174
182
  const item = soleItem(sub);
175
183
  need(own(item, "subscription") === p.subscription);
176
184
  // Do not constrain status, current price, old item ID/period, phases or material
@@ -0,0 +1,93 @@
1
+ import { expect, it, vi } from "vitest";
2
+ import {
3
+ configureAdmissionCase,
4
+ admissionControls,
5
+ } from "../test-fixtures/producerConfigureAdmission.js";
6
+ import {
7
+ prepareObservationReader,
8
+ observerIdentity,
9
+ authorizeObservation,
10
+ readerControls,
11
+ } from "../test-fixtures/observationReader.js";
12
+ import { captureAuthorizedObservationHistoryReader } from "./reader.js";
13
+ configureAdmissionCase(
14
+ "fresh authenticated query-only reader survives original write retirement and period boundary",
15
+ prepareObservationReader,
16
+ async (h, state) => {
17
+ const calls = h.calls.length,
18
+ selectors = admissionControls.selectors;
19
+ await h.inAnotherAction(async (ctx) => {
20
+ const reader = await captureAuthorizedObservationHistoryReader(h.sdk, {
21
+ actualActionCtx: ctx,
22
+ operationId: state.operationId,
23
+ parentOperationId: state.parentOperationId,
24
+ });
25
+ expect(Object.keys(reader)).toEqual(["read"]);
26
+ const output = await reader.read();
27
+ expect(output.status).toBe("authorized_observation_history_data");
28
+ expect(output.history.snapshot).toEqual(state.full);
29
+ expect(output.authorization.authorizationRevision).toBe(3);
30
+ expect(output.operationalAuthority).toBe(false);
31
+ expect(Object.isFrozen(output.history.record)).toBe(true);
32
+ await expect(reader.read()).rejects.toThrow();
33
+ });
34
+ expect(readerControls.authorizations).toBe(2);
35
+ expect(h.calls).toHaveLength(calls);
36
+ expect(admissionControls.selectors).toBe(selectors);
37
+ expect(admissionControls.legacy).toBe(0);
38
+ },
39
+ { identity: observerIdentity, hostQuery: authorizeObservation },
40
+ );
41
+ it("EMPTY observation history profile refuses before root/input/clock reflection", async () => {
42
+ admissionControls.history.splice(0);
43
+ let traps = 0;
44
+ const root = new Proxy(
45
+ {},
46
+ {
47
+ getPrototypeOf() {
48
+ traps++;
49
+ throw Error("TRAP");
50
+ },
51
+ },
52
+ );
53
+ const input = new Proxy(
54
+ {},
55
+ {
56
+ ownKeys() {
57
+ traps++;
58
+ throw Error("TRAP");
59
+ },
60
+ },
61
+ );
62
+ const wall = vi.spyOn(Date, "now"),
63
+ ns = vi.spyOn(process.hrtime, "bigint");
64
+ wall.mockClear();
65
+ ns.mockClear();
66
+ await expect(
67
+ captureAuthorizedObservationHistoryReader(root, input),
68
+ ).rejects.toThrow("OBSERVATION_HISTORY_READER_UNBOUND");
69
+ expect(traps).toBe(0);
70
+ expect(wall).not.toHaveBeenCalled();
71
+ expect(ns).not.toHaveBeenCalled();
72
+ });
73
+ configureAdmissionCase(
74
+ "reader consumes before concurrent calls and exposes only four fixed query routes",
75
+ prepareObservationReader,
76
+ async (h, state) => {
77
+ await h.inAnotherAction(async (ctx) => {
78
+ const queries = vi.spyOn(ctx, "runQuery"),
79
+ mutations = vi.spyOn(ctx, "runMutation");
80
+ const reader = await captureAuthorizedObservationHistoryReader(h.sdk, {
81
+ actualActionCtx: ctx,
82
+ operationId: state.operationId,
83
+ parentOperationId: state.parentOperationId,
84
+ });
85
+ const first = reader.read();
86
+ await expect(reader.read()).rejects.toThrow();
87
+ expect((await first).status).toBe("authorized_observation_history_data");
88
+ expect(mutations).not.toHaveBeenCalled();
89
+ expect(queries).toHaveBeenCalledTimes(14);
90
+ });
91
+ },
92
+ { identity: observerIdentity, hostQuery: authorizeObservation },
93
+ );
@@ -0,0 +1,35 @@
1
+ import { readerNeed as need } from "./readerAuthorization.js";
2
+ import { freeze } from "../c10/ownData.js";
3
+ import {
4
+ captureObservationInvocation,
5
+ readObservationInvocation,
6
+ closeObservationInvocation,
7
+ } from "./invocation.js";
8
+ /** Query-only wrapper. Returned DATA does not retain an open invocation. */
9
+ export async function captureAuthorizedObservationHistoryReader(
10
+ root: object,
11
+ raw: unknown,
12
+ ) {
13
+ need(arguments.length === 2);
14
+ const token = await captureObservationInvocation(root, raw);
15
+ let used = false;
16
+ return Object.freeze({
17
+ async read() {
18
+ need(arguments.length === 0 && !used);
19
+ used = true;
20
+ try {
21
+ const state = readObservationInvocation(token);
22
+ const captured = await state.captureHistory();
23
+ await state.authorizeUnchanged();
24
+ state.guard();
25
+ return freeze({
26
+ status: "authorized_observation_history_data" as const,
27
+ ...captured,
28
+ operationalAuthority: false as const,
29
+ });
30
+ } finally {
31
+ closeObservationInvocation(token);
32
+ }
33
+ },
34
+ });
35
+ }
@@ -0,0 +1,179 @@
1
+ import { closed, freeze } from "../c10/ownData.js";
2
+ import { rejectProxyJSON } from "../acquisition/rawWireSource.js";
3
+ import { renewalSnapshot } from "../../../renewalReplacementSnapshot.js";
4
+ import { matchConfigureDATA } from "../producer/configureJournalData.js";
5
+ import type { FunctionReference } from "convex/server";
6
+ import type { Component } from "../../../../helpers.js";
7
+ export const readerStop = (): never => {
8
+ throw Error("OBSERVATION_HISTORY_READER_UNBOUND");
9
+ };
10
+ export function readerNeed(value: unknown): asserts value {
11
+ if (!value) readerStop();
12
+ }
13
+ export function readerText(value: unknown, max = 255): string {
14
+ readerNeed(
15
+ typeof value === "string" && value.length > 0 && value.length <= max,
16
+ );
17
+ return value;
18
+ }
19
+ export type AuthorizationArgs = {
20
+ componentScope: string;
21
+ parentOperationId: string;
22
+ operationId: string;
23
+ };
24
+ export type ObservationHistorySourceEntry = Readonly<{
25
+ component: Component;
26
+ componentScope: string;
27
+ authorizationQuery: FunctionReference<
28
+ "query",
29
+ "public" | "internal",
30
+ AuthorizationArgs,
31
+ unknown
32
+ >;
33
+ }>;
34
+ /** Detached bounded own DATA before another query or await can observe it. */
35
+ export function captureReaderQueryDATA<T>(raw: T): T {
36
+ rejectProxyJSON(raw);
37
+ const copy = renewalSnapshot(raw);
38
+ readerNeed(new TextEncoder().encode(JSON.stringify(copy)).length <= 500000);
39
+ matchConfigureDATA(raw, copy);
40
+ return freeze(copy);
41
+ }
42
+ export function captureReaderAuthorization(
43
+ raw: unknown,
44
+ args: AuthorizationArgs,
45
+ tokenIdentifier: string,
46
+ now: number,
47
+ ) {
48
+ rejectProxyJSON(raw);
49
+ const copy = renewalSnapshot(raw);
50
+ readerNeed(new TextEncoder().encode(JSON.stringify(copy)).length <= 8192);
51
+ matchConfigureDATA(raw, copy);
52
+ const x = closed(copy, [
53
+ "tokenIdentifier",
54
+ "componentScope",
55
+ "parentOperationId",
56
+ "operationId",
57
+ "providerScope",
58
+ "authorizationId",
59
+ "authorizationRevision",
60
+ "expiresAtMs",
61
+ ]);
62
+ const p = closed(x.providerScope, [
63
+ "mode",
64
+ "stripeAccount",
65
+ "livemode",
66
+ "customerAccountId",
67
+ "subscriptionId",
68
+ "scheduleId",
69
+ ]);
70
+ readerNeed(
71
+ x.tokenIdentifier === tokenIdentifier &&
72
+ x.componentScope === args.componentScope &&
73
+ x.parentOperationId === args.parentOperationId &&
74
+ x.operationId === args.operationId,
75
+ );
76
+ readerNeed(
77
+ p.mode === "platform" &&
78
+ p.stripeAccount === null &&
79
+ typeof p.livemode === "boolean",
80
+ );
81
+ readerNeed(
82
+ typeof x.authorizationRevision === "number" &&
83
+ Number.isSafeInteger(x.authorizationRevision) &&
84
+ x.authorizationRevision > 0,
85
+ );
86
+ readerNeed(
87
+ typeof x.expiresAtMs === "number" &&
88
+ Number.isSafeInteger(x.expiresAtMs) &&
89
+ x.expiresAtMs > now,
90
+ );
91
+ return freeze({
92
+ ...args,
93
+ tokenIdentifier: readerText(tokenIdentifier, 2048),
94
+ providerScope: {
95
+ mode: "platform" as const,
96
+ stripeAccount: null,
97
+ livemode: p.livemode,
98
+ customerAccountId: readerText(p.customerAccountId),
99
+ subscriptionId: readerText(p.subscriptionId),
100
+ scheduleId: readerText(p.scheduleId),
101
+ },
102
+ authorizationId: readerText(x.authorizationId),
103
+ authorizationRevision: x.authorizationRevision,
104
+ expiresAtMs: x.expiresAtMs,
105
+ });
106
+ }
107
+
108
+ /** Fresh query-only budget, including capture and idle time. Never an old write Owner. */
109
+ export function createObservationReaderLifetime() {
110
+ let state: "running" | "closed" | "expired" = "running";
111
+ const initial = { wallMs: Date.now(), ns: process.hrtime.bigint() };
112
+ let last = initial;
113
+ const valid = (s: typeof initial) =>
114
+ Number.isSafeInteger(s.wallMs) &&
115
+ s.wallMs >= 0 &&
116
+ s.ns >= 0n &&
117
+ s.ns <= 18446744073709551615n;
118
+ readerNeed(valid(initial));
119
+ let rejectExpiry!: (error: Error) => void;
120
+ const expiry = new Promise<never>((_resolve, reject) => {
121
+ rejectExpiry = reject;
122
+ });
123
+ void expiry.catch(() => {});
124
+ function expire(): never {
125
+ state = "expired";
126
+ clearTimeout(timer);
127
+ const error = Error("OBSERVATION_HISTORY_READER_EXPIRED");
128
+ rejectExpiry(error);
129
+ throw error;
130
+ }
131
+ const timer = setTimeout(() => {
132
+ if (state === "running") {
133
+ state = "expired";
134
+ rejectExpiry(Error("OBSERVATION_HISTORY_READER_EXPIRED"));
135
+ }
136
+ }, 30000);
137
+ timer.unref?.();
138
+ function check() {
139
+ if (state === "expired") throw Error("OBSERVATION_HISTORY_READER_EXPIRED");
140
+ readerNeed(state === "running");
141
+ const sample = { wallMs: Date.now(), ns: process.hrtime.bigint() };
142
+ if (
143
+ !valid(sample) ||
144
+ sample.wallMs < last.wallMs ||
145
+ sample.ns < last.ns ||
146
+ sample.wallMs - initial.wallMs >= 30000 ||
147
+ sample.ns - initial.ns >= 30000000000n
148
+ )
149
+ expire();
150
+ last = sample;
151
+ return sample;
152
+ }
153
+ function close() {
154
+ if (state === "running") state = "closed";
155
+ clearTimeout(timer);
156
+ }
157
+ async function owned<T>(
158
+ work: () => T | PromiseLike<T>,
159
+ guard: () => void,
160
+ ): Promise<T> {
161
+ check();
162
+ guard();
163
+ try {
164
+ const pending = Promise.resolve().then(() => {
165
+ check();
166
+ guard();
167
+ return work();
168
+ });
169
+ const result = await Promise.race([pending, expiry]);
170
+ check();
171
+ guard();
172
+ return result;
173
+ } catch (error) {
174
+ close();
175
+ throw error;
176
+ }
177
+ }
178
+ return Object.freeze({ check, close, owned });
179
+ }