@devlab.group/agent-commerce 2.5.0 → 2.7.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 (129) hide show
  1. package/README.md +78 -21
  2. package/dist/ap2.d.ts +19 -6
  3. package/dist/ap2.js +56 -18
  4. package/dist/ap2.js.map +1 -1
  5. package/dist/{chunk-ES3V6ECS.js → chunk-77HLISG4.js} +3 -2
  6. package/dist/chunk-77HLISG4.js.map +1 -0
  7. package/dist/{chunk-5ZYXBCDX.js → chunk-D7FPSGUQ.js} +25 -4
  8. package/dist/chunk-D7FPSGUQ.js.map +1 -0
  9. package/dist/{chunk-VUCMBGUR.js → chunk-DJRWYDKJ.js} +3 -3
  10. package/dist/{chunk-VUCMBGUR.js.map → chunk-DJRWYDKJ.js.map} +1 -1
  11. package/dist/{chunk-4K7FIBJM.js → chunk-EMKITGVV.js} +4 -4
  12. package/dist/chunk-EMKITGVV.js.map +1 -0
  13. package/dist/chunk-IWXVQYG5.js +6 -0
  14. package/dist/chunk-IWXVQYG5.js.map +1 -0
  15. package/dist/chunk-O3ACF45K.js +8 -0
  16. package/dist/chunk-O3ACF45K.js.map +1 -0
  17. package/dist/chunk-WDD2ZUR3.js +20 -0
  18. package/dist/chunk-WDD2ZUR3.js.map +1 -0
  19. package/dist/{chunk-3OTCFFFT.js → chunk-YHNTTMED.js} +7 -7
  20. package/dist/chunk-YHNTTMED.js.map +1 -0
  21. package/dist/{chunk-FKQK5XZA.js → chunk-ZSIUZPNB.js} +183 -80
  22. package/dist/chunk-ZSIUZPNB.js.map +1 -0
  23. package/dist/cli/{ap2-YAPLERSC.js → ap2-5FFGSW6F.js} +61 -25
  24. package/dist/cli/ap2-5FFGSW6F.js.map +1 -0
  25. package/dist/cli/{chunk-5K4XEAZV.js → chunk-3IEXJ7I3.js} +25 -4
  26. package/dist/cli/chunk-3IEXJ7I3.js.map +1 -0
  27. package/dist/cli/{chunk-NIU5EMSB.js → chunk-3NVJAQRO.js} +5 -5
  28. package/dist/cli/{chunk-NIU5EMSB.js.map → chunk-3NVJAQRO.js.map} +1 -1
  29. package/dist/cli/{chunk-IDY2735M.js → chunk-55AI6CLW.js} +6 -4
  30. package/dist/cli/chunk-55AI6CLW.js.map +1 -0
  31. package/dist/cli/{chunk-QA2OPHBF.js → chunk-5K2JDM4G.js} +185 -83
  32. package/dist/cli/chunk-5K2JDM4G.js.map +1 -0
  33. package/dist/cli/{chunk-QLUCNPRT.js → chunk-5TID36YG.js} +860 -170
  34. package/dist/cli/chunk-5TID36YG.js.map +1 -0
  35. package/dist/cli/{chunk-5R7DM5LM.js → chunk-66NTYSXI.js} +27 -27
  36. package/dist/cli/chunk-66NTYSXI.js.map +1 -0
  37. package/dist/cli/{chunk-VJ4EO4LE.js → chunk-6EBDOH37.js} +3 -3
  38. package/dist/cli/{chunk-VJ4EO4LE.js.map → chunk-6EBDOH37.js.map} +1 -1
  39. package/dist/cli/{chunk-4H2QLHQI.js → chunk-AGQ4U7IN.js} +5 -5
  40. package/dist/cli/chunk-AGQ4U7IN.js.map +1 -0
  41. package/dist/cli/chunk-APC5BTQM.js +6 -0
  42. package/dist/cli/chunk-APC5BTQM.js.map +1 -0
  43. package/dist/cli/{chunk-SYQLJXIU.js → chunk-C5YISPT6.js} +3 -3
  44. package/dist/cli/chunk-C5YISPT6.js.map +1 -0
  45. package/dist/cli/chunk-DKWO6LLX.js +34 -0
  46. package/dist/cli/chunk-DKWO6LLX.js.map +1 -0
  47. package/dist/cli/{chunk-SPAYKVUP.js → chunk-FL4HPCD4.js} +3 -2
  48. package/dist/cli/chunk-FL4HPCD4.js.map +1 -0
  49. package/dist/cli/{chunk-3EQBCFZY.js → chunk-H7EBJ4I3.js} +3 -3
  50. package/dist/cli/{chunk-3EQBCFZY.js.map → chunk-H7EBJ4I3.js.map} +1 -1
  51. package/dist/cli/{chunk-Z34UMZBB.js → chunk-OETKXDGA.js} +546 -175
  52. package/dist/cli/chunk-OETKXDGA.js.map +1 -0
  53. package/dist/cli/{chunk-JFVRG2HH.js → chunk-PLHPKXAT.js} +8 -8
  54. package/dist/cli/chunk-PLHPKXAT.js.map +1 -0
  55. package/dist/cli/{chunk-2UPPX3FJ.js → chunk-VSSSU4AU.js} +76 -14
  56. package/dist/cli/chunk-VSSSU4AU.js.map +1 -0
  57. package/dist/cli/chunk-ZCW56PZ3.js +8 -0
  58. package/dist/cli/{chunk-M7NXVRU5.js.map → chunk-ZCW56PZ3.js.map} +1 -1
  59. package/dist/cli/{chunk-2J2IQQ4X.js → chunk-ZFVQWOGG.js} +95 -42
  60. package/dist/cli/chunk-ZFVQWOGG.js.map +1 -0
  61. package/dist/cli/config-WT5HHDRR.js +13 -0
  62. package/dist/cli/{config-BWFMN2ZB.js.map → config-WT5HHDRR.js.map} +1 -1
  63. package/dist/cli/index.js +560 -252
  64. package/dist/cli/index.js.map +1 -1
  65. package/dist/cli/{mcp-KZEMXLHR.js → mcp-HHGNOUKE.js} +7 -7
  66. package/dist/cli/{mcp-KZEMXLHR.js.map → mcp-HHGNOUKE.js.map} +1 -1
  67. package/dist/cli/payment-providers-EWXZFBIE.js +6 -0
  68. package/dist/cli/{payment-providers-SZL36H3Y.js.map → payment-providers-EWXZFBIE.js.map} +1 -1
  69. package/dist/cli/{provider-6TKB5ADJ.js → provider-XUPLYNQ7.js} +36 -18
  70. package/dist/cli/provider-XUPLYNQ7.js.map +1 -0
  71. package/dist/cli/receipts-3DSV4DIK.js +9 -0
  72. package/dist/cli/{receipts-ZGLJWMQG.js.map → receipts-3DSV4DIK.js.map} +1 -1
  73. package/dist/cli/reconcile-GS25MQ42.js +4 -0
  74. package/dist/cli/{reconcile-IC22MJD5.js.map → reconcile-GS25MQ42.js.map} +1 -1
  75. package/dist/cli/{run-ZTYPQI4D.js → run-7KLKW3HE.js} +310 -91
  76. package/dist/cli/run-7KLKW3HE.js.map +1 -0
  77. package/dist/cli/{x402-WLYBLODI.js → x402-HP4E3QET.js} +11 -10
  78. package/dist/cli/x402-HP4E3QET.js.map +1 -0
  79. package/dist/{guardrails-CX_jYXvZ.d.ts → guardrails-CeyLS1ou.d.ts} +2 -2
  80. package/dist/index.d.ts +119 -206
  81. package/dist/index.js +1703 -427
  82. package/dist/index.js.map +1 -1
  83. package/dist/logger-CllGwQ8i.d.ts +19 -0
  84. package/dist/mcp.d.ts +3 -1
  85. package/dist/mcp.js +4 -3
  86. package/dist/mcp.js.map +1 -1
  87. package/dist/mpp.d.ts +2 -1
  88. package/dist/mpp.js +32 -13
  89. package/dist/mpp.js.map +1 -1
  90. package/dist/{protocol-adapter-DEXpdp8m.d.ts → protocol-adapter-DdFL5LBU.d.ts} +15 -132
  91. package/dist/{runtime-Dz2fSO-P.d.ts → runtime-BmaSp2Ce.d.ts} +36 -23
  92. package/dist/store-BVvMzpuV.d.ts +389 -0
  93. package/dist/testing.d.ts +51 -0
  94. package/dist/testing.js +2050 -0
  95. package/dist/testing.js.map +1 -0
  96. package/dist/transaction-BXXJltZ-.d.ts +129 -0
  97. package/dist/{types-j7MnUXYN.d.ts → types-DWqjz81-.d.ts} +5 -2
  98. package/dist/x402.d.ts +9 -3
  99. package/dist/x402.js +7 -5
  100. package/dist/x402.js.map +1 -1
  101. package/package.json +17 -29
  102. package/dist/chunk-3OTCFFFT.js.map +0 -1
  103. package/dist/chunk-4K7FIBJM.js.map +0 -1
  104. package/dist/chunk-5ZYXBCDX.js.map +0 -1
  105. package/dist/chunk-ES3V6ECS.js.map +0 -1
  106. package/dist/chunk-FKQK5XZA.js.map +0 -1
  107. package/dist/cli/ap2-YAPLERSC.js.map +0 -1
  108. package/dist/cli/chunk-2J2IQQ4X.js.map +0 -1
  109. package/dist/cli/chunk-2UPPX3FJ.js.map +0 -1
  110. package/dist/cli/chunk-4H2QLHQI.js.map +0 -1
  111. package/dist/cli/chunk-5K4XEAZV.js.map +0 -1
  112. package/dist/cli/chunk-5R7DM5LM.js.map +0 -1
  113. package/dist/cli/chunk-FHCFR2GS.js +0 -17
  114. package/dist/cli/chunk-FHCFR2GS.js.map +0 -1
  115. package/dist/cli/chunk-IDY2735M.js.map +0 -1
  116. package/dist/cli/chunk-JFVRG2HH.js.map +0 -1
  117. package/dist/cli/chunk-M7NXVRU5.js +0 -8
  118. package/dist/cli/chunk-QA2OPHBF.js.map +0 -1
  119. package/dist/cli/chunk-QLUCNPRT.js.map +0 -1
  120. package/dist/cli/chunk-SPAYKVUP.js.map +0 -1
  121. package/dist/cli/chunk-SYQLJXIU.js.map +0 -1
  122. package/dist/cli/chunk-Z34UMZBB.js.map +0 -1
  123. package/dist/cli/config-BWFMN2ZB.js +0 -12
  124. package/dist/cli/payment-providers-SZL36H3Y.js +0 -6
  125. package/dist/cli/provider-6TKB5ADJ.js.map +0 -1
  126. package/dist/cli/receipts-ZGLJWMQG.js +0 -8
  127. package/dist/cli/reconcile-IC22MJD5.js +0 -4
  128. package/dist/cli/run-ZTYPQI4D.js.map +0 -1
  129. package/dist/cli/x402-WLYBLODI.js.map +0 -1
