@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,592 @@
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 { canonicalFingerprint } from "../operationEvidence/canonical.js";
7
+ import { canonicalJournalRecord } from "../../shared/renewalOperationJournal.js";
8
+ import { renewalSnapshot } from "../../client/billing/renewalReplacementSnapshot.js";
9
+
10
+ const VALUE_LIMIT = 1048576;
11
+ // Independent immutable storage DATA. No maintained provider/Owner applicability.
12
+ const base = Object.freeze({
13
+ schemaVersion: 1,
14
+ requestBinding: "encoding-consistency-A",
15
+ authorization: Object.freeze({
16
+ scope: "encoding-merchant",
17
+ id: "encoding-consent",
18
+ revision: 1,
19
+ }),
20
+ logicalOperationId: "encoding-base",
21
+ stage: "attach",
22
+ account: Object.freeze({
23
+ mode: "platform",
24
+ stripeAccount: null,
25
+ livemode: false,
26
+ }),
27
+ apiVersion: "2026-09-30.endive",
28
+ profile: "unqualified-encoding-DATA",
29
+ subscriptionId: "sub_encoding",
30
+ customerId: "cus_encoding",
31
+ itemId: "si_encoding",
32
+ currentPriceId: "price_old",
33
+ targetPriceId: "price_new",
34
+ targetProductId: "prod_new",
35
+ period: Object.freeze({ start: 2000000000, end: 2000003600 }),
36
+ dispatch: Object.freeze({
37
+ scope: "platform",
38
+ apiVersion: "2026-09-30.endive",
39
+ method: "POST",
40
+ path: "/v1/subscription_schedules",
41
+ payload: Object.freeze({ from_subscription: "sub_encoding" }),
42
+ key: "retained-encoding-key",
43
+ firstDispatchedAt: 2000000000,
44
+ }),
45
+ options: Object.freeze({ maxNetworkRetries: 0, redirect: "error" }),
46
+ originalBundle: Object.freeze({
47
+ subscription: Object.freeze({
48
+ id: "sub_encoding",
49
+ schedule: null,
50
+ metadata: Object.freeze({ retained: "complete" }),
51
+ }),
52
+ targetPrice: Object.freeze({ id: "price_new", product: "prod_new" }),
53
+ }),
54
+ basis: Object.freeze({
55
+ startWallMs: 2000000000000,
56
+ startNs: "1000000000",
57
+ workEndWallMs: 2000000004000,
58
+ workEndNs: "5000000000",
59
+ endWallMs: 2000000005000,
60
+ endNs: "6000000000",
61
+ }),
62
+ });
63
+ const badKey = Object.freeze({
64
+ ...base,
65
+ logicalOperationId: "encoding-key",
66
+ dispatch: Object.freeze({ ...base.dispatch, key: "\ud800" }),
67
+ });
68
+ const badAPI = Object.freeze({
69
+ ...base,
70
+ logicalOperationId: "encoding-api",
71
+ apiVersion: "\ud800",
72
+ dispatch: Object.freeze({ ...base.dispatch, apiVersion: "\ud800" }),
73
+ });
74
+ const pairedHeader = Object.freeze({
75
+ ...base,
76
+ logicalOperationId: "encoding-paired",
77
+ authorization: Object.freeze({
78
+ ...base.authorization,
79
+ id: "consent-\u00e9-\ud83d\ude80",
80
+ }),
81
+ });
82
+ const escapedNested = Object.freeze({
83
+ ...base,
84
+ logicalOperationId: "encoding-nested",
85
+ originalBundle: Object.freeze({
86
+ ...base.originalBundle,
87
+ subscription: Object.freeze({
88
+ ...base.originalBundle.subscription,
89
+ metadata: Object.freeze({
90
+ ...base.originalBundle.subscription.metadata,
91
+ unpaired: "\ud800",
92
+ }),
93
+ }),
94
+ }),
95
+ });
96
+
97
+ const create = makeFunctionReference<"mutation">(
98
+ "renewalOperations/mutations:createAuthorizedOperation",
99
+ );
100
+ const load = makeFunctionReference<"query">(
101
+ "renewalOperations/queries:loadAuthorizedOperation",
102
+ );
103
+ const reserve = makeFunctionReference<"mutation">(
104
+ "renewalOperations/mutations:reserveAttempt",
105
+ );
106
+ afterEach(() => vi.unstubAllGlobals());
107
+ function fixture() {
108
+ let calls = 0;
109
+ vi.stubGlobal("fetch", () => {
110
+ calls++;
111
+ throw Error("UNEXPECTED_EXTERNAL_FETCH");
112
+ });
113
+ const t = convexTest(schema, modules);
114
+ async function physical() {
115
+ const [operations, attempts, events, payloads] = await Promise.all([
116
+ t.run((ctx) => ctx.db.query("renewalOperations").take(3)),
117
+ t.run((ctx) => ctx.db.query("renewalOperationAttempts").take(3)),
118
+ t.run((ctx) => ctx.db.query("renewalOperationEvents").take(4)),
119
+ t.run((ctx) => ctx.db.query("renewalOperationPayloads").take(6)),
120
+ ]);
121
+ return { operations, attempts, events, payloads };
122
+ }
123
+ return { t, physical, fetchCalls: () => calls };
124
+ }
125
+ function wireRecord(value: unknown) {
126
+ const canonicalJSON = JSON.stringify(renewalSnapshot(value));
127
+ const wireJSON = canonicalJSON
128
+ .split("\ud83d\ude80")
129
+ .join("\\ud83d\\ude80")
130
+ .split("\u00e9")
131
+ .join("\\u00e9");
132
+ expect(
133
+ Array.from(wireJSON).every((character) => character.charCodeAt(0) < 128),
134
+ ).toBe(true);
135
+ return { canonicalJSON, wireJSON };
136
+ }
137
+
138
+ async function refusedAttempt(
139
+ candidate: typeof badKey | typeof badAPI,
140
+ field: "key" | "apiVersion",
141
+ ) {
142
+ const { canonicalJSON, wireJSON } = wireRecord(candidate);
143
+ const normalized = canonicalJournalRecord(wireJSON);
144
+ expect(normalized.json).toBe(canonicalJSON);
145
+ expect(normalized.authorizationScope).toBe(base.authorization.scope);
146
+ expect(normalized.authorizationId).toBe(base.authorization.id);
147
+ expect(normalized.authorizationRevision).toBe(base.authorization.revision);
148
+ expect(normalized.logicalOperationId).toBe(candidate.logicalOperationId);
149
+ expect(normalized.requestBinding).toBe(base.requestBinding);
150
+ const parsed: typeof candidate = JSON.parse(wireJSON);
151
+ expect(parsed).toEqual(candidate);
152
+ const invalid = field === "key" ? parsed.dispatch.key : parsed.apiVersion;
153
+ expect(invalid.length).toBe(1);
154
+ expect(invalid.charCodeAt(0)).toBe(0xd800);
155
+ expect(parsed.dispatch.scope).toBe(parsed.account.mode);
156
+ expect(parsed.dispatch.apiVersion).toBe(parsed.apiVersion);
157
+ expect(parsed.dispatch.firstDispatchedAt).toBe(
158
+ base.dispatch.firstDispatchedAt,
159
+ );
160
+ expect(wireJSON.length).toBeLessThan(500000);
161
+ expect(new TextEncoder().encode(wireJSON).length).toBeLessThan(500000);
162
+ // A real existing SHA256 DATA fingerprint; not C1/provider/authorization proof.
163
+ const fingerprint = await canonicalFingerprint(canonicalJSON);
164
+ expect(fingerprint).toMatch(/^[0-9a-f]{64}$/);
165
+ const { t, physical, fetchCalls } = fixture();
166
+ const creationArgs = {
167
+ authorizationScope: candidate.authorization.scope,
168
+ authorizationRevision: candidate.authorization.revision,
169
+ logicalOperationId: candidate.logicalOperationId,
170
+ recordJSON: wireJSON,
171
+ };
172
+ expect(getConvexSize(creationArgs)).toBeLessThan(VALUE_LIMIT);
173
+ const created = await t.mutation(create, creationArgs);
174
+ expect(created.status).toBe("created");
175
+ const loaded = await t.query(load, { operationId: created.operationId });
176
+ expect(loaded).toEqual({
177
+ operationId: created.operationId,
178
+ recordJSON: canonicalJSON,
179
+ revision: 0,
180
+ activeAttempt: null,
181
+ });
182
+ const before = await physical();
183
+ expect(before.operations).toHaveLength(1);
184
+ expect(before.attempts).toHaveLength(0);
185
+ expect(before.events).toHaveLength(0);
186
+ expect(before.payloads).toHaveLength(1);
187
+ expect(before.operations[0].revision).toBe(0);
188
+ expect(before.operations[0].state).toBe("PREPARED");
189
+ expect(before.operations[0].authorizationId).toBe(base.authorization.id);
190
+ expect(before.payloads[0].json).toBe(canonicalJSON);
191
+ const beforeJSON = JSON.stringify(before);
192
+ const args = {
193
+ operationId: created.operationId,
194
+ expectedRevision: 0,
195
+ stage: "attach",
196
+ expectedRequestBinding: candidate.requestBinding,
197
+ recordJSON: wireJSON,
198
+ };
199
+ const wholeArgsBytes = getConvexSize(args);
200
+ expect(wholeArgsBytes).toBeLessThan(VALUE_LIMIT);
201
+ const beforeDocumentBytes = [...before.operations, ...before.payloads].map(
202
+ (doc) => getDocumentSize(doc),
203
+ );
204
+ for (const bytes of beforeDocumentBytes)
205
+ expect(bytes).toBeLessThan(VALUE_LIMIT);
206
+ expect(fetchCalls()).toBe(0);
207
+ console.info(
208
+ "BTS317_ATTEMPT_ENCODING_PREREQUISITES",
209
+ JSON.stringify({
210
+ field,
211
+ wholeArgsBytes,
212
+ canonicalCharacters: canonicalJSON.length,
213
+ canonicalUTF8Bytes: new TextEncoder().encode(canonicalJSON).length,
214
+ fingerprintLength: fingerprint.length,
215
+ invalidCodeUnit: invalid.charCodeAt(0),
216
+ beforeDocumentBytes,
217
+ counts: { operations: 1, attempts: 0, events: 0, payloads: 1 },
218
+ fetchCalls: fetchCalls(),
219
+ }),
220
+ );
221
+ let settlement:
222
+ | { status: "fulfilled"; disposition: string }
223
+ | { status: "rejected"; message: string; messageLength: number }
224
+ | undefined;
225
+ let after: Awaited<ReturnType<typeof physical>> | undefined;
226
+ try {
227
+ const result = await t.mutation(reserve, args);
228
+ settlement = { status: "fulfilled", disposition: result.disposition };
229
+ } catch (error) {
230
+ const message =
231
+ error instanceof Error ? error.message : "NON_ERROR_REJECTION";
232
+ settlement = {
233
+ status: "rejected",
234
+ message: message.slice(0, 200),
235
+ messageLength: message.length,
236
+ };
237
+ } finally {
238
+ after = await physical();
239
+ console.info(
240
+ "BTS317_ATTEMPT_ENCODING_SETTLEMENT",
241
+ JSON.stringify({
242
+ field,
243
+ settlement,
244
+ physicalEqual: JSON.stringify(after) === beforeJSON,
245
+ counts: {
246
+ operations: after.operations.length,
247
+ attempts: after.attempts.length,
248
+ events: after.events.length,
249
+ payloads: after.payloads.length,
250
+ },
251
+ revision: after.operations[0]?.revision,
252
+ documentBytes: [
253
+ ...after.operations,
254
+ ...after.attempts,
255
+ ...after.events,
256
+ ...after.payloads,
257
+ ].map((doc) => getDocumentSize(doc)),
258
+ fetchCalls: fetchCalls(),
259
+ }),
260
+ );
261
+ }
262
+ expect(fetchCalls()).toBe(0);
263
+ expect(settlement).toEqual({
264
+ status: "rejected",
265
+ message: "RENEWAL_JOURNAL_ENCODING",
266
+ messageLength: 24,
267
+ });
268
+ expect(after !== undefined && JSON.stringify(after) === beforeJSON).toBe(
269
+ true,
270
+ );
271
+ }
272
+
273
+ it("P03 refuses an unpaired parsed attempt key after valid creation", async () => {
274
+ await refusedAttempt(badKey, "key");
275
+ });
276
+ it("P04 refuses an unpaired parsed attempt API version after valid creation", async () => {
277
+ await refusedAttempt(badAPI, "apiVersion");
278
+ });
279
+ it("P05 preserves valid Unicode and a paired surrogate in a creation header", async () => {
280
+ const { canonicalJSON, wireJSON } = wireRecord(pairedHeader);
281
+ const { t, physical, fetchCalls } = fixture();
282
+ const created = await t.mutation(create, {
283
+ authorizationScope: pairedHeader.authorization.scope,
284
+ authorizationRevision: pairedHeader.authorization.revision,
285
+ logicalOperationId: pairedHeader.logicalOperationId,
286
+ recordJSON: wireJSON,
287
+ });
288
+ expect(created.status).toBe("created");
289
+ const loaded = await t.query(load, { operationId: created.operationId });
290
+ expect(loaded).toEqual({
291
+ operationId: created.operationId,
292
+ recordJSON: canonicalJSON,
293
+ revision: 0,
294
+ activeAttempt: null,
295
+ });
296
+ const stored = await physical();
297
+ expect(stored.operations).toHaveLength(1);
298
+ expect(stored.payloads).toHaveLength(1);
299
+ expect(stored.attempts).toHaveLength(0);
300
+ expect(stored.events).toHaveLength(0);
301
+ expect(stored.operations[0].authorizationId).toBe(
302
+ pairedHeader.authorization.id,
303
+ );
304
+ expect(stored.payloads[0].json).toBe(canonicalJSON);
305
+ const id = stored.operations[0].authorizationId;
306
+ expect(id.charCodeAt(id.length - 2)).toBe(0xd83d);
307
+ expect(id.charCodeAt(id.length - 1)).toBe(0xde80);
308
+ expect(id.includes("\u00e9")).toBe(true);
309
+ for (const doc of [...stored.operations, ...stored.payloads])
310
+ expect(getDocumentSize(doc)).toBeLessThan(VALUE_LIMIT);
311
+ expect(fetchCalls()).toBe(0);
312
+ });
313
+ it("P06 preserves an escaped unpaired value nested only inside retained JSON", async () => {
314
+ const { canonicalJSON, wireJSON } = wireRecord(escapedNested);
315
+ expect(wireJSON).toContain("\\ud800");
316
+ const { t, physical, fetchCalls } = fixture();
317
+ const created = await t.mutation(create, {
318
+ authorizationScope: escapedNested.authorization.scope,
319
+ authorizationRevision: escapedNested.authorization.revision,
320
+ logicalOperationId: escapedNested.logicalOperationId,
321
+ recordJSON: wireJSON,
322
+ });
323
+ expect(created.status).toBe("created");
324
+ const loaded = await t.query(load, { operationId: created.operationId });
325
+ expect(loaded.recordJSON).toBe(canonicalJSON);
326
+ expect(JSON.parse(loaded.recordJSON)).toEqual(escapedNested);
327
+ const nested: string = JSON.parse(loaded.recordJSON).originalBundle
328
+ .subscription.metadata.unpaired;
329
+ expect(nested.length).toBe(1);
330
+ expect(nested.charCodeAt(0)).toBe(0xd800);
331
+ const stored = await physical();
332
+ expect(stored.operations).toHaveLength(1);
333
+ expect(stored.payloads).toHaveLength(1);
334
+ expect(stored.attempts).toHaveLength(0);
335
+ expect(stored.events).toHaveLength(0);
336
+ expect(stored.operations[0].authorizationId).toBe(base.authorization.id);
337
+ expect(stored.payloads[0].json).toBe(canonicalJSON);
338
+ for (const doc of [...stored.operations, ...stored.payloads])
339
+ expect(getDocumentSize(doc)).toBeLessThan(VALUE_LIMIT);
340
+ expect(fetchCalls()).toBe(0);
341
+ });
342
+
343
+ // All six recipes and complete near-cap records are declared before fixtures.
344
+ // Large indexed scope is emulator-only until native index limits are qualified.
345
+ const loadBoundaryRecipes = [
346
+ ["basis", 'é🚀\\"\n'],
347
+ ["account", "🚀é\t\\"],
348
+ ["authorization-scope", 'é🚀"\\'],
349
+ ["authorization-id", '🚀é\n"'],
350
+ ["key", "é🚀\\\t"],
351
+ ["request-binding", '🚀é"\n'],
352
+ ] as const;
353
+ type LoadBoundaryField = (typeof loadBoundaryRecipes)[number][0];
354
+ function boundaryRecord(field: LoadBoundaryField, padding: string) {
355
+ return {
356
+ ...base,
357
+ logicalOperationId: `load-boundary-${field}`,
358
+ requestBinding: field === "request-binding" ? padding : base.requestBinding,
359
+ basis: {
360
+ ...base.basis,
361
+ boundaryPadding: field === "basis" ? padding : "",
362
+ },
363
+ account: {
364
+ ...base.account,
365
+ boundaryPadding: field === "account" ? padding : "",
366
+ },
367
+ authorization: {
368
+ ...base.authorization,
369
+ scope:
370
+ field === "authorization-scope" ? padding : base.authorization.scope,
371
+ id: field === "authorization-id" ? padding : base.authorization.id,
372
+ },
373
+ dispatch: {
374
+ ...base.dispatch,
375
+ key: field === "key" ? padding : base.dispatch.key,
376
+ },
377
+ };
378
+ }
379
+ const loadBoundaryCases = loadBoundaryRecipes.map(([name, unit]) => {
380
+ const utf8 = new TextEncoder();
381
+ const emptyBytes = utf8.encode(
382
+ JSON.stringify(renewalSnapshot(boundaryRecord(name, ""))),
383
+ ).length;
384
+ const unitJSONBytes = utf8.encode(JSON.stringify(unit)).length - 2;
385
+ const count = Math.floor((499900 - emptyBytes) / unitJSONBytes);
386
+ const record = boundaryRecord(name, unit.repeat(count));
387
+ const recordJSON = JSON.stringify(renewalSnapshot(record));
388
+ return Object.freeze({ name, record, recordJSON, unitJSONBytes });
389
+ });
390
+
391
+ it.each(loadBoundaryCases)(
392
+ "P08 near-cap complete load retains every field for $name",
393
+ async ({ name, record, recordJSON, unitJSONBytes }) => {
394
+ // Pure declared UTF8 construction, never adjusted after an RPC response.
395
+ const bytes = new TextEncoder().encode(recordJSON).length;
396
+ expect(bytes).toBeGreaterThanOrEqual(499900 - unitJSONBytes);
397
+ expect(bytes).toBeLessThanOrEqual(499900);
398
+ expect(recordJSON.length).toBeLessThanOrEqual(500000);
399
+ expect(bytes).toBeLessThanOrEqual(500000);
400
+ expect(recordJSON).toContain("é");
401
+ expect(recordJSON).toContain("🚀");
402
+ expect(recordJSON).toMatch(/\\["\\nt]/);
403
+ const canonical = canonicalJournalRecord(recordJSON);
404
+ expect(canonical.json).toBe(recordJSON);
405
+ const { t, physical, fetchCalls } = fixture();
406
+ const creationArgs = {
407
+ authorizationScope: record.authorization.scope,
408
+ authorizationRevision: record.authorization.revision,
409
+ logicalOperationId: record.logicalOperationId,
410
+ recordJSON,
411
+ };
412
+ expect(getConvexSize(creationArgs)).toBeLessThanOrEqual(VALUE_LIMIT);
413
+ const created = await t.mutation(create, creationArgs);
414
+ expect(created.status).toBe("created");
415
+ expect(getConvexSize(created)).toBeLessThanOrEqual(VALUE_LIMIT);
416
+ const queryArgs = { operationId: created.operationId };
417
+ expect(getConvexSize(queryArgs)).toBeLessThanOrEqual(VALUE_LIMIT);
418
+ const prepared = await t.query(load, queryArgs);
419
+ expect(prepared).toEqual({
420
+ operationId: created.operationId,
421
+ recordJSON,
422
+ revision: 0,
423
+ activeAttempt: null,
424
+ });
425
+ expect(getConvexSize(prepared)).toBeLessThanOrEqual(VALUE_LIMIT);
426
+ const preparedRows = await physical();
427
+ expect(preparedRows.operations).toHaveLength(1);
428
+ expect(preparedRows.attempts).toHaveLength(0);
429
+ expect(preparedRows.events).toHaveLength(0);
430
+ expect(preparedRows.payloads).toHaveLength(1);
431
+ for (const rows of Object.values(preparedRows))
432
+ for (const doc of rows)
433
+ expect(getDocumentSize(doc)).toBeLessThanOrEqual(VALUE_LIMIT);
434
+ const reserveArgs = {
435
+ operationId: created.operationId,
436
+ expectedRevision: 0,
437
+ stage: "attach",
438
+ expectedRequestBinding: record.requestBinding,
439
+ recordJSON,
440
+ };
441
+ expect(getConvexSize(reserveArgs)).toBeLessThanOrEqual(VALUE_LIMIT);
442
+ const acquired = await t.mutation(reserve, reserveArgs);
443
+ expect(acquired.disposition).toBe("acquired");
444
+ expect(getConvexSize(acquired)).toBeLessThanOrEqual(VALUE_LIMIT);
445
+ expect(acquired.reservation.recordJSON).toBe(recordJSON);
446
+ expect(acquired.reservation.basisJSON).toBe(
447
+ JSON.stringify(renewalSnapshot(record.basis)),
448
+ );
449
+ expect(acquired.reservation.accountJSON).toBe(
450
+ JSON.stringify(renewalSnapshot(record.account)),
451
+ );
452
+ expect(acquired.reservation.authorizationScope).toBe(
453
+ record.authorization.scope,
454
+ );
455
+ expect(acquired.reservation.authorizationId).toBe(record.authorization.id);
456
+ expect(acquired.reservation.key).toBe(record.dispatch.key);
457
+ expect(acquired.reservation.requestBinding).toBe(record.requestBinding);
458
+ const { recordJSON: reservationJSON, ...expectedSummary } =
459
+ acquired.reservation;
460
+ expect(reservationJSON).toBe(recordJSON);
461
+ expect(Object.keys(expectedSummary)).toHaveLength(17);
462
+ const beforeLoad = await physical();
463
+ const beforeLoadJSON = JSON.stringify(beforeLoad);
464
+ const loaded = await t.query(load, queryArgs);
465
+ expect(getConvexSize(loaded)).toBeLessThanOrEqual(VALUE_LIMIT);
466
+ expect(loaded).toEqual({
467
+ operationId: created.operationId,
468
+ recordJSON,
469
+ revision: 1,
470
+ activeAttempt: expectedSummary,
471
+ });
472
+ expect(JSON.parse(loaded.recordJSON)).toEqual(record);
473
+ expect(
474
+ Object.prototype.hasOwnProperty.call(loaded.activeAttempt, "recordJSON"),
475
+ ).toBe(false);
476
+ expect(Object.prototype.hasOwnProperty.call(loaded, "acquired")).toBe(
477
+ false,
478
+ );
479
+ function completeRecordCopies(value: unknown): number {
480
+ if (value === recordJSON) return 1;
481
+ if (value === null || typeof value !== "object") return 0;
482
+ return Object.values(value).reduce<number>(
483
+ (sum, child) => sum + completeRecordCopies(child),
484
+ 0,
485
+ );
486
+ }
487
+ expect(completeRecordCopies(loaded)).toBe(1);
488
+ const stored = await physical();
489
+ expect(JSON.stringify(stored)).toBe(beforeLoadJSON);
490
+ expect(stored.operations).toHaveLength(1);
491
+ expect(stored.attempts).toHaveLength(1);
492
+ expect(stored.events).toHaveLength(0);
493
+ expect(stored.payloads).toHaveLength(1);
494
+ expect(stored.payloads[0].json).toBe(recordJSON);
495
+ expect(stored.operations[0].revision).toBe(1);
496
+ expect(stored.attempts[0]._id).toBe(expectedSummary.attemptId);
497
+ const documentBytes = Object.values(stored).flatMap((rows) =>
498
+ rows.map((doc) => getDocumentSize(doc)),
499
+ );
500
+ for (const size of documentBytes)
501
+ expect(size).toBeLessThanOrEqual(VALUE_LIMIT);
502
+ expect(fetchCalls()).toBe(0);
503
+ console.info(
504
+ "BTS317_LOAD_BOUNDARY",
505
+ JSON.stringify({
506
+ name,
507
+ canonicalCharacters: recordJSON.length,
508
+ canonicalUTF8Bytes: bytes,
509
+ creationArgsBytes: getConvexSize(creationArgs),
510
+ reserveArgsBytes: getConvexSize(reserveArgs),
511
+ acquiredBytes: getConvexSize(acquired),
512
+ loadedBytes: getConvexSize(loaded),
513
+ documentBytes,
514
+ counts: [1, 1, 0, 1],
515
+ fetchCalls: fetchCalls(),
516
+ }),
517
+ );
518
+ },
519
+ );
520
+
521
+ it("OWN01 unowned committed source payload refuses load without repair", async () => {
522
+ const { t, physical, fetchCalls } = fixture();
523
+ const { canonicalJSON: json, wireJSON } = wireRecord(base);
524
+ expect(canonicalJournalRecord(wireJSON).json).toBe(json);
525
+ const args = {
526
+ authorizationScope: base.authorization.scope,
527
+ logicalOperationId: base.logicalOperationId,
528
+ authorizationRevision: base.authorization.revision,
529
+ recordJSON: wireJSON,
530
+ };
531
+ const created = await t.mutation(create, args);
532
+ expect(created.status).toBe("created");
533
+ const queryArgs = { operationId: created.operationId };
534
+ const original = await t.query(load, queryArgs);
535
+ expect(original.recordJSON).toBe(json);
536
+ expect(JSON.parse(original.recordJSON)).toEqual(base);
537
+ const rows = await physical();
538
+ expect(rows.operations).toHaveLength(1);
539
+ expect(rows.payloads).toHaveLength(1);
540
+ const payloadId = rows.operations[0].payloadId;
541
+ expect(rows.payloads[0]._id).toBe(payloadId);
542
+ expect(rows.payloads[0].json).toBe(json);
543
+ // Controlled damaged fixture: preserve complete JSON, remove all owner data.
544
+ await t.run((ctx) =>
545
+ ctx.db.replace("renewalOperationPayloads", payloadId, {
546
+ codecVersion: 1,
547
+ json,
548
+ }),
549
+ );
550
+ const damaged = await physical();
551
+ expect(damaged.payloads[0].json).toBe(json);
552
+ expect(Object.keys(damaged.payloads[0]).sort()).toEqual([
553
+ "_creationTime",
554
+ "_id",
555
+ "codecVersion",
556
+ "json",
557
+ ]);
558
+ try {
559
+ await expect(t.query(load, queryArgs)).rejects.toThrow(
560
+ "RENEWAL_JOURNAL_CONFLICT",
561
+ );
562
+ } finally {
563
+ expect(JSON.stringify(await physical()) === JSON.stringify(damaged)).toBe(
564
+ true,
565
+ );
566
+ expect(fetchCalls()).toBe(0);
567
+ }
568
+ });
569
+ it("OWN02 parent abort rolls back registered create operation and payload", async () => {
570
+ const { t, physical, fetchCalls } = fixture();
571
+ const empty = await physical();
572
+ expect(Object.values(empty).map((rows) => rows.length)).toEqual([0, 0, 0, 0]);
573
+ const args = {
574
+ authorizationScope: base.authorization.scope,
575
+ logicalOperationId: base.logicalOperationId,
576
+ authorizationRevision: base.authorization.revision,
577
+ recordJSON: JSON.stringify(renewalSnapshot(base)),
578
+ };
579
+ let receivedCreated = false;
580
+ await expect(
581
+ t.mutation(async (ctx) => {
582
+ const reply = await ctx.runMutation(create, args);
583
+ expect(reply.status).toBe("created");
584
+ expect(typeof reply.operationId).toBe("string");
585
+ receivedCreated = true;
586
+ throw Error("OWN_PARENT_ABORT_AFTER_CREATED");
587
+ }),
588
+ ).rejects.toThrow("OWN_PARENT_ABORT_AFTER_CREATED");
589
+ expect(receivedCreated).toBe(true);
590
+ expect(await physical()).toEqual(empty);
591
+ expect(fetchCalls()).toBe(0);
592
+ });