@fantastic.dev/better-stripe 0.92.0 → 0.94.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 (96) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/renewalAttach/internal/operationJournal.d.ts +41 -0
  4. package/dist/client/billing/renewalAttach/internal/operationJournal.d.ts.map +1 -0
  5. package/dist/client/billing/renewalAttach/internal/operationJournal.js +378 -0
  6. package/dist/client/billing/renewalAttach/internal/operationJournal.js.map +1 -0
  7. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.d.ts +44 -0
  8. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.d.ts.map +1 -0
  9. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.js +251 -0
  10. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.js.map +1 -0
  11. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +562 -0
  12. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  13. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +281 -0
  14. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  15. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +562 -0
  16. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  17. package/dist/client/connect/payoutSyncTestHelpers.d.ts +281 -0
  18. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  19. package/dist/client/index.d.ts +3 -2
  20. package/dist/client/index.d.ts.map +1 -1
  21. package/dist/client/index.js +16 -3
  22. package/dist/client/index.js.map +1 -1
  23. package/dist/component/_generated/api.d.ts +6 -0
  24. package/dist/component/_generated/api.d.ts.map +1 -1
  25. package/dist/component/_generated/api.js.map +1 -1
  26. package/dist/component/_generated/component.d.ts +406 -0
  27. package/dist/component/_generated/component.d.ts.map +1 -1
  28. package/dist/component/balanceFunding/mutations.d.ts +27 -27
  29. package/dist/component/balanceFunding/queries.d.ts +1 -1
  30. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  31. package/dist/component/earnings/triggers.d.ts +294 -0
  32. package/dist/component/earnings/triggers.d.ts.map +1 -1
  33. package/dist/component/financialObservations/settlementHelpers.d.ts +3 -3
  34. package/dist/component/renewalOperations/helpers.d.ts +236 -0
  35. package/dist/component/renewalOperations/helpers.d.ts.map +1 -0
  36. package/dist/component/renewalOperations/helpers.js +457 -0
  37. package/dist/component/renewalOperations/helpers.js.map +1 -0
  38. package/dist/component/renewalOperations/mutations.d.ts +252 -0
  39. package/dist/component/renewalOperations/mutations.d.ts.map +1 -0
  40. package/dist/component/renewalOperations/mutations.js +340 -0
  41. package/dist/component/renewalOperations/mutations.js.map +1 -0
  42. package/dist/component/renewalOperations/queries.d.ts +163 -0
  43. package/dist/component/renewalOperations/queries.d.ts.map +1 -0
  44. package/dist/component/renewalOperations/queries.js +167 -0
  45. package/dist/component/renewalOperations/queries.js.map +1 -0
  46. package/dist/component/renewalOperations/schema.d.ts +1988 -0
  47. package/dist/component/renewalOperations/schema.d.ts.map +1 -0
  48. package/dist/component/renewalOperations/schema.js +227 -0
  49. package/dist/component/renewalOperations/schema.js.map +1 -0
  50. package/dist/component/schema.d.ts +281 -0
  51. package/dist/component/schema.js +5 -0
  52. package/dist/component/schema.js.map +1 -1
  53. package/dist/component/usage/allowance.fixtures.d.ts +281 -0
  54. package/dist/component/usage/allowance.fixtures.d.ts.map +1 -1
  55. package/dist/component/usageCredits/accounting.fixtures.d.ts +297 -16
  56. package/dist/component/usageCredits/accounting.fixtures.d.ts.map +1 -1
  57. package/dist/shared/renewalOperationJournal.d.ts +43 -0
  58. package/dist/shared/renewalOperationJournal.d.ts.map +1 -0
  59. package/dist/shared/renewalOperationJournal.js +294 -0
  60. package/dist/shared/renewalOperationJournal.js.map +1 -0
  61. package/docs/renewal-context-reads.md +180 -0
  62. package/package.json +1 -1
  63. package/src/client/billing/renewalAttach/internal/operationJournal.acknowledgement.integration.test.ts +500 -0
  64. package/src/client/billing/renewalAttach/internal/operationJournal.c10.integration.test.ts +560 -0
  65. package/src/client/billing/renewalAttach/internal/operationJournal.controls.integration.test.ts +356 -0
  66. package/src/client/billing/renewalAttach/internal/operationJournal.integration.test.ts +560 -0
  67. package/src/client/billing/renewalAttach/internal/operationJournal.methods.integration.test.ts +534 -0
  68. package/src/client/billing/renewalAttach/internal/operationJournal.ts +561 -0
  69. package/src/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.ts +334 -0
  70. package/src/client/billing/renewalAttach/internal/producer/producerGuards.integration.test.ts +323 -0
  71. package/src/client/billing/renewalAttach/internal/producer/producerInitial.integration.test.ts +301 -0
  72. package/src/client/billing/renewalAttach/internal/producer/producerIsolation.integration.test.ts +531 -0
  73. package/src/client/index.ts +24 -3
  74. package/src/component/_generated/api.ts +6 -0
  75. package/src/component/_generated/component.ts +450 -0
  76. package/src/component/renewalOperations/acknowledgement.fixtures.ts +552 -0
  77. package/src/component/renewalOperations/acknowledgement.test.ts +573 -0
  78. package/src/component/renewalOperations/acknowledgementReads.test.ts +442 -0
  79. package/src/component/renewalOperations/acknowledgementV2.test.ts +493 -0
  80. package/src/component/renewalOperations/acknowledgementV2Publication.test.ts +373 -0
  81. package/src/component/renewalOperations/basisBinding.test.ts +567 -0
  82. package/src/component/renewalOperations/basisLifecycle.test.ts +569 -0
  83. package/src/component/renewalOperations/boundHistory.test.ts +474 -0
  84. package/src/component/renewalOperations/helpers.ts +592 -0
  85. package/src/component/renewalOperations/historyReads.test.ts +595 -0
  86. package/src/component/renewalOperations/initialBasis.test.ts +578 -0
  87. package/src/component/renewalOperations/journal.test.ts +567 -0
  88. package/src/component/renewalOperations/mutations.ts +456 -0
  89. package/src/component/renewalOperations/payload.test.ts +589 -0
  90. package/src/component/renewalOperations/payloadEncoding.test.ts +592 -0
  91. package/src/component/renewalOperations/queries.ts +204 -0
  92. package/src/component/renewalOperations/schema.ts +268 -0
  93. package/src/component/renewalOperations/timingPolicy.fixtures.ts +193 -0
  94. package/src/component/renewalOperations/timingPolicy.test.ts +523 -0
  95. package/src/component/schema.ts +11 -0
  96. package/src/shared/renewalOperationJournal.ts +333 -0