@@ -1,9 +1,446 @@
1
- import { openSqliteDatabase } from './chunk-VJ4EO4LE.js';
2
- import { PACKAGE_VERSION } from './chunk-M7NXVRU5.js';
3
- import { NOOP_LOGGER, systemClock, transactionState } from './chunk-IDY2735M.js';
4
- import { toCommerceError, CommerceError } from './chunk-SYQLJXIU.js';
1
+ import { openSqliteDatabase } from './chunk-6EBDOH37.js';
2
+ import { PAYMENT_KEY_ENDPOINT_PREFIX } from './chunk-APC5BTQM.js';
3
+ import { PACKAGE_VERSION } from './chunk-ZCW56PZ3.js';
4
+ import { NOOP_LOGGER, systemClock, transactionState, RESERVED_INPUT_FIELDS } from './chunk-55AI6CLW.js';
5
+ import { CommerceError, toCommerceError } from './chunk-C5YISPT6.js';
6
+ import { isRecord } from './chunk-3M6U7ILB.js';
7
+ import { accessSync, constants, existsSync } from 'fs';
8
+ import { resolve } from 'path';
9
+ import Database from 'better-sqlite3';
5
10
  import { randomUUID } from 'crypto';
6
- import { accessSync, constants } from 'fs';
11
+
12
+ // src/storage/receipts/schema.ts
13
+ var MIGRATIONS = [
14
+ {
15
+ version: 1,
16
+ up(db) {
17
+ db.exec(`
18
+ CREATE TABLE IF NOT EXISTS receipts (
19
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
20
+ id TEXT NOT NULL UNIQUE,
21
+ request_id TEXT NOT NULL,
22
+ resource_id TEXT NOT NULL,
23
+ payment_json TEXT,
24
+ delivered_at TEXT NOT NULL,
25
+ backend_status INTEGER NOT NULL,
26
+ duration_ms INTEGER,
27
+ protocol TEXT,
28
+ metadata_json TEXT
29
+ );
30
+ CREATE INDEX IF NOT EXISTS idx_receipts_request_id ON receipts(request_id);
31
+ CREATE INDEX IF NOT EXISTS idx_receipts_delivered_at ON receipts(delivered_at);
32
+
33
+ CREATE TABLE IF NOT EXISTS events (
34
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
35
+ id TEXT NOT NULL UNIQUE,
36
+ type TEXT NOT NULL,
37
+ request_id TEXT NOT NULL,
38
+ resource_id TEXT,
39
+ at TEXT NOT NULL,
40
+ adapter TEXT,
41
+ payment_provider TEXT,
42
+ duration_ms INTEGER,
43
+ status TEXT,
44
+ data_json TEXT
45
+ );
46
+ CREATE INDEX IF NOT EXISTS idx_events_request_id ON events(request_id);
47
+ CREATE INDEX IF NOT EXISTS idx_events_at ON events(at);
48
+
49
+ CREATE TABLE IF NOT EXISTS payment_attempts (
50
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
51
+ id TEXT NOT NULL UNIQUE,
52
+ request_id TEXT NOT NULL,
53
+ resource_id TEXT NOT NULL,
54
+ provider TEXT NOT NULL,
55
+ replay_key TEXT NOT NULL UNIQUE,
56
+ status TEXT NOT NULL,
57
+ amount TEXT NOT NULL,
58
+ currency TEXT NOT NULL,
59
+ payer TEXT,
60
+ payee TEXT,
61
+ external_reference TEXT,
62
+ rejection_reason TEXT,
63
+ created_at TEXT NOT NULL,
64
+ updated_at TEXT NOT NULL
65
+ );
66
+ CREATE INDEX IF NOT EXISTS idx_payment_attempts_request_id ON payment_attempts(request_id);
67
+ CREATE INDEX IF NOT EXISTS idx_payment_attempts_created_at ON payment_attempts(created_at);
68
+ `);
69
+ }
70
+ },
71
+ {
72
+ version: 2,
73
+ up(db) {
74
+ db.exec(`ALTER TABLE receipts ADD COLUMN authorization_json TEXT;`);
75
+ }
76
+ },
77
+ {
78
+ version: 3,
79
+ up(db) {
80
+ db.exec(`
81
+ CREATE TABLE IF NOT EXISTS payment_attempt_history (
82
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
83
+ id TEXT NOT NULL,
84
+ request_id TEXT NOT NULL,
85
+ resource_id TEXT NOT NULL,
86
+ provider TEXT NOT NULL,
87
+ replay_key TEXT NOT NULL,
88
+ status TEXT NOT NULL,
89
+ amount TEXT NOT NULL,
90
+ currency TEXT NOT NULL,
91
+ payer TEXT,
92
+ payee TEXT,
93
+ external_reference TEXT,
94
+ rejection_reason TEXT,
95
+ created_at TEXT NOT NULL,
96
+ updated_at TEXT NOT NULL,
97
+ superseded_at TEXT NOT NULL
98
+ );
99
+ CREATE INDEX IF NOT EXISTS idx_payment_attempt_history_replay_key ON payment_attempt_history(replay_key);
100
+ CREATE INDEX IF NOT EXISTS idx_payment_attempt_history_request_id ON payment_attempt_history(request_id);
101
+ `);
102
+ }
103
+ },
104
+ {
105
+ version: 4,
106
+ up(db) {
107
+ db.exec(`
108
+ CREATE TABLE IF NOT EXISTS transactions (
109
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
110
+ id TEXT NOT NULL UNIQUE,
111
+ request_id TEXT NOT NULL,
112
+ resource_id TEXT NOT NULL,
113
+ protocol TEXT NOT NULL,
114
+ state TEXT NOT NULL,
115
+ provider TEXT NOT NULL,
116
+ attempt_id TEXT NOT NULL,
117
+ replay_key TEXT NOT NULL,
118
+ network TEXT,
119
+ asset TEXT,
120
+ authorization_json TEXT,
121
+ reservation_id TEXT,
122
+ locator_json TEXT,
123
+ expires_at TEXT,
124
+ input_digest TEXT,
125
+ config_digest TEXT NOT NULL,
126
+ settling_at TEXT,
127
+ backend_dispatched_at TEXT,
128
+ backend_deadline_at TEXT,
129
+ backend_status INTEGER,
130
+ backend_error_code TEXT,
131
+ receipt_id TEXT,
132
+ persistence_failures_json TEXT,
133
+ completed_at TEXT,
134
+ created_at TEXT NOT NULL,
135
+ updated_at TEXT NOT NULL
136
+ );
137
+ CREATE INDEX IF NOT EXISTS idx_transactions_state_seq ON transactions(state, seq);
138
+ CREATE INDEX IF NOT EXISTS idx_transactions_request_id ON transactions(request_id);
139
+ CREATE INDEX IF NOT EXISTS idx_transactions_replay_key ON transactions(replay_key);
140
+
141
+ ALTER TABLE receipts ADD COLUMN transaction_id TEXT;
142
+ ALTER TABLE events ADD COLUMN transaction_id TEXT;
143
+ ALTER TABLE payment_attempts ADD COLUMN transaction_id TEXT;
144
+ ALTER TABLE payment_attempts ADD COLUMN resolution_json TEXT;
145
+ ALTER TABLE payment_attempt_history ADD COLUMN transaction_id TEXT;
146
+ ALTER TABLE payment_attempt_history ADD COLUMN resolution_json TEXT;
147
+ CREATE INDEX IF NOT EXISTS idx_payment_attempt_history_id ON payment_attempt_history(id);
148
+ `);
149
+ }
150
+ },
151
+ {
152
+ version: 5,
153
+ up(db) {
154
+ db.exec(`
155
+ CREATE TABLE IF NOT EXISTS authorization_holds (
156
+ reference TEXT PRIMARY KEY,
157
+ method TEXT NOT NULL,
158
+ binding_reference TEXT NOT NULL,
159
+ resource_id TEXT NOT NULL,
160
+ request_id TEXT NOT NULL,
161
+ state TEXT NOT NULL
162
+ CHECK (state IN ('reserved', 'consumed', 'released', 'uncertain')),
163
+ metadata_json TEXT,
164
+ created_at TEXT NOT NULL,
165
+ updated_at TEXT NOT NULL
166
+ );
167
+ CREATE INDEX IF NOT EXISTS idx_authorization_holds_binding ON authorization_holds(binding_reference);
168
+ CREATE INDEX IF NOT EXISTS idx_authorization_holds_request_id ON authorization_holds(request_id);
169
+ CREATE INDEX IF NOT EXISTS idx_authorization_holds_state_updated ON authorization_holds(state, updated_at);
170
+
171
+ CREATE TABLE IF NOT EXISTS idempotency_keys (
172
+ deployment TEXT NOT NULL,
173
+ endpoint TEXT NOT NULL,
174
+ idempotency_key TEXT NOT NULL,
175
+ fingerprint TEXT NOT NULL,
176
+ state TEXT NOT NULL,
177
+ status INTEGER,
178
+ body_json TEXT,
179
+ created_at TEXT NOT NULL,
180
+ expires_at TEXT NOT NULL,
181
+ PRIMARY KEY (deployment, endpoint, idempotency_key)
182
+ );
183
+ CREATE INDEX IF NOT EXISTS idx_idempotency_keys_expires_at ON idempotency_keys(expires_at);
184
+
185
+ CREATE TABLE IF NOT EXISTS pending_tasks (
186
+ id TEXT PRIMARY KEY,
187
+ protocol TEXT NOT NULL,
188
+ resource_id TEXT NOT NULL,
189
+ input_json TEXT NOT NULL,
190
+ adapter_data_json TEXT,
191
+ created_at TEXT NOT NULL,
192
+ expires_at TEXT NOT NULL
193
+ );
194
+ CREATE INDEX IF NOT EXISTS idx_pending_tasks_expires_at ON pending_tasks(expires_at);
195
+
196
+ -- path is NULL when the feature started with nothing to import
197
+ CREATE TABLE IF NOT EXISTS legacy_imports (
198
+ source TEXT PRIMARY KEY,
199
+ path TEXT,
200
+ rows INTEGER NOT NULL,
201
+ imported_at TEXT NOT NULL
202
+ );
203
+ `);
204
+ }
205
+ }
206
+ ];
207
+ var SCHEMA_VERSION = MIGRATIONS.at(-1)?.version ?? 0;
208
+ function hasTable(db, name) {
209
+ return db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name) !== void 0;
210
+ }
211
+ function migrate(db, target = SCHEMA_VERSION) {
212
+ const current = db.pragma("user_version", { simple: true });
213
+ for (const migration of MIGRATIONS) {
214
+ if (migration.version <= current || migration.version > target) continue;
215
+ const apply = db.transaction(() => {
216
+ migration.up(db);
217
+ db.pragma(`user_version = ${migration.version}`);
218
+ });
219
+ apply();
220
+ }
221
+ }
222
+
223
+ // src/storage/receipts/legacy-import.ts
224
+ var NOTHING = { rows: 0, write: () => {
225
+ } };
226
+ var SOURCES = [
227
+ {
228
+ name: "ap2-replay",
229
+ option: "ap2Replay",
230
+ feature: "ap2",
231
+ key: "authorization.ap2.replay.path",
232
+ usedSql: `SELECT 1 FROM receipts WHERE authorization_json IS NOT NULL
233
+ UNION ALL SELECT 1 FROM transactions WHERE authorization_json IS NOT NULL LIMIT 1`,
234
+ read(file) {
235
+ if (!hasTable(file, "ap2_authorizations")) return NOTHING;
236
+ const rows = file.prepare(
237
+ `SELECT reference, checkout_jti, mandate_issuer, checkout_issuer, resource_id,
238
+ request_id, state, created_at, updated_at
239
+ FROM ap2_authorizations`
240
+ ).all();
241
+ return {
242
+ rows: rows.length,
243
+ write(db) {
244
+ const insert = db.prepare(
245
+ `INSERT INTO authorization_holds
246
+ (reference, method, binding_reference, resource_id, request_id, state,
247
+ metadata_json, created_at, updated_at)
248
+ VALUES (@reference, 'ap2', @checkout_jti, @resource_id, @request_id, @state,
249
+ @metadata_json, @created_at, @updated_at)
250
+ ON CONFLICT (reference) DO UPDATE SET
251
+ binding_reference = excluded.binding_reference, resource_id = excluded.resource_id,
252
+ request_id = excluded.request_id, state = excluded.state,
253
+ metadata_json = excluded.metadata_json, updated_at = excluded.updated_at
254
+ WHERE authorization_holds.state = 'released'`
255
+ );
256
+ for (const row of rows) {
257
+ insert.run({
258
+ ...row,
259
+ metadata_json: JSON.stringify({
260
+ mandateIssuer: row.mandate_issuer,
261
+ checkoutIssuer: row.checkout_issuer
262
+ })
263
+ });
264
+ }
265
+ }
266
+ };
267
+ }
268
+ },
269
+ {
270
+ name: "acp-idempotency",
271
+ option: "acpIdempotency",
272
+ feature: "acp",
273
+ key: "protocols.acp.idempotency.path",
274
+ usedSql: "SELECT 1 FROM events WHERE adapter = 'acp' LIMIT 1",
275
+ read(file, logger) {
276
+ if (!hasTable(file, "acp_idempotency")) return NOTHING;
277
+ if (file.pragma("user_version", { simple: true }) < 2) {
278
+ const { count } = file.prepare("SELECT COUNT(*) AS count FROM acp_idempotency WHERE state != 'completed'").get();
279
+ if (count > 0) {
280
+ logger.warn(
281
+ { unresolved: count },
282
+ "acp idempotency: the schema v1 file holds claims keyed by an old bearer-token digest, which are not imported; reconcile these operations against the merchant before trusting a retry"
283
+ );
284
+ }
285
+ return NOTHING;
286
+ }
287
+ const rows = file.prepare(
288
+ `SELECT deployment, endpoint, idempotency_key, fingerprint, state, status, body_json,
289
+ created_at, expires_at
290
+ FROM acp_idempotency`
291
+ ).all();
292
+ return {
293
+ rows: rows.length,
294
+ write(db) {
295
+ const insert = db.prepare(
296
+ `INSERT INTO idempotency_keys
297
+ (deployment, endpoint, idempotency_key, fingerprint, state, status, body_json,
298
+ created_at, expires_at)
299
+ VALUES (@deployment, @endpoint, @idempotency_key, @fingerprint, @state, @status,
300
+ @body_json, @created_at, @expires_at)
301
+ ON CONFLICT DO NOTHING`
302
+ );
303
+ for (const row of rows) insert.run(row);
304
+ }
305
+ };
306
+ }
307
+ }
308
+ ];
309
+ function storageError(message, details, cause) {
310
+ return new CommerceError("STORAGE_ERROR", message, { details, cause });
311
+ }
312
+ function selectMarker(db, source) {
313
+ return db.prepare("SELECT path FROM legacy_imports WHERE source = ?").get(source);
314
+ }
315
+ var usedBefore = (db, source) => db.prepare(source.usedSql).get() !== void 0;
316
+ function missingLegacyImports(db) {
317
+ const recorded = hasTable(db, "legacy_imports");
318
+ return SOURCES.filter(
319
+ (source) => !(recorded && selectMarker(db, source.name) !== void 0) && usedBefore(db, source)
320
+ ).map((source) => source.name);
321
+ }
322
+ function readMissingLegacyImports(path) {
323
+ let db;
324
+ try {
325
+ db = new Database(path, { readonly: true, fileMustExist: true });
326
+ return missingLegacyImports(db);
327
+ } catch {
328
+ return void 0;
329
+ } finally {
330
+ db?.close();
331
+ }
332
+ }
333
+ function importLegacyStores(db, receiptsPath, options, clock, logger) {
334
+ const recordMarker = db.prepare(
335
+ `INSERT INTO legacy_imports (source, path, rows, imported_at) VALUES (?, ?, ?, ?)
336
+ ON CONFLICT (source) DO UPDATE SET
337
+ path = excluded.path, rows = excluded.rows, imported_at = excluded.imported_at`
338
+ );
339
+ const locks = [];
340
+ const release = () => {
341
+ for (const lock of locks.splice(0)) lock.close();
342
+ };
343
+ try {
344
+ for (const source of SOURCES) {
345
+ const given = options[source.option];
346
+ const marker = selectMarker(db, source.name);
347
+ const importedPath = marker?.path ?? void 0;
348
+ const path = given !== void 0 && given !== ":memory:" ? resolve(given) : void 0;
349
+ if (path !== void 0 && receiptsPath !== ":memory:" && path === resolve(receiptsPath)) {
350
+ throw storageError(`${source.key} names the receipt database "${path}"`, {
351
+ key: source.key,
352
+ path
353
+ });
354
+ }
355
+ if (path !== void 0 && importedPath !== void 0 && importedPath !== path) {
356
+ throw storageError(
357
+ `${source.key} names "${path}", but "${importedPath}" was imported from it already. Point ${source.key} back at the imported file, or remove the key.`,
358
+ { key: source.key, path, importedPath }
359
+ );
360
+ }
361
+ if (path === void 0 || !existsSync(path)) {
362
+ if (marker === void 0 && options.enabled?.[source.feature] === true) {
363
+ if (given !== ":memory:" && usedBefore(db, source)) {
364
+ throw forgottenKey(source, path);
365
+ }
366
+ recordMarker.run(source.name, null, 0, clock.nowIso());
367
+ }
368
+ if (given !== void 0) {
369
+ logger.info(
370
+ { key: source.key, path: path ?? given },
371
+ "deprecated store has no file to import; the key can be removed"
372
+ );
373
+ }
374
+ continue;
375
+ }
376
+ let file;
377
+ try {
378
+ file = new Database(path, { fileMustExist: true });
379
+ file.exec("BEGIN EXCLUSIVE");
380
+ } catch (cause) {
381
+ file?.close();
382
+ const cantOpen = cause.code === "SQLITE_CANTOPEN";
383
+ if (importedPath !== void 0 && cantOpen) {
384
+ logger.warn(
385
+ { key: source.key, path },
386
+ "deprecated store file cannot be opened to lock it; its rows are already imported"
387
+ );
388
+ continue;
389
+ }
390
+ throw storageError(
391
+ cantOpen ? `${source.key} "${path}" cannot be opened to import it, as on a read-only mount. Make its directory writable for the first start of this version, or copy the file somewhere writable and point the key at the copy.` : `${source.key} "${path}" cannot be locked for import: ${cause instanceof Error ? cause.message : String(cause)}`,
392
+ { key: source.key, path },
393
+ cause
394
+ );
395
+ }
396
+ locks.push(file);
397
+ if (importedPath !== void 0) continue;
398
+ let imported;
399
+ try {
400
+ imported = source.read(file, logger);
401
+ } catch (cause) {
402
+ throw storageError(
403
+ `${source.key} "${path}" cannot be read for import: ${cause instanceof Error ? cause.message : String(cause)}`,
404
+ { key: source.key, path },
405
+ cause
406
+ );
407
+ }
408
+ db.transaction(() => {
409
+ imported.write(db);
410
+ recordMarker.run(source.name, path, imported.rows, clock.nowIso());
411
+ })();
412
+ logger.info(
413
+ { key: source.key, path, rows: imported.rows },
414
+ "imported deprecated store file; it stays locked against writes while this gateway runs"
415
+ );
416
+ }
417
+ } catch (err) {
418
+ release();
419
+ throw toCommerceError(err, "STORAGE_ERROR", "Failed to import deprecated store files");
420
+ }
421
+ return release;
422
+ }
423
+ function forgottenKey(source, path) {
424
+ return storageError(
425
+ `${source.feature.toUpperCase()} ran on this receipt database before, but ${source.key} ${path === void 0 ? "is not set" : `names a missing file "${path}"`}, so its records would be lost. Set ${source.key} to the file the previous version used to import them, or to an empty file to accept the loss.`,
426
+ { key: source.key, ...path !== void 0 ? { path } : {} }
427
+ );
428
+ }
429
+
430
+ // src/storage/receipts/params.ts
431
+ var DEFAULT_LIST_LIMIT = 50;
432
+ var MAX_LIST_LIMIT = 500;
433
+ function clampListLimit(limit) {
434
+ const base = limit !== void 0 && Number.isFinite(limit) ? limit : DEFAULT_LIST_LIMIT;
435
+ return Math.min(Math.max(Math.trunc(base), 1), MAX_LIST_LIMIT);
436
+ }
437
+ function storedIso(value, field) {
438
+ const ms = Date.parse(value);
439
+ if (!Number.isFinite(ms)) {
440
+ throw new CommerceError("STORAGE_ERROR", `${field} is not a valid timestamp`);
441
+ }
442
+ return new Date(ms).toISOString();
443
+ }
7
444
 
8
445
  // src/storage/receipts/redact.ts
9
446
  var SECRET_KEY_PATTERN = /private[-_ ]?key|secret|password|mnemonic|seed[-_ ]?phrase|api[-_ ]?key|authoriz(e|ation)|^auth$|auth[-_]?header|payment[-_ ]?proof|^proof$|x-payment|signature|signed[-_ ]?message|token|bearer|credential|cookie|session|jwt/i;
@@ -28,6 +465,311 @@ function redactValue(value) {
28
465
  return value;
29
466
  }
30
467
 
468
+ // src/storage/receipts/holds.ts
469
+ var TRANSITION_TARGETS = /* @__PURE__ */ new Set(["consumed", "released", "uncertain"]);
470
+ var ORPHAN_HOLD_WHERE = `h.state = 'reserved' AND h.updated_at < ?
471
+ AND NOT EXISTS (SELECT 1 FROM payment_attempts a WHERE a.request_id = h.request_id)
472
+ AND NOT EXISTS (SELECT 1 FROM payment_attempt_history p WHERE p.request_id = h.request_id)`;
473
+ function rowToHold(row) {
474
+ return {
475
+ method: row.method,
476
+ reference: row.reference,
477
+ bindingReference: row.binding_reference,
478
+ resourceId: row.resource_id,
479
+ requestId: row.request_id,
480
+ ...row.metadata_json !== null ? { metadata: JSON.parse(row.metadata_json) } : {},
481
+ state: row.state,
482
+ createdAt: row.created_at,
483
+ updatedAt: row.updated_at
484
+ };
485
+ }
486
+ function createHoldMethods(db, clock) {
487
+ const selectHold = db.prepare(
488
+ "SELECT * FROM authorization_holds WHERE reference = ?"
489
+ );
490
+ const selectLiveBinding = db.prepare(
491
+ `SELECT state FROM authorization_holds
492
+ WHERE binding_reference = ? AND reference != ? AND state != 'released' LIMIT 1`
493
+ );
494
+ const insertHold = db.prepare(
495
+ `INSERT INTO authorization_holds
496
+ (reference, method, binding_reference, resource_id, request_id, state, metadata_json, created_at, updated_at)
497
+ VALUES (@reference, @method, @binding_reference, @resource_id, @request_id, 'reserved', @metadata_json, @at, @at)`
498
+ );
499
+ const reReserveHold = db.prepare(
500
+ `UPDATE authorization_holds
501
+ SET state = 'reserved', method = @method, binding_reference = @binding_reference,
502
+ resource_id = @resource_id, request_id = @request_id,
503
+ metadata_json = @metadata_json, updated_at = @at
504
+ WHERE reference = @reference AND state = 'released'`
505
+ );
506
+ const transitionHold = db.prepare(
507
+ `UPDATE authorization_holds SET state = @state, updated_at = @at
508
+ WHERE reference = @reference AND state IN ('reserved', 'uncertain')
509
+ AND (@request_id IS NULL OR request_id = @request_id)`
510
+ );
511
+ const listOrphans = db.prepare(
512
+ `SELECT h.* FROM authorization_holds h WHERE ${ORPHAN_HOLD_WHERE}
513
+ ORDER BY h.updated_at, h.reference LIMIT ?`
514
+ );
515
+ const reserve = db.transaction(
516
+ (reservation) => {
517
+ const existing = selectHold.get(reservation.reference);
518
+ if (existing !== void 0 && existing.state !== "released") {
519
+ return { kind: "replayed", state: existing.state };
520
+ }
521
+ const binding = selectLiveBinding.get(reservation.bindingReference, reservation.reference);
522
+ if (binding !== void 0) {
523
+ return { kind: "replayed", state: binding.state };
524
+ }
525
+ const params = {
526
+ reference: reservation.reference,
527
+ method: reservation.method,
528
+ binding_reference: reservation.bindingReference,
529
+ resource_id: reservation.resourceId,
530
+ request_id: reservation.requestId,
531
+ metadata_json: reservation.metadata !== void 0 ? JSON.stringify(redact(reservation.metadata)) : null,
532
+ at: clock.nowIso()
533
+ };
534
+ (existing !== void 0 ? reReserveHold : insertHold).run(params);
535
+ return { kind: "reserved" };
536
+ }
537
+ );
538
+ const transition = db.transaction(
539
+ (reference, to, requestId) => {
540
+ const { changes } = transitionHold.run({
541
+ reference,
542
+ state: to,
543
+ request_id: requestId ?? null,
544
+ at: clock.nowIso()
545
+ });
546
+ if (changes > 0) return true;
547
+ const row = selectHold.get(reference);
548
+ if (row === void 0) return false;
549
+ if (requestId !== void 0 && row.request_id !== requestId) return to === "released";
550
+ return row.state === to;
551
+ }
552
+ );
553
+ return {
554
+ async reserveAuthorizationHold(reservation) {
555
+ try {
556
+ return reserve.immediate(reservation);
557
+ } catch (err) {
558
+ throw toCommerceError(err, "STORAGE_ERROR", "Failed to reserve authorization hold");
559
+ }
560
+ },
561
+ async transitionAuthorizationHold(reference, to, requestId) {
562
+ try {
563
+ if (!TRANSITION_TARGETS.has(to)) {
564
+ throw new CommerceError("STORAGE_ERROR", `Invalid authorization hold target: ${to}`);
565
+ }
566
+ return transition.immediate(reference, to, requestId);
567
+ } catch (err) {
568
+ throw toCommerceError(err, "STORAGE_ERROR", "Failed to update authorization hold");
569
+ }
570
+ },
571
+ async getAuthorizationHoldState(reference) {
572
+ return selectHold.get(reference)?.state;
573
+ },
574
+ async listOrphanAuthorizationHolds(options) {
575
+ const before = storedIso(options.updatedBefore, "updatedBefore");
576
+ return listOrphans.all(before, clampListLimit(options.limit)).map(rowToHold);
577
+ }
578
+ };
579
+ }
580
+
581
+ // src/storage/receipts/idempotency.ts
582
+ var ENDPOINT_HAS_PREFIX = "substr(endpoint, 1, length(@prefix)) = @prefix";
583
+ var scopeParams = (scope) => ({
584
+ deployment: scope.deployment,
585
+ endpoint: scope.endpoint,
586
+ idempotency_key: scope.key
587
+ });
588
+ function claimOf(row, fingerprint) {
589
+ if (row.fingerprint !== fingerprint) return { kind: "conflict" };
590
+ const body = row.body_json === null ? null : JSON.parse(row.body_json);
591
+ if (row.state === "completed") return { kind: "replay", status: row.status ?? 500, body };
592
+ const kind = row.state === "unresolved" ? "unresolved" : "in-flight";
593
+ const owner = isRecord(body) ? body["owner"] : void 0;
594
+ return typeof owner === "string" ? { kind, owner } : { kind };
595
+ }
596
+ function hasExpired(row, endpoint, now) {
597
+ if (row.expires_at > now) return false;
598
+ return row.state === "completed" || row.state === "unresolved" && endpoint.startsWith(PAYMENT_KEY_ENDPOINT_PREFIX);
599
+ }
600
+ function createIdempotencyMethods(db, clock) {
601
+ const SCOPE = "deployment = @deployment AND endpoint = @endpoint AND idempotency_key = @idempotency_key";
602
+ const selectClaim = db.prepare(
603
+ `SELECT state, fingerprint, status, body_json, expires_at FROM idempotency_keys WHERE ${SCOPE}`
604
+ );
605
+ const insertClaim = db.prepare(
606
+ `INSERT INTO idempotency_keys
607
+ (deployment, endpoint, idempotency_key, fingerprint, state, body_json, created_at, expires_at)
608
+ VALUES (@deployment, @endpoint, @idempotency_key, @fingerprint, 'in_flight', @body_json, @created_at, @expires_at)`
609
+ );
610
+ const expireFinished = db.prepare(
611
+ `DELETE FROM idempotency_keys WHERE expires_at <= @now
612
+ AND (state = 'completed' OR (state = 'unresolved' AND ${ENDPOINT_HAS_PREFIX}))`
613
+ );
614
+ const completeClaim = db.prepare(
615
+ `UPDATE idempotency_keys SET state = 'completed', status = @status, body_json = @body_json
616
+ WHERE ${SCOPE}`
617
+ );
618
+ const markUnresolved = db.prepare(
619
+ `UPDATE idempotency_keys SET state = 'unresolved' WHERE ${SCOPE}`
620
+ );
621
+ const deleteClaim = db.prepare(`DELETE FROM idempotency_keys WHERE ${SCOPE}`);
622
+ const IN_FLIGHT = `state = 'in_flight' AND ${ENDPOINT_HAS_PREFIX}`;
623
+ const releaseInFlight = db.prepare(`DELETE FROM idempotency_keys WHERE ${IN_FLIGHT}`);
624
+ const unresolveInFlight = db.prepare(
625
+ `UPDATE idempotency_keys SET state = 'unresolved' WHERE ${IN_FLIGHT}`
626
+ );
627
+ const claim = db.transaction(
628
+ (scope, fingerprint, expiresAt, owner) => {
629
+ const now = clock.nowIso();
630
+ expireFinished.run({ now, prefix: PAYMENT_KEY_ENDPOINT_PREFIX });
631
+ const existing = selectClaim.get(scopeParams(scope));
632
+ if (existing === void 0) {
633
+ insertClaim.run({
634
+ ...scopeParams(scope),
635
+ fingerprint,
636
+ body_json: owner !== void 0 ? JSON.stringify({ owner }) : null,
637
+ created_at: now,
638
+ expires_at: expiresAt
639
+ });
640
+ return { kind: "reserved" };
641
+ }
642
+ return claimOf(existing, fingerprint);
643
+ }
644
+ );
645
+ return {
646
+ async claimIdempotencyKey(scope, fingerprint, expiresAt, owner) {
647
+ try {
648
+ return claim.immediate(scope, fingerprint, storedIso(expiresAt, "expiresAt"), owner);
649
+ } catch (err) {
650
+ throw toCommerceError(err, "STORAGE_ERROR", "Failed to claim idempotency key");
651
+ }
652
+ },
653
+ async getIdempotencyKey(scope, fingerprint) {
654
+ try {
655
+ const existing = selectClaim.get(scopeParams(scope));
656
+ if (existing === void 0) return void 0;
657
+ return hasExpired(existing, scope.endpoint, clock.nowIso()) ? void 0 : claimOf(existing, fingerprint);
658
+ } catch (err) {
659
+ throw toCommerceError(err, "STORAGE_ERROR", "Failed to read idempotency key");
660
+ }
661
+ },
662
+ async updateIdempotencyKey(scope, update) {
663
+ try {
664
+ switch (update.kind) {
665
+ case "completed":
666
+ completeClaim.run({
667
+ ...scopeParams(scope),
668
+ status: update.status,
669
+ body_json: JSON.stringify(update.body ?? null)
670
+ });
671
+ break;
672
+ case "unresolved":
673
+ markUnresolved.run(scopeParams(scope));
674
+ break;
675
+ case "released":
676
+ deleteClaim.run(scopeParams(scope));
677
+ break;
678
+ }
679
+ } catch (err) {
680
+ throw toCommerceError(err, "STORAGE_ERROR", "Failed to update idempotency key");
681
+ }
682
+ },
683
+ async recoverIdempotencyKeys({ release, endpointPrefix = "" }) {
684
+ try {
685
+ const recover = release ? releaseInFlight : unresolveInFlight;
686
+ return recover.run({ prefix: endpointPrefix }).changes;
687
+ } catch (err) {
688
+ throw toCommerceError(err, "STORAGE_ERROR", "Failed to recover idempotency keys");
689
+ }
690
+ }
691
+ };
692
+ }
693
+
694
+ // src/storage/receipts/pending-tasks.ts
695
+ function rowToTask(row) {
696
+ return {
697
+ id: row.id,
698
+ protocol: row.protocol,
699
+ resourceId: row.resource_id,
700
+ input: JSON.parse(row.input_json),
701
+ ...row.adapter_data_json !== null ? { adapterData: JSON.parse(row.adapter_data_json) } : {},
702
+ expiresAt: row.expires_at
703
+ };
704
+ }
705
+ function withoutReservedFields(input) {
706
+ return Object.fromEntries(
707
+ Object.entries(input).filter(([key]) => !RESERVED_INPUT_FIELDS.includes(key))
708
+ );
709
+ }
710
+ var SWEEP_EXPIRED = "DELETE FROM pending_tasks WHERE expires_at <= ?";
711
+ function sweepExpiredPendingTasks(db, now) {
712
+ db.prepare(SWEEP_EXPIRED).run(now);
713
+ }
714
+ function createPendingTaskMethods(db, clock) {
715
+ const sweepExpired = db.prepare(SWEEP_EXPIRED);
716
+ const countLive = db.prepare(
717
+ "SELECT COUNT(*) AS count FROM pending_tasks WHERE expires_at > ?"
718
+ );
719
+ const upsertTask = db.prepare(
720
+ `INSERT OR REPLACE INTO pending_tasks
721
+ (id, protocol, resource_id, input_json, adapter_data_json, created_at, expires_at)
722
+ VALUES (@id, @protocol, @resource_id, @input_json, @adapter_data_json, @created_at, @expires_at)`
723
+ );
724
+ const selectLive = db.prepare(
725
+ "SELECT * FROM pending_tasks WHERE id = ? AND expires_at > ?"
726
+ );
727
+ const takeLive = db.prepare(
728
+ "DELETE FROM pending_tasks WHERE id = ? AND expires_at > ? RETURNING *"
729
+ );
730
+ const put = db.transaction((task, maxTasks, expiresAt) => {
731
+ const now = clock.nowIso();
732
+ sweepExpired.run(now);
733
+ if ((countLive.get(now)?.count ?? 0) >= maxTasks) return false;
734
+ upsertTask.run({
735
+ id: task.id,
736
+ protocol: task.protocol,
737
+ resource_id: task.resourceId,
738
+ input_json: JSON.stringify(withoutReservedFields(task.input)),
739
+ adapter_data_json: task.adapterData !== void 0 ? JSON.stringify(task.adapterData) : null,
740
+ created_at: now,
741
+ expires_at: expiresAt
742
+ });
743
+ return true;
744
+ });
745
+ return {
746
+ async putPendingTask(task, options) {
747
+ try {
748
+ if (!Number.isInteger(options.maxTasks) || options.maxTasks < 0) {
749
+ throw new CommerceError("STORAGE_ERROR", "maxTasks must be a non-negative integer");
750
+ }
751
+ return put.immediate(task, options.maxTasks, storedIso(task.expiresAt, "expiresAt"));
752
+ } catch (err) {
753
+ throw toCommerceError(err, "STORAGE_ERROR", "Failed to store pending task");
754
+ }
755
+ },
756
+ async getPendingTask(id) {
757
+ const row = selectLive.get(id, clock.nowIso());
758
+ return row !== void 0 ? rowToTask(row) : void 0;
759
+ },
760
+ async takePendingTask(id) {
761
+ try {
762
+ const now = clock.nowIso();
763
+ sweepExpired.run(now);
764
+ const row = takeLive.get(id, now);
765
+ return row !== void 0 ? rowToTask(row) : void 0;
766
+ } catch (err) {
767
+ throw toCommerceError(err, "STORAGE_ERROR", "Failed to take pending task");
768
+ }
769
+ }
770
+ };
771
+ }
772
+
31
773
  // src/storage/receipts/rows.ts