@@ -0,0 +1,589 @@
1
+ import { convexTest } from "convex-test";
2
+ import { makeFunctionReference } from "convex/server";
3
+ import { getConvexSize, getDocumentSize } from "convex/values";
4
+ import { afterEach, expect, it, vi } from "vitest";
5
+ import { modules, schema } from "../../test.js";
6
+ import { renewalSnapshot } from "../../client/billing/renewalReplacementSnapshot.js";
7
+ import {
8
+ eventDigest,
9
+ materialize,
10
+ objectNode,
11
+ scalarNode,
12
+ } from "../../client/billing/renewalAttach/internal/c10/eventCodec.js";
13
+
14
+ const VALUE_LIMIT = 1048576;
15
+ const ACTOR_JSON_LIMIT = 500000;
16
+ const BASIS_PADDING = 380000;
17
+ const EVENT_PADDING = 300000;
18
+ // These are immutable storage DATA. The padded basis is NOT a qualified Owner.
19
+ const record = Object.freeze({
20
+ schemaVersion: 1,
21
+ requestBinding: "journal-payload-consistency-A",
22
+ authorization: Object.freeze({
23
+ scope: "merchant-payload",
24
+ id: "consent-payload",
25
+ revision: 1,
26
+ }),
27
+ logicalOperationId: "payload-A",
28
+ stage: "attach",
29
+ account: Object.freeze({
30
+ mode: "platform",
31
+ stripeAccount: null,
32
+ livemode: false,
33
+ }),
34
+ apiVersion: "2026-09-30.endive",
35
+ profile: "unqualified-storage-DATA-only",
36
+ subscriptionId: "sub_payload",
37
+ customerId: "cus_payload",
38
+ itemId: "si_payload",
39
+ currentPriceId: "price_old",
40
+ targetPriceId: "price_new",
41
+ targetProductId: "prod_new",
42
+ period: Object.freeze({ start: 2000000000, end: 2000003600 }),
43
+ dispatch: Object.freeze({
44
+ scope: "platform",
45
+ apiVersion: "2026-09-30.endive",
46
+ method: "POST",
47
+ path: "/v1/subscription_schedules",
48
+ payload: Object.freeze({ from_subscription: "sub_payload" }),
49
+ key: "retained-payload-key",
50
+ firstDispatchedAt: 2000000000,
51
+ }),
52
+ options: Object.freeze({ maxNetworkRetries: 0, redirect: "error" }),
53
+ originalBundle: Object.freeze({
54
+ subscription: Object.freeze({
55
+ id: "sub_payload",
56
+ schedule: null,
57
+ metadata: Object.freeze({ retained: "complete" }),
58
+ }),
59
+ targetPrice: Object.freeze({ id: "price_new", product: "prod_new" }),
60
+ }),
61
+ basis: Object.freeze({
62
+ startWallMs: 2000000000000,
63
+ startNs: "1000000000",
64
+ workEndWallMs: 2000000004000,
65
+ workEndNs: "5000000000",
66
+ endWallMs: 2000000005000,
67
+ endNs: "6000000000",
68
+ unqualifiedStoragePadding: "x".repeat(BASIS_PADDING),
69
+ }),
70
+ });
71
+ const eventData = Object.freeze({
72
+ event: "dispatch",
73
+ request: record.dispatch,
74
+ unqualifiedStoragePadding: "y".repeat(EVENT_PADDING),
75
+ });
76
+ // Distinct predeclared storage case. RPC argument strings remain ASCII.
77
+ const parsedUnicodeRecord = Object.freeze({
78
+ ...record,
79
+ logicalOperationId: "unicode-A",
80
+ authorization: Object.freeze({ ...record.authorization, id: "\ud800" }),
81
+ basis: Object.freeze({
82
+ ...record.basis,
83
+ unqualifiedStoragePadding: "finite-encoding-control",
84
+ }),
85
+ });
86
+ const create = makeFunctionReference<"mutation">(
87
+ "renewalOperations/mutations:createAuthorizedOperation",
88
+ );
89
+ const reserve = makeFunctionReference<"mutation">(
90
+ "renewalOperations/mutations:reserveAttempt",
91
+ );
92
+ const append = makeFunctionReference<"mutation">(
93
+ "renewalOperations/mutations:appendStageEvent",
94
+ );
95
+ const load = makeFunctionReference<"query">(
96
+ "renewalOperations/queries:loadAuthorizedOperation",
97
+ );
98
+ const read = makeFunctionReference<"query">(
99
+ "renewalOperations/queries:readAttempt",
100
+ );
101
+ afterEach(() => vi.unstubAllGlobals());
102
+
103
+ function jsonMetrics(value: unknown) {
104
+ let nodes = 0,
105
+ depth = 0;
106
+ function visit(item: unknown, level: number) {
107
+ nodes++;
108
+ depth = Math.max(depth, level);
109
+ if (item !== null && typeof item === "object")
110
+ for (const child of Object.values(item)) visit(child, level + 1);
111
+ }
112
+ visit(value, 0);
113
+ const json = JSON.stringify(value);
114
+ return {
115
+ characters: json.length,
116
+ utf8Bytes: new TextEncoder().encode(json).length,
117
+ nodes,
118
+ depth,
119
+ };
120
+ }
121
+
122
+ it("P01 refuses an oversized whole append envelope before any storage changes", async () => {
123
+ let fetchCalls = 0;
124
+ vi.stubGlobal("fetch", () => {
125
+ fetchCalls++;
126
+ throw Error("UNEXPECTED_EXTERNAL_FETCH");
127
+ });
128
+ const recordJSON = JSON.stringify(renewalSnapshot(record));
129
+ const eventJSON = JSON.stringify(renewalSnapshot(eventData));
130
+ const recordMetrics = jsonMetrics(JSON.parse(recordJSON));
131
+ const eventMetrics = jsonMetrics(JSON.parse(eventJSON));
132
+ for (const metric of [recordMetrics, eventMetrics]) {
133
+ expect(metric.characters).toBeLessThan(ACTOR_JSON_LIMIT);
134
+ expect(metric.utf8Bytes).toBeLessThan(ACTOR_JSON_LIMIT);
135
+ expect(metric.nodes).toBeLessThanOrEqual(10000);
136
+ expect(metric.depth).toBeLessThanOrEqual(40);
137
+ }
138
+ const node = objectNode([
139
+ ["event", scalarNode("dispatch")],
140
+ [
141
+ "request",
142
+ objectNode([
143
+ ["scope", scalarNode(record.dispatch.scope)],
144
+ ["apiVersion", scalarNode(record.dispatch.apiVersion)],
145
+ ["method", scalarNode(record.dispatch.method)],
146
+ ["path", scalarNode(record.dispatch.path)],
147
+ [
148
+ "payload",
149
+ objectNode([
150
+ [
151
+ "from_subscription",
152
+ scalarNode(record.dispatch.payload.from_subscription),
153
+ ],
154
+ ]),
155
+ ],
156
+ ["key", scalarNode(record.dispatch.key)],
157
+ ["firstDispatchedAt", scalarNode(record.dispatch.firstDispatchedAt)],
158
+ ]),
159
+ ],
160
+ [
161
+ "unqualifiedStoragePadding",
162
+ scalarNode(eventData.unqualifiedStoragePadding),
163
+ ],
164
+ ]);
165
+ // The whole DATA is in the existing hash preimage; no padding is projected away.
166
+ expect(materialize(node)).toEqual(eventData);
167
+ const binding = await eventDigest(
168
+ objectNode([
169
+ ["sequence", scalarNode(1)],
170
+ ["data", node],
171
+ ]),
172
+ );
173
+ expect(binding).toMatch(
174
+ /^unbound-qualification-event:v2:sha256:[0-9a-f]{64}$/,
175
+ );
176
+ const t = convexTest(schema, modules);
177
+ const creationArgs = {
178
+ authorizationScope: record.authorization.scope,
179
+ logicalOperationId: record.logicalOperationId,
180
+ authorizationRevision: record.authorization.revision,
181
+ recordJSON,
182
+ };
183
+ expect(getConvexSize(creationArgs)).toBeLessThan(VALUE_LIMIT);
184
+ const created = await t.mutation(create, creationArgs);
185
+ expect(created.status).toBe("created");
186
+ const loaded = await t.query(load, { operationId: created.operationId });
187
+ expect(loaded.recordJSON).toBe(recordJSON);
188
+ expect(loaded.revision).toBe(0);
189
+ expect(loaded.activeAttempt).toBeNull();
190
+ const reserveArgs = {
191
+ operationId: created.operationId,
192
+ expectedRevision: 0,
193
+ stage: "attach",
194
+ expectedRequestBinding: record.requestBinding,
195
+ recordJSON,
196
+ };
197
+ expect(getConvexSize(reserveArgs)).toBeLessThan(VALUE_LIMIT);
198
+ const acquired = await t.mutation(reserve, reserveArgs);
199
+ expect(acquired.disposition).toBe("acquired");
200
+ expect(acquired.reservation.recordJSON).toBe(recordJSON);
201
+ expect(acquired.reservation.basisJSON).toBe(
202
+ JSON.stringify(renewalSnapshot(record.basis)),
203
+ );
204
+ expect(acquired.reservation.key).toBe(record.dispatch.key);
205
+ expect(acquired.reservation.firstDispatchedAt).toBe(
206
+ record.dispatch.firstDispatchedAt,
207
+ );
208
+ expect(getConvexSize(acquired)).toBeLessThan(VALUE_LIMIT);
209
+ const initialHistory = await t.query(read, {
210
+ operationId: created.operationId,
211
+ attemptId: acquired.reservation.attemptId,
212
+ });
213
+ expect(initialHistory.events).toHaveLength(0);
214
+ expect(initialHistory.reservation).toEqual(acquired.reservation);
215
+ const args = {
216
+ reservation: acquired.reservation,
217
+ expectedSequence: 0,
218
+ event: { sequence: 1, binding, dataJSON: eventJSON },
219
+ };
220
+ const wholeArgsBytes = getConvexSize(args);
221
+ expect(wholeArgsBytes).toBeGreaterThan(VALUE_LIMIT);
222
+ const candidateEventPayloadBytes = getDocumentSize({
223
+ codecVersion: 1,
224
+ json: eventJSON,
225
+ });
226
+ expect(candidateEventPayloadBytes).toBeLessThan(VALUE_LIMIT);
227
+ async function physical() {
228
+ // Separate, joined bounded reads avoid inventing a giant production query.
229
+ const [operations, attempts, events, payloads] = await Promise.all([
230
+ t.run((ctx) => ctx.db.query("renewalOperations").take(3)),
231
+ t.run((ctx) => ctx.db.query("renewalOperationAttempts").take(3)),
232
+ t.run((ctx) => ctx.db.query("renewalOperationEvents").take(4)),
233
+ t.run((ctx) => ctx.db.query("renewalOperationPayloads").take(6)),
234
+ ]);
235
+ return { operations, attempts, events, payloads };
236
+ }
237
+ const before = await physical();
238
+ expect(before.operations).toHaveLength(1);
239
+ expect(before.attempts).toHaveLength(1);
240
+ expect(before.events).toHaveLength(0);
241
+ expect(before.payloads).toHaveLength(1);
242
+ expect(before.attempts[0].lastSequence).toBe(0);
243
+ expect(before.payloads[0].json).toBe(recordJSON);
244
+ const beforeDocumentBytes = [
245
+ ...before.operations,
246
+ ...before.attempts,
247
+ ...before.events,
248
+ ...before.payloads,
249
+ ].map((document) => getDocumentSize(document));
250
+ for (const bytes of beforeDocumentBytes)
251
+ expect(bytes).toBeLessThan(VALUE_LIMIT);
252
+ const beforeBytes = JSON.stringify(before);
253
+ expect(fetchCalls).toBe(0);
254
+ console.info(
255
+ "BTS317_P01_PREREQUISITES",
256
+ JSON.stringify({
257
+ basisPadding: BASIS_PADDING,
258
+ eventPadding: EVENT_PADDING,
259
+ recordMetrics,
260
+ eventMetrics,
261
+ wholeArgsBytes,
262
+ valueLimit: VALUE_LIMIT,
263
+ candidateEventPayloadBytes,
264
+ beforeDocumentBytes,
265
+ counts: { operations: 1, attempts: 1, events: 0, payloads: 1 },
266
+ sequence: before.attempts[0].lastSequence,
267
+ fetchCalls,
268
+ }),
269
+ );
270
+ let settlement:
271
+ | { status: "fulfilled" }
272
+ | { status: "rejected"; message: string; messageLength: number }
273
+ | undefined;
274
+ let after: Awaited<ReturnType<typeof physical>> | undefined;
275
+ let appendResultBytes: number | undefined;
276
+ try {
277
+ const actualReply = await t.mutation(append, args);
278
+ appendResultBytes = getConvexSize(actualReply);
279
+ settlement = { status: "fulfilled" };
280
+ } catch (error) {
281
+ const message =
282
+ error instanceof Error ? error.message : "NON_ERROR_REJECTION";
283
+ settlement = {
284
+ status: "rejected",
285
+ message: message.slice(0, 200),
286
+ messageLength: message.length,
287
+ };
288
+ } finally {
289
+ after = await physical();
290
+ const documentBytes = [
291
+ ...after.operations,
292
+ ...after.attempts,
293
+ ...after.events,
294
+ ...after.payloads,
295
+ ].map((document) => getDocumentSize(document));
296
+ console.info(
297
+ "BTS317_P01_SETTLEMENT",
298
+ JSON.stringify({
299
+ settlement,
300
+ appendResultBytes,
301
+ physicalEqual: JSON.stringify(after) === beforeBytes,
302
+ counts: {
303
+ operations: after.operations.length,
304
+ attempts: after.attempts.length,
305
+ events: after.events.length,
306
+ payloads: after.payloads.length,
307
+ },
308
+ sequence: after.attempts[0]?.lastSequence,
309
+ documentBytes,
310
+ fetchCalls,
311
+ }),
312
+ );
313
+ }
314
+ expect(fetchCalls).toBe(0);
315
+ // Tiny result assertion avoids dumping a giant resolved receipt on failure.
316
+ expect(settlement).toEqual({
317
+ status: "rejected",
318
+ message: "RENEWAL_JOURNAL_LIMIT",
319
+ messageLength: 21,
320
+ });
321
+ expect(after !== undefined && JSON.stringify(after) === beforeBytes).toBe(
322
+ true,
323
+ );
324
+ });
325
+
326
+ it("P02 refuses an unpaired parsed authorization ID before any writes", async () => {
327
+ let fetchCalls = 0;
328
+ vi.stubGlobal("fetch", () => {
329
+ fetchCalls++;
330
+ throw Error("UNEXPECTED_EXTERNAL_FETCH");
331
+ });
332
+ const recordJSON = JSON.stringify(renewalSnapshot(parsedUnicodeRecord));
333
+ expect(recordJSON).toContain("\\ud800");
334
+ expect(
335
+ Array.from(recordJSON).every((character) => character.charCodeAt(0) < 128),
336
+ ).toBe(true);
337
+ const parsedId: string = JSON.parse(recordJSON).authorization.id;
338
+ expect(parsedId.length).toBe(1);
339
+ expect(parsedId.charCodeAt(0)).toBe(0xd800);
340
+ const metrics = jsonMetrics(JSON.parse(recordJSON));
341
+ expect(metrics.characters).toBeLessThan(ACTOR_JSON_LIMIT);
342
+ expect(metrics.utf8Bytes).toBeLessThan(ACTOR_JSON_LIMIT);
343
+ expect(metrics.nodes).toBeLessThanOrEqual(10000);
344
+ expect(metrics.depth).toBeLessThanOrEqual(40);
345
+ const args = {
346
+ authorizationScope: parsedUnicodeRecord.authorization.scope,
347
+ logicalOperationId: parsedUnicodeRecord.logicalOperationId,
348
+ authorizationRevision: parsedUnicodeRecord.authorization.revision,
349
+ recordJSON,
350
+ };
351
+ const wholeArgsBytes = getConvexSize(args);
352
+ expect(wholeArgsBytes).toBeLessThan(VALUE_LIMIT);
353
+ const t = convexTest(schema, modules);
354
+ async function physical() {
355
+ const [operations, attempts, events, payloads] = await Promise.all([
356
+ t.run((ctx) => ctx.db.query("renewalOperations").take(3)),
357
+ t.run((ctx) => ctx.db.query("renewalOperationAttempts").take(3)),
358
+ t.run((ctx) => ctx.db.query("renewalOperationEvents").take(4)),
359
+ t.run((ctx) => ctx.db.query("renewalOperationPayloads").take(6)),
360
+ ]);
361
+ return { operations, attempts, events, payloads };
362
+ }
363
+ const before = await physical();
364
+ expect(before).toEqual({
365
+ operations: [],
366
+ attempts: [],
367
+ events: [],
368
+ payloads: [],
369
+ });
370
+ const beforeBytes = JSON.stringify(before);
371
+ expect(fetchCalls).toBe(0);
372
+ console.info(
373
+ "BTS317_P02_PREREQUISITES",
374
+ JSON.stringify({
375
+ metrics,
376
+ wholeArgsBytes,
377
+ valueLimit: VALUE_LIMIT,
378
+ parsedIdCodeUnits: [parsedId.charCodeAt(0)],
379
+ rpcStringsASCII: true,
380
+ counts: { operations: 0, attempts: 0, events: 0, payloads: 0 },
381
+ fetchCalls,
382
+ }),
383
+ );
384
+ let settlement:
385
+ | { status: "fulfilled"; resultStatus: string }
386
+ | { status: "rejected"; message: string; messageLength: number }
387
+ | undefined;
388
+ let after: Awaited<ReturnType<typeof physical>> | undefined;
389
+ try {
390
+ const actualReply = await t.mutation(create, args);
391
+ settlement = { status: "fulfilled", resultStatus: actualReply.status };
392
+ } catch (error) {
393
+ const message =
394
+ error instanceof Error ? error.message : "NON_ERROR_REJECTION";
395
+ settlement = {
396
+ status: "rejected",
397
+ message: message.slice(0, 200),
398
+ messageLength: message.length,
399
+ };
400
+ } finally {
401
+ after = await physical();
402
+ const documentBytes = [
403
+ ...after.operations,
404
+ ...after.attempts,
405
+ ...after.events,
406
+ ...after.payloads,
407
+ ].map((document) => getDocumentSize(document));
408
+ console.info(
409
+ "BTS317_P02_SETTLEMENT",
410
+ JSON.stringify({
411
+ settlement,
412
+ physicalEqual: JSON.stringify(after) === beforeBytes,
413
+ counts: {
414
+ operations: after.operations.length,
415
+ attempts: after.attempts.length,
416
+ events: after.events.length,
417
+ payloads: after.payloads.length,
418
+ },
419
+ documentBytes,
420
+ fetchCalls,
421
+ }),
422
+ );
423
+ }
424
+ expect(fetchCalls).toBe(0);
425
+ expect(settlement).toEqual({
426
+ status: "rejected",
427
+ message: "RENEWAL_JOURNAL_ENCODING",
428
+ messageLength: 24,
429
+ });
430
+ expect(after !== undefined && JSON.stringify(after) === beforeBytes).toBe(
431
+ true,
432
+ );
433
+ });
434
+
435
+ it("P07 returns complete readable operation DATA within one value envelope", async () => {
436
+ let fetchCalls = 0;
437
+ vi.stubGlobal("fetch", () => {
438
+ fetchCalls++;
439
+ throw Error("UNEXPECTED_EXTERNAL_FETCH");
440
+ });
441
+ const recordJSON = JSON.stringify(renewalSnapshot(record));
442
+ const t = convexTest(schema, modules);
443
+ const creationArgs = {
444
+ authorizationScope: record.authorization.scope,
445
+ authorizationRevision: record.authorization.revision,
446
+ logicalOperationId: record.logicalOperationId,
447
+ recordJSON,
448
+ };
449
+ expect(getConvexSize(creationArgs)).toBeLessThan(VALUE_LIMIT);
450
+ const created = await t.mutation(create, creationArgs);
451
+ expect(created.status).toBe("created");
452
+ expect(getConvexSize(created)).toBeLessThan(VALUE_LIMIT);
453
+ const queryArgs = { operationId: created.operationId };
454
+ expect(getConvexSize(queryArgs)).toBeLessThan(VALUE_LIMIT);
455
+ const prepared = await t.query(load, queryArgs);
456
+ expect(prepared).toEqual({
457
+ operationId: created.operationId,
458
+ recordJSON,
459
+ revision: 0,
460
+ activeAttempt: null,
461
+ });
462
+ expect(getConvexSize(prepared)).toBeLessThan(VALUE_LIMIT);
463
+ const reserveArgs = {
464
+ operationId: created.operationId,
465
+ expectedRevision: 0,
466
+ stage: "attach",
467
+ expectedRequestBinding: record.requestBinding,
468
+ recordJSON,
469
+ };
470
+ expect(getConvexSize(reserveArgs)).toBeLessThan(VALUE_LIMIT);
471
+ const acquired = await t.mutation(reserve, reserveArgs);
472
+ expect(acquired.disposition).toBe("acquired");
473
+ expect(acquired.reservation.recordJSON).toBe(recordJSON);
474
+ expect(acquired.reservation.basisJSON).toBe(
475
+ JSON.stringify(renewalSnapshot(record.basis)),
476
+ );
477
+ const acquiredBytes = getConvexSize(acquired);
478
+ expect(acquiredBytes).toBeLessThan(VALUE_LIMIT);
479
+ // Counterexample construction only. The desired query may remove this duplication.
480
+ const oldShapeBytes = getConvexSize({
481
+ operationId: created.operationId,
482
+ recordJSON,
483
+ revision: 1,
484
+ activeAttempt: acquired.reservation,
485
+ });
486
+ expect(oldShapeBytes).toBeGreaterThan(VALUE_LIMIT);
487
+ const physical = () =>
488
+ Promise.all([
489
+ t.run((ctx) => ctx.db.query("renewalOperations").take(3)),
490
+ t.run((ctx) => ctx.db.query("renewalOperationAttempts").take(3)),
491
+ t.run((ctx) => ctx.db.query("renewalOperationEvents").take(4)),
492
+ t.run((ctx) => ctx.db.query("renewalOperationPayloads").take(6)),
493
+ ]);
494
+ const before = await physical();
495
+ expect(before.map((rows) => rows.length)).toEqual([1, 1, 0, 1]);
496
+ expect(before[0][0].state).toBe("RESERVED");
497
+ expect(before[0][0].revision).toBe(1);
498
+ expect(before[1][0].lastSequence).toBe(0);
499
+ expect(before[3][0].json).toBe(recordJSON);
500
+ const beforeJSON = JSON.stringify(before);
501
+ const documentBytes = before.flatMap((rows) =>
502
+ rows.map((doc) => getDocumentSize(doc)),
503
+ );
504
+ for (const bytes of documentBytes) expect(bytes).toBeLessThan(VALUE_LIMIT);
505
+ expect(fetchCalls).toBe(0);
506
+ console.info(
507
+ "BTS317_P07_PREREQUISITES",
508
+ JSON.stringify({
509
+ basisPadding: BASIS_PADDING,
510
+ canonicalCharacters: recordJSON.length,
511
+ canonicalUTF8Bytes: new TextEncoder().encode(recordJSON).length,
512
+ acquiredBytes,
513
+ oldShapeBytes,
514
+ documentBytes,
515
+ counts: [1, 1, 0, 1],
516
+ fetchCalls,
517
+ }),
518
+ );
519
+ function fullRecordCopies(value: unknown): number {
520
+ if (value === recordJSON) return 1;
521
+ if (value === null || typeof value !== "object") return 0;
522
+ return Object.values(value).reduce<number>(
523
+ (sum, child) => sum + fullRecordCopies(child),
524
+ 0,
525
+ );
526
+ }
527
+ let settlement:
528
+ | { status: "fulfilled"; bytes: number }
529
+ | { status: "rejected"; message: string; messageLength: number }
530
+ | undefined;
531
+ let observed:
532
+ | {
533
+ fullRecordEqual: boolean;
534
+ copies: number;
535
+ revision: unknown;
536
+ sameAttempt: boolean;
537
+ sameOperation: boolean;
538
+ }
539
+ | undefined;
540
+ let after: Awaited<ReturnType<typeof physical>> | undefined;
541
+ try {
542
+ const actual = await t.query(load, queryArgs);
543
+ settlement = { status: "fulfilled", bytes: getConvexSize(actual) };
544
+ observed = {
545
+ fullRecordEqual: actual.recordJSON === recordJSON,
546
+ copies: fullRecordCopies(actual),
547
+ revision: actual.revision,
548
+ sameAttempt:
549
+ actual.activeAttempt?.attemptId === acquired.reservation.attemptId,
550
+ sameOperation: actual.operationId === created.operationId,
551
+ };
552
+ } catch (error) {
553
+ const message =
554
+ error instanceof Error ? error.message : "NON_ERROR_REJECTION";
555
+ settlement = {
556
+ status: "rejected",
557
+ message: message.slice(0, 200),
558
+ messageLength: message.length,
559
+ };
560
+ } finally {
561
+ after = await physical();
562
+ console.info(
563
+ "BTS317_P07_SETTLEMENT",
564
+ JSON.stringify({
565
+ settlement,
566
+ observed,
567
+ physicalEqual: JSON.stringify(after) === beforeJSON,
568
+ counts: after.map((rows) => rows.length),
569
+ revision: after[0][0]?.revision,
570
+ fetchCalls,
571
+ }),
572
+ );
573
+ }
574
+ expect(fetchCalls).toBe(0);
575
+ expect(settlement?.status).toBe("fulfilled");
576
+ expect(
577
+ settlement?.status === "fulfilled" && settlement.bytes <= VALUE_LIMIT,
578
+ ).toBe(true);
579
+ expect(observed).toEqual({
580
+ fullRecordEqual: true,
581
+ copies: 1,
582
+ revision: 1,
583
+ sameAttempt: true,
584
+ sameOperation: true,
585
+ });
586
+ expect(after !== undefined && JSON.stringify(after) === beforeJSON).toBe(
587
+ true,
588
+ );
589
+ });