32
774
  function receiptToRow(receipt) {
33
775
  return {
@@ -166,166 +908,7 @@ function rowToTransaction(row, now) {
166
908
  };
167
909
  }
168
910
 
169
- // src/storage/receipts/schema.ts
170
- var MIGRATIONS = [
171
- {
172
- version: 1,
173
- up(db) {
174
- db.exec(`
175
- CREATE TABLE IF NOT EXISTS receipts (
176
- seq INTEGER PRIMARY KEY AUTOINCREMENT,
177
- id TEXT NOT NULL UNIQUE,
178
- request_id TEXT NOT NULL,
179
- resource_id TEXT NOT NULL,
180
- payment_json TEXT,
181
- delivered_at TEXT NOT NULL,
182
- backend_status INTEGER NOT NULL,
183
- duration_ms INTEGER,
184
- protocol TEXT,
185
- metadata_json TEXT
186
- );
187
- CREATE INDEX IF NOT EXISTS idx_receipts_request_id ON receipts(request_id);
188
- CREATE INDEX IF NOT EXISTS idx_receipts_delivered_at ON receipts(delivered_at);
189
-
190
- CREATE TABLE IF NOT EXISTS events (
191
- seq INTEGER PRIMARY KEY AUTOINCREMENT,
192
- id TEXT NOT NULL UNIQUE,
193
- type TEXT NOT NULL,
194
- request_id TEXT NOT NULL,
195
- resource_id TEXT,
196
- at TEXT NOT NULL,
197
- adapter TEXT,
198
- payment_provider TEXT,
199
- duration_ms INTEGER,
200
- status TEXT,
201
- data_json TEXT
202
- );
203
- CREATE INDEX IF NOT EXISTS idx_events_request_id ON events(request_id);
204
- CREATE INDEX IF NOT EXISTS idx_events_at ON events(at);
205
-
206
- CREATE TABLE IF NOT EXISTS payment_attempts (
207
- seq INTEGER PRIMARY KEY AUTOINCREMENT,
208
- id TEXT NOT NULL UNIQUE,
209
- request_id TEXT NOT NULL,
210
- resource_id TEXT NOT NULL,
211
- provider TEXT NOT NULL,
212
- replay_key TEXT NOT NULL UNIQUE,
213
- status TEXT NOT NULL,
214
- amount TEXT NOT NULL,
215
- currency TEXT NOT NULL,
216
- payer TEXT,
217
- payee TEXT,
218
- external_reference TEXT,
219
- rejection_reason TEXT,
220
- created_at TEXT NOT NULL,
221
- updated_at TEXT NOT NULL
222
- );
223
- CREATE INDEX IF NOT EXISTS idx_payment_attempts_request_id ON payment_attempts(request_id);
224
- CREATE INDEX IF NOT EXISTS idx_payment_attempts_created_at ON payment_attempts(created_at);
225
- `);
226
- }
227
- },
228
- {
229
- version: 2,
230
- up(db) {
231
- db.exec(`ALTER TABLE receipts ADD COLUMN authorization_json TEXT;`);
232
- }
233
- },
234
- {
235
- version: 3,
236
- up(db) {
237
- db.exec(`
238
- CREATE TABLE IF NOT EXISTS payment_attempt_history (
239
- seq INTEGER PRIMARY KEY AUTOINCREMENT,
240
- id TEXT NOT NULL,
241
- request_id TEXT NOT NULL,
242
- resource_id TEXT NOT NULL,
243
- provider TEXT NOT NULL,
244
- replay_key TEXT NOT NULL,
245
- status TEXT NOT NULL,
246
- amount TEXT NOT NULL,
247
- currency TEXT NOT NULL,
248
- payer TEXT,
249
- payee TEXT,
250
- external_reference TEXT,
251
- rejection_reason TEXT,
252
- created_at TEXT NOT NULL,
253
- updated_at TEXT NOT NULL,
254
- superseded_at TEXT NOT NULL
255
- );
256
- CREATE INDEX IF NOT EXISTS idx_payment_attempt_history_replay_key ON payment_attempt_history(replay_key);
257
- CREATE INDEX IF NOT EXISTS idx_payment_attempt_history_request_id ON payment_attempt_history(request_id);
258
- `);
259
- }
260
- },
261
- {
262
- version: 4,
263
- up(db) {
264
- db.exec(`
265
- CREATE TABLE IF NOT EXISTS transactions (
266
- seq INTEGER PRIMARY KEY AUTOINCREMENT,
267
- id TEXT NOT NULL UNIQUE,
268
- request_id TEXT NOT NULL,
269
- resource_id TEXT NOT NULL,
270
- protocol TEXT NOT NULL,
271
- state TEXT NOT NULL,
272
- provider TEXT NOT NULL,
273
- attempt_id TEXT NOT NULL,
274
- replay_key TEXT NOT NULL,
275
- network TEXT,
276
- asset TEXT,
277
- authorization_json TEXT,
278
- reservation_id TEXT,
279
- locator_json TEXT,
280
- expires_at TEXT,
281
- input_digest TEXT,
282
- config_digest TEXT NOT NULL,
283
- settling_at TEXT,
284
- backend_dispatched_at TEXT,
285
- backend_deadline_at TEXT,
286
- backend_status INTEGER,
287
- backend_error_code TEXT,
288
- receipt_id TEXT,
289
- persistence_failures_json TEXT,
290
- completed_at TEXT,
291
- created_at TEXT NOT NULL,
292
- updated_at TEXT NOT NULL
293
- );
294
- CREATE INDEX IF NOT EXISTS idx_transactions_state_seq ON transactions(state, seq);
295
- CREATE INDEX IF NOT EXISTS idx_transactions_request_id ON transactions(request_id);
296
- CREATE INDEX IF NOT EXISTS idx_transactions_replay_key ON transactions(replay_key);
297
-
298
- ALTER TABLE receipts ADD COLUMN transaction_id TEXT;
299
- ALTER TABLE events ADD COLUMN transaction_id TEXT;
300
- ALTER TABLE payment_attempts ADD COLUMN transaction_id TEXT;
301
- ALTER TABLE payment_attempts ADD COLUMN resolution_json TEXT;
302
- ALTER TABLE payment_attempt_history ADD COLUMN transaction_id TEXT;
303
- ALTER TABLE payment_attempt_history ADD COLUMN resolution_json TEXT;
304
- CREATE INDEX IF NOT EXISTS idx_payment_attempt_history_id ON payment_attempt_history(id);
305
- `);
306
- }
307
- }
308
- ];
309
- var SCHEMA_VERSION = MIGRATIONS.at(-1)?.version ?? 0;
310
- function migrate(db, target = SCHEMA_VERSION) {
311
- const current = db.pragma("user_version", { simple: true });
312
- for (const migration of MIGRATIONS) {
313
- if (migration.version <= current || migration.version > target) continue;
314
- const apply = db.transaction(() => {
315
- migration.up(db);
316
- db.pragma(`user_version = ${migration.version}`);
317
- });
318
- apply();
319
- }
320
- }
321
-
322
911
  // src/storage/receipts/store.ts
323
- var DEFAULT_LIST_LIMIT = 50;
324
- var MAX_LIST_LIMIT = 500;
325
- function clampListLimit(limit) {
326
- const base = limit !== void 0 && Number.isFinite(limit) ? limit : DEFAULT_LIST_LIMIT;
327
- return Math.min(Math.max(Math.trunc(base), 1), MAX_LIST_LIMIT);
328
- }
329
912
  var UNDELIVERED = "backend_status NOT BETWEEN 200 AND 299";
330
913
  var UNCERTAIN = "status IN ('settlement-uncertain', 'failed')";
331
914
  var TRANSACTION_SELECT = `
@@ -351,13 +934,44 @@ function isUniqueConstraintOn(err, column) {
351
934
  return err instanceof Error && "code" in err && err.code === "SQLITE_CONSTRAINT_UNIQUE" && err.message.includes(column);
352
935
  }
353
936
  function createSqliteReceiptStore(options) {
937
+ const db = openSqliteDatabase({
938
+ path: options.path,
939
+ label: "Receipt database",
940
+ logger: options.logger ?? NOOP_LOGGER
941
+ });
942
+ migrate(db);
943
+ return storeOn(db, options);
944
+ }
945
+ function openSqliteReceiptStoreReadOnly(path) {
946
+ let db;
947
+ let schemaVersion;
948
+ try {
949
+ db = new Database(path, { readonly: true, fileMustExist: true });
950
+ schemaVersion = db.pragma("user_version", { simple: true });
951
+ } catch (cause) {
952
+ db?.close();
953
+ throw new CommerceError(
954
+ "STORAGE_ERROR",
955
+ `Receipt database "${path}" cannot be opened: ${cause instanceof Error ? cause.message : String(cause)}`,
956
+ { details: { path }, cause }
957
+ );
958
+ }
959
+ if (schemaVersion !== SCHEMA_VERSION) {
960
+ db.close();
961
+ throw new CommerceError(
962
+ "STORAGE_ERROR",
963
+ `Receipt database "${path}" is at schema v${schemaVersion}, not v${SCHEMA_VERSION}`,
964
+ { details: { path, schemaVersion, expected: SCHEMA_VERSION } }
965
+ );
966
+ }
967
+ return storeOn(db, { path });
968
+ }
969
+ function storeOn(db, options) {
354
970
  const logger = options.logger ?? NOOP_LOGGER;
355
971
  const clock = options.clock ?? systemClock;
356
972
  const ids = options.ids ?? defaultIds;
357
973
  const path = options.path;
358
974
  const isFileBacked = path !== ":memory:";
359
- const db = openSqliteDatabase({ path, label: "Receipt database", logger });
360
- migrate(db);
361
975
  const insertReceiptStmt = db.prepare(
362
976
  `INSERT INTO receipts (id, request_id, resource_id, payment_json, delivered_at, backend_status, duration_ms, protocol, metadata_json, authorization_json, transaction_id)
363
977
  VALUES (@id, @request_id, @resource_id, @payment_json, @delivered_at, @backend_status, @duration_ms, @protocol, @metadata_json, @authorization_json, @transaction_id)`
@@ -487,6 +1101,9 @@ function createSqliteReceiptStore(options) {
487
1101
  const getArchivedPaymentAttemptStmt = db.prepare(
488
1102
  "SELECT * FROM payment_attempt_history WHERE id = ? ORDER BY seq DESC LIMIT 1"
489
1103
  );
1104
+ const paymentAttemptByReplayKeyStmt = db.prepare(
1105
+ "SELECT * FROM payment_attempts WHERE replay_key = ?"
1106
+ );
490
1107
  const resolvePaymentAttemptStmt = db.prepare(
491
1108
  `UPDATE payment_attempts SET status = @status,
492
1109
  rejection_reason = COALESCE(@rejection_reason, rejection_reason),
@@ -605,13 +1222,39 @@ function createSqliteReceiptStore(options) {
605
1222
  return true;
606
1223
  }
607
1224
  );
1225
+ const unresolvedTransactionsStmt = db.prepare(
1226
+ `${TRANSACTION_SELECT} WHERE t.state NOT IN (?, ?)`
1227
+ );
1228
+ const countOrphanHoldsStmt = db.prepare(
1229
+ `SELECT COUNT(*) AS count FROM authorization_holds h WHERE ${ORPHAN_HOLD_WHERE}`
1230
+ );
1231
+ const countUnresolvedKeysStmt = db.prepare(
1232
+ `SELECT COUNT(*) FILTER (WHERE ${ENDPOINT_HAS_PREFIX} AND expires_at > @now) AS payment,
1233
+ COUNT(*) FILTER (WHERE NOT ${ENDPOINT_HAS_PREFIX}) AS other
1234
+ FROM idempotency_keys WHERE state = 'unresolved'`
1235
+ );
1236
+ const countLiveTasksStmt = db.prepare(
1237
+ "SELECT COUNT(*) AS count FROM pending_tasks WHERE expires_at > ?"
1238
+ );
1239
+ const legacyImportsStmt = db.prepare(
1240
+ "SELECT source, path, rows, imported_at FROM legacy_imports WHERE path IS NOT NULL ORDER BY source"
1241
+ );
608
1242
  let closed = false;
1243
+ let releaseLegacyLocks;
609
1244
  const descriptor = {
610
1245
  name: "sqlite-receipt-store",
611
1246
  kind: "storage",
612
1247
  implementationVersion: PACKAGE_VERSION,
613
1248
  supportedSpec: `sqlite-schema-v${SCHEMA_VERSION}`,
614
- capabilities: ["receipts", "events", "payment-attempts", "transactions"],
1249
+ capabilities: [
1250
+ "receipts",
1251
+ "events",
1252
+ "payment-attempts",
1253
+ "transactions",
1254
+ "idempotency-keys",
1255
+ "authorization-holds",
1256
+ "pending-tasks"
1257
+ ],
615
1258
  status: "stable"
616
1259
  };
617
1260
  const store = {
@@ -623,6 +1266,16 @@ function createSqliteReceiptStore(options) {
623
1266
  `Receipt store schema version mismatch (found ${version}, expected ${SCHEMA_VERSION})`
624
1267
  );
625
1268
  }
1269
+ if (!db.readonly) sweepExpiredPendingTasks(db, clock.nowIso());
1270
+ if (options.legacyStores !== void 0 && releaseLegacyLocks === void 0) {
1271
+ releaseLegacyLocks = importLegacyStores(
1272
+ db,
1273
+ options.path,
1274
+ options.legacyStores,
1275
+ clock,
1276
+ logger
1277
+ );
1278
+ }
626
1279
  },
627
1280
  async appendEvent(event) {
628
1281
  try {
@@ -805,6 +1458,10 @@ function createSqliteReceiptStore(options) {
805
1458
  const row = getPaymentAttemptStmt.get(id) ?? getArchivedPaymentAttemptStmt.get(id);
806
1459
  return row !== void 0 ? rowToPaymentAttempt(row) : void 0;
807
1460
  },
1461
+ async findPaymentAttemptByReplayKey(replayKey) {
1462
+ const row = paymentAttemptByReplayKeyStmt.get(replayKey);
1463
+ return row !== void 0 ? rowToPaymentAttempt(row) : void 0;
1464
+ },
808
1465
  async resolvePaymentAttempt(request) {
809
1466
  try {
810
1467
  return resolveAttempt(request, clock.nowIso());
@@ -812,6 +1469,38 @@ function createSqliteReceiptStore(options) {
812
1469
  throw toCommerceError(err, "STORAGE_ERROR", "Failed to resolve payment attempt");
813
1470
  }
814
1471
  },
1472
+ ...createIdempotencyMethods(db, clock),
1473
+ ...createHoldMethods(db, clock),
1474
+ ...createPendingTaskMethods(db, clock),
1475
+ // Reads all unresolved transactions at once. Page this query if large
1476
+ // journals make operator diagnostics too costly.
1477
+ async summary({ orphanHoldMinAgeMs }) {
1478
+ const now = clock.nowIso();
1479
+ const unresolvedTransactions = {};
1480
+ for (const row of unresolvedTransactionsStmt.all(...RESOLVED_STATES)) {
1481
+ const { state } = rowToTransaction(row, now);
1482
+ unresolvedTransactions[state] = (unresolvedTransactions[state] ?? 0) + 1;
1483
+ }
1484
+ const orphansBefore = new Date(Date.parse(now) - orphanHoldMinAgeMs).toISOString();
1485
+ const unresolvedKeys = countUnresolvedKeysStmt.get({
1486
+ prefix: PAYMENT_KEY_ENDPOINT_PREFIX,
1487
+ now
1488
+ });
1489
+ return {
1490
+ unresolvedTransactions,
1491
+ orphanHolds: countOrphanHoldsStmt.get(orphansBefore)?.count ?? 0,
1492
+ unresolvedIdempotencyKeys: unresolvedKeys?.other ?? 0,
1493
+ unresolvedPaymentKeys: unresolvedKeys?.payment ?? 0,
1494
+ unexpiredPendingTasks: countLiveTasksStmt.get(now)?.count ?? 0,
1495
+ legacyImports: legacyImportsStmt.all().map((row) => ({
1496
+ source: row.source,
1497
+ path: row.path,
1498
+ rows: row.rows,
1499
+ importedAt: row.imported_at
1500
+ })),
1501
+ missingLegacyImports: missingLegacyImports(db)
1502
+ };
1503
+ },
815
1504
  descriptor,
816
1505
  async health() {
817
1506
  const startedAt = clock.monotonicMs();
@@ -870,6 +1559,7 @@ function createSqliteReceiptStore(options) {
870
1559
  async close() {
871
1560
  if (!closed) {
872
1561
  closed = true;
1562
+ releaseLegacyLocks?.();
873
1563
  db.close();
874
1564
  }
875
1565
  }
@@ -877,6 +1567,6 @@ function createSqliteReceiptStore(options) {
877
1567
  return store;
878
1568
  }
879
1569
 
880
- export { createSqliteReceiptStore };
881
- //# sourceMappingURL=chunk-QLUCNPRT.js.map
882
- //# sourceMappingURL=chunk-QLUCNPRT.js.map
1570
+ export { SCHEMA_VERSION, createSqliteReceiptStore, hasTable, openSqliteReceiptStoreReadOnly, readMissingLegacyImports };
1571
+ //# sourceMappingURL=chunk-5TID36YG.js.map
1572
+ //# sourceMappingURL=chunk-5TID36YG.js.map