@payai/x402-evm 2.4.1 → 2.4.3

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 (143) hide show
  1. package/dist/cjs/batch-settlement/client/file-storage.d.ts +47 -0
  2. package/dist/cjs/batch-settlement/client/file-storage.js +116 -0
  3. package/dist/cjs/batch-settlement/client/file-storage.js.map +1 -0
  4. package/dist/cjs/batch-settlement/client/index.d.ts +111 -0
  5. package/dist/cjs/batch-settlement/client/index.js +1565 -0
  6. package/dist/cjs/batch-settlement/client/index.js.map +1 -0
  7. package/dist/cjs/batch-settlement/facilitator/index.d.ts +71 -0
  8. package/dist/cjs/batch-settlement/facilitator/index.js +2032 -0
  9. package/dist/cjs/batch-settlement/facilitator/index.js.map +1 -0
  10. package/dist/cjs/batch-settlement/server/file-storage.d.ts +53 -0
  11. package/dist/cjs/batch-settlement/server/file-storage.js +181 -0
  12. package/dist/cjs/batch-settlement/server/file-storage.js.map +1 -0
  13. package/dist/cjs/batch-settlement/server/index.d.ts +491 -0
  14. package/dist/cjs/batch-settlement/server/index.js +1960 -0
  15. package/dist/cjs/batch-settlement/server/index.js.map +1 -0
  16. package/dist/cjs/batch-settlement/server/redis-storage.d.ts +87 -0
  17. package/dist/cjs/batch-settlement/server/redis-storage.js +181 -0
  18. package/dist/cjs/batch-settlement/server/redis-storage.js.map +1 -0
  19. package/dist/cjs/exact/client/index.d.ts +6 -4
  20. package/dist/cjs/exact/client/index.js +7 -5
  21. package/dist/cjs/exact/client/index.js.map +1 -1
  22. package/dist/cjs/exact/facilitator/index.d.ts +16 -9
  23. package/dist/cjs/exact/facilitator/index.js +35 -7
  24. package/dist/cjs/exact/facilitator/index.js.map +1 -1
  25. package/dist/cjs/exact/server/index.js +40 -1
  26. package/dist/cjs/exact/server/index.js.map +1 -1
  27. package/dist/cjs/exact/v1/client/index.d.ts +2 -1
  28. package/dist/cjs/exact/v1/client/index.js.map +1 -1
  29. package/dist/cjs/exact/v1/facilitator/index.d.ts +11 -5
  30. package/dist/cjs/exact/v1/facilitator/index.js +16 -2
  31. package/dist/cjs/exact/v1/facilitator/index.js.map +1 -1
  32. package/dist/cjs/index.d.ts +113 -7
  33. package/dist/cjs/index.js +1353 -5
  34. package/dist/cjs/index.js.map +1 -1
  35. package/dist/{esm/permit2-CyZxwngN.d.mts → cjs/permit2-DhJRUcgY.d.ts} +1 -13
  36. package/dist/cjs/rpc-DULZzRne.d.ts +13 -0
  37. package/dist/cjs/scheme-CvkPJXBD.d.ts +307 -0
  38. package/dist/{esm/scheme-DCR7hsa3.d.mts → cjs/scheme-DTQFE9xp.d.ts} +2 -2
  39. package/dist/{esm/signer-D912R4mq.d.mts → cjs/signer-tYS6Y46X.d.ts} +3 -0
  40. package/dist/cjs/storage-6W5MO46W.d.ts +50 -0
  41. package/dist/cjs/storage-Bl6aD0Xg.d.ts +81 -0
  42. package/dist/cjs/types-CF8P2-NM.d.ts +180 -0
  43. package/dist/cjs/upto/client/index.d.ts +5 -3
  44. package/dist/cjs/upto/client/index.js +7 -5
  45. package/dist/cjs/upto/client/index.js.map +1 -1
  46. package/dist/cjs/upto/facilitator/index.d.ts +2 -1
  47. package/dist/cjs/upto/facilitator/index.js +2 -1
  48. package/dist/cjs/upto/facilitator/index.js.map +1 -1
  49. package/dist/cjs/upto/server/index.js +40 -1
  50. package/dist/cjs/upto/server/index.js.map +1 -1
  51. package/dist/cjs/v1/index.d.ts +2 -1
  52. package/dist/cjs/v1/index.js.map +1 -1
  53. package/dist/esm/batch-settlement/client/file-storage.d.mts +47 -0
  54. package/dist/esm/batch-settlement/client/file-storage.mjs +63 -0
  55. package/dist/esm/batch-settlement/client/file-storage.mjs.map +1 -0
  56. package/dist/esm/batch-settlement/client/index.d.mts +111 -0
  57. package/dist/esm/batch-settlement/client/index.mjs +59 -0
  58. package/dist/esm/batch-settlement/client/index.mjs.map +1 -0
  59. package/dist/esm/batch-settlement/facilitator/index.d.mts +71 -0
  60. package/dist/esm/batch-settlement/facilitator/index.mjs +1235 -0
  61. package/dist/esm/batch-settlement/facilitator/index.mjs.map +1 -0
  62. package/dist/esm/batch-settlement/server/file-storage.d.mts +53 -0
  63. package/dist/esm/batch-settlement/server/file-storage.mjs +128 -0
  64. package/dist/esm/batch-settlement/server/file-storage.mjs.map +1 -0
  65. package/dist/esm/batch-settlement/server/index.d.mts +491 -0
  66. package/dist/esm/batch-settlement/server/index.mjs +1645 -0
  67. package/dist/esm/batch-settlement/server/index.mjs.map +1 -0
  68. package/dist/esm/batch-settlement/server/redis-storage.d.mts +87 -0
  69. package/dist/esm/batch-settlement/server/redis-storage.mjs +156 -0
  70. package/dist/esm/batch-settlement/server/redis-storage.mjs.map +1 -0
  71. package/dist/esm/chunk-2EUQTNJO.mjs +38 -0
  72. package/dist/esm/chunk-2EUQTNJO.mjs.map +1 -0
  73. package/dist/esm/chunk-53USC5VE.mjs +47 -0
  74. package/dist/esm/chunk-53USC5VE.mjs.map +1 -0
  75. package/dist/esm/{chunk-GJ57SZGI.mjs → chunk-6WQOGWBE.mjs} +7 -5
  76. package/dist/esm/{chunk-GJ57SZGI.mjs.map → chunk-6WQOGWBE.mjs.map} +1 -1
  77. package/dist/esm/{chunk-F3OOHBAW.mjs → chunk-BTYNCDNS.mjs} +42 -2
  78. package/dist/esm/{chunk-F3OOHBAW.mjs.map → chunk-BTYNCDNS.mjs.map} +1 -1
  79. package/dist/esm/{chunk-ERK2ZPOY.mjs → chunk-CSQS7ZON.mjs} +27 -7
  80. package/dist/esm/chunk-CSQS7ZON.mjs.map +1 -0
  81. package/dist/esm/chunk-GD4MKCN7.mjs +57 -0
  82. package/dist/esm/chunk-GD4MKCN7.mjs.map +1 -0
  83. package/dist/esm/chunk-HYABYUBD.mjs +432 -0
  84. package/dist/esm/chunk-HYABYUBD.mjs.map +1 -0
  85. package/dist/esm/chunk-IN5YIT5C.mjs +159 -0
  86. package/dist/esm/chunk-IN5YIT5C.mjs.map +1 -0
  87. package/dist/esm/{chunk-JII456TS.mjs → chunk-JK7SLLF7.mjs} +1 -1
  88. package/dist/esm/chunk-JK7SLLF7.mjs.map +1 -0
  89. package/dist/esm/{chunk-C4ZQMS77.mjs → chunk-MACPBXCT.mjs} +2 -216
  90. package/dist/esm/chunk-MACPBXCT.mjs.map +1 -0
  91. package/dist/esm/chunk-NKYVYGRA.mjs +911 -0
  92. package/dist/esm/chunk-NKYVYGRA.mjs.map +1 -0
  93. package/dist/esm/{chunk-FQJR4RCF.mjs → chunk-R7I3RZFF.mjs} +10 -6
  94. package/dist/esm/{chunk-FQJR4RCF.mjs.map → chunk-R7I3RZFF.mjs.map} +1 -1
  95. package/dist/esm/{chunk-CRT6YNY5.mjs → chunk-RWLVVO3B.mjs} +21 -61
  96. package/dist/esm/chunk-RWLVVO3B.mjs.map +1 -0
  97. package/dist/esm/chunk-TGFAVNUD.mjs +111 -0
  98. package/dist/esm/chunk-TGFAVNUD.mjs.map +1 -0
  99. package/dist/esm/chunk-TW7Z65AO.mjs +34 -0
  100. package/dist/esm/chunk-TW7Z65AO.mjs.map +1 -0
  101. package/dist/esm/chunk-U4HCGTLU.mjs +35 -0
  102. package/dist/esm/chunk-U4HCGTLU.mjs.map +1 -0
  103. package/dist/esm/chunk-VS3RYAYE.mjs +80 -0
  104. package/dist/esm/chunk-VS3RYAYE.mjs.map +1 -0
  105. package/dist/esm/chunk-W6ON4LG2.mjs +39 -0
  106. package/dist/esm/chunk-W6ON4LG2.mjs.map +1 -0
  107. package/dist/esm/{chunk-WKBC5YMI.mjs → chunk-YMQCTKDU.mjs} +23 -55
  108. package/dist/esm/chunk-YMQCTKDU.mjs.map +1 -0
  109. package/dist/esm/exact/client/index.d.mts +6 -4
  110. package/dist/esm/exact/client/index.mjs +10 -5
  111. package/dist/esm/exact/facilitator/index.d.mts +16 -9
  112. package/dist/esm/exact/facilitator/index.mjs +36 -14
  113. package/dist/esm/exact/facilitator/index.mjs.map +1 -1
  114. package/dist/esm/exact/server/index.mjs +1 -1
  115. package/dist/esm/exact/v1/client/index.d.mts +2 -1
  116. package/dist/esm/exact/v1/client/index.mjs +5 -2
  117. package/dist/esm/exact/v1/facilitator/index.d.mts +11 -5
  118. package/dist/esm/exact/v1/facilitator/index.mjs +5 -2
  119. package/dist/esm/index.d.mts +113 -7
  120. package/dist/esm/index.mjs +53 -7
  121. package/dist/esm/index.mjs.map +1 -1
  122. package/dist/esm/permit2-DhJRUcgY.d.mts +729 -0
  123. package/dist/esm/rpc-DULZzRne.d.mts +13 -0
  124. package/dist/esm/scheme-DtbSS4Fk.d.mts +307 -0
  125. package/dist/esm/scheme-gtqAIYPJ.d.mts +47 -0
  126. package/dist/esm/signer-tYS6Y46X.d.mts +170 -0
  127. package/dist/esm/storage-6W5MO46W.d.mts +50 -0
  128. package/dist/esm/storage-sZ1CDS4P.d.mts +81 -0
  129. package/dist/esm/types-CF8P2-NM.d.mts +180 -0
  130. package/dist/esm/upto/client/index.d.mts +5 -3
  131. package/dist/esm/upto/client/index.mjs +9 -4
  132. package/dist/esm/upto/facilitator/index.d.mts +2 -1
  133. package/dist/esm/upto/facilitator/index.mjs +17 -9
  134. package/dist/esm/upto/facilitator/index.mjs.map +1 -1
  135. package/dist/esm/upto/server/index.mjs +1 -1
  136. package/dist/esm/v1/index.d.mts +2 -1
  137. package/dist/esm/v1/index.mjs +5 -2
  138. package/package.json +5 -5
  139. package/dist/esm/chunk-C4ZQMS77.mjs.map +0 -1
  140. package/dist/esm/chunk-CRT6YNY5.mjs.map +0 -1
  141. package/dist/esm/chunk-ERK2ZPOY.mjs.map +0 -1
  142. package/dist/esm/chunk-JII456TS.mjs.map +0 -1
  143. package/dist/esm/chunk-WKBC5YMI.mjs.map +0 -1
@@ -0,0 +1,181 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/batch-settlement/server/fileStorage.ts
21
+ var fileStorage_exports = {};
22
+ __export(fileStorage_exports, {
23
+ FileChannelStorage: () => FileChannelStorage
24
+ });
25
+ module.exports = __toCommonJS(fileStorage_exports);
26
+ var import_promises2 = require("fs/promises");
27
+ var import_node_fs = require("fs");
28
+ var import_node_path2 = require("path");
29
+
30
+ // src/batch-settlement/storage-utils.ts
31
+ var import_promises = require("fs/promises");
32
+ var import_node_path = require("path");
33
+ function isNodeEnoent(err) {
34
+ if (!err || typeof err !== "object" || !("code" in err)) return false;
35
+ return err.code === "ENOENT";
36
+ }
37
+ async function readJsonFile(filePath) {
38
+ try {
39
+ const raw = await (0, import_promises.readFile)(filePath, "utf8");
40
+ return JSON.parse(raw);
41
+ } catch (err) {
42
+ if (isNodeEnoent(err)) return void 0;
43
+ throw err;
44
+ }
45
+ }
46
+ async function writeJsonAtomic(filePath, value) {
47
+ const dir = (0, import_node_path.dirname)(filePath);
48
+ await (0, import_promises.mkdir)(dir, { recursive: true });
49
+ const tmp = (0, import_node_path.join)(dir, `.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);
50
+ const body = `${JSON.stringify(value, null, 2)}
51
+ `;
52
+ await (0, import_promises.writeFile)(tmp, body, "utf8");
53
+ try {
54
+ await (0, import_promises.rename)(tmp, filePath);
55
+ } catch {
56
+ await (0, import_promises.unlink)(filePath).catch(() => {
57
+ });
58
+ await (0, import_promises.rename)(tmp, filePath);
59
+ }
60
+ }
61
+
62
+ // src/batch-settlement/server/fileStorage.ts
63
+ var FileChannelStorage = class {
64
+ /**
65
+ * Creates file-backed server channel storage under the given root directory.
66
+ *
67
+ * @param options - Configuration including the storage root directory.
68
+ */
69
+ constructor(options) {
70
+ this.root = options.directory;
71
+ }
72
+ /**
73
+ * Loads a persisted channel record, if present.
74
+ *
75
+ * @param channelId - The channel identifier (path segment is lowercased).
76
+ * @returns Parsed channel record or `undefined` when the file is missing.
77
+ */
78
+ async get(channelId) {
79
+ return readJsonFile(this.filePath(channelId));
80
+ }
81
+ /**
82
+ * Lists all stored channel records by reading the server directory.
83
+ *
84
+ * @returns Channel records sorted by channelId; empty array if the directory is missing.
85
+ */
86
+ async list() {
87
+ const dir = (0, import_node_path2.join)(this.root, "server");
88
+ let names;
89
+ try {
90
+ names = await (0, import_promises2.readdir)(dir);
91
+ } catch (err) {
92
+ if (isNodeEnoent(err)) return [];
93
+ throw err;
94
+ }
95
+ const channels = [];
96
+ for (const name of names) {
97
+ if (!name.endsWith(".json")) continue;
98
+ const path = (0, import_node_path2.join)(dir, name);
99
+ try {
100
+ const raw = await (0, import_promises2.readFile)(path, "utf8");
101
+ channels.push(JSON.parse(raw));
102
+ } catch (err) {
103
+ if (isNodeEnoent(err)) continue;
104
+ throw err;
105
+ }
106
+ }
107
+ return channels.sort((a, b) => a.channelId.localeCompare(b.channelId));
108
+ }
109
+ /**
110
+ * Atomically inspects and mutates a channel record under a cross-process file lock.
111
+ *
112
+ * @param channelId - The channel identifier.
113
+ * @param update - Mutation callback. Return `undefined` to delete, or `current` to leave unchanged.
114
+ * @returns The final stored channel and whether storage updated, stayed unchanged, or deleted.
115
+ */
116
+ async updateChannel(channelId, update) {
117
+ const lockPath = this.filePath(channelId) + ".lock";
118
+ await (0, import_promises2.mkdir)((0, import_node_path2.dirname)(lockPath), { recursive: true });
119
+ const lockHandle = await this.acquireLock(lockPath);
120
+ try {
121
+ const path = this.filePath(channelId);
122
+ let current;
123
+ try {
124
+ const raw = await (0, import_promises2.readFile)(path, "utf8");
125
+ current = JSON.parse(raw);
126
+ } catch (err) {
127
+ if (!isNodeEnoent(err)) throw err;
128
+ }
129
+ const next = update(current);
130
+ if (next === current) {
131
+ return { channel: current, status: "unchanged" };
132
+ }
133
+ if (!next) {
134
+ try {
135
+ await (0, import_promises2.unlink)(path);
136
+ } catch (err) {
137
+ if (!isNodeEnoent(err)) throw err;
138
+ }
139
+ return { channel: void 0, status: current ? "deleted" : "unchanged" };
140
+ }
141
+ await writeJsonAtomic(path, next);
142
+ return { channel: next, status: "updated" };
143
+ } finally {
144
+ await lockHandle.close();
145
+ await (0, import_promises2.unlink)(lockPath).catch(() => {
146
+ });
147
+ }
148
+ }
149
+ /**
150
+ * Absolute path to the JSON file for a channel.
151
+ *
152
+ * @param channelId - The channel identifier.
153
+ * @returns Filesystem path under `{root}/server/...`.
154
+ */
155
+ filePath(channelId) {
156
+ return (0, import_node_path2.join)(this.root, "server", `${channelId.toLowerCase()}.json`);
157
+ }
158
+ /**
159
+ * Creates an exclusive lock file, polling until no other process holds it.
160
+ *
161
+ * @param lockPath - Absolute path for the lock file (created with `O_EXCL`).
162
+ * @returns Writable file handle for the lock file; caller must close it to release.
163
+ */
164
+ async acquireLock(lockPath) {
165
+ while (true) {
166
+ try {
167
+ return await (0, import_promises2.open)(lockPath, import_node_fs.constants.O_CREAT | import_node_fs.constants.O_EXCL | import_node_fs.constants.O_WRONLY);
168
+ } catch (err) {
169
+ if (err.code !== "EEXIST") {
170
+ throw err;
171
+ }
172
+ await new Promise((resolve) => setTimeout(resolve, 10));
173
+ }
174
+ }
175
+ }
176
+ };
177
+ // Annotate the CommonJS export names for ESM import in node:
178
+ 0 && (module.exports = {
179
+ FileChannelStorage
180
+ });
181
+ //# sourceMappingURL=file-storage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/batch-settlement/server/fileStorage.ts","../../../../src/batch-settlement/storage-utils.ts"],"sourcesContent":["import { mkdir, open, readdir, readFile, unlink } from \"node:fs/promises\";\nimport { constants } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\nimport { isNodeEnoent, readJsonFile, writeJsonAtomic } from \"../storage-utils\";\nimport type { FileChannelStorageOptions } from \"../types\";\nimport type { ChannelStorage, Channel, ChannelUpdateResult } from \"./storage\";\n\nexport type { FileChannelStorageOptions };\n\n/**\n * Node.js file-backed {@link ChannelStorage} for the batched server scheme.\n */\nexport class FileChannelStorage implements ChannelStorage {\n private readonly root: string;\n\n /**\n * Creates file-backed server channel storage under the given root directory.\n *\n * @param options - Configuration including the storage root directory.\n */\n constructor(options: FileChannelStorageOptions) {\n this.root = options.directory;\n }\n\n /**\n * Loads a persisted channel record, if present.\n *\n * @param channelId - The channel identifier (path segment is lowercased).\n * @returns Parsed channel record or `undefined` when the file is missing.\n */\n async get(channelId: string): Promise<Channel | undefined> {\n return readJsonFile<Channel>(this.filePath(channelId));\n }\n\n /**\n * Lists all stored channel records by reading the server directory.\n *\n * @returns Channel records sorted by channelId; empty array if the directory is missing.\n */\n async list(): Promise<Channel[]> {\n const dir = join(this.root, \"server\");\n let names: string[];\n try {\n names = await readdir(dir);\n } catch (err: unknown) {\n if (isNodeEnoent(err)) return [];\n throw err;\n }\n\n const channels: Channel[] = [];\n for (const name of names) {\n if (!name.endsWith(\".json\")) continue;\n const path = join(dir, name);\n try {\n const raw = await readFile(path, \"utf8\");\n channels.push(JSON.parse(raw) as Channel);\n } catch (err: unknown) {\n // Skip files that disappeared between readdir and readFile (e.g. concurrent delete).\n // Rethrow other failures (corrupt JSON, permission denied) so callers see them.\n if (isNodeEnoent(err)) continue;\n throw err;\n }\n }\n return channels.sort((a, b) => a.channelId.localeCompare(b.channelId));\n }\n\n /**\n * Atomically inspects and mutates a channel record under a cross-process file lock.\n *\n * @param channelId - The channel identifier.\n * @param update - Mutation callback. Return `undefined` to delete, or `current` to leave unchanged.\n * @returns The final stored channel and whether storage updated, stayed unchanged, or deleted.\n */\n async updateChannel(\n channelId: string,\n update: (current: Channel | undefined) => Channel | undefined,\n ): Promise<ChannelUpdateResult> {\n const lockPath = this.filePath(channelId) + \".lock\";\n await mkdir(dirname(lockPath), { recursive: true });\n const lockHandle = await this.acquireLock(lockPath);\n\n try {\n const path = this.filePath(channelId);\n let current: Channel | undefined;\n try {\n const raw = await readFile(path, \"utf8\");\n current = JSON.parse(raw) as Channel;\n } catch (err: unknown) {\n if (!isNodeEnoent(err)) throw err;\n }\n\n const next = update(current);\n if (next === current) {\n return { channel: current, status: \"unchanged\" };\n }\n\n if (!next) {\n try {\n await unlink(path);\n } catch (err: unknown) {\n if (!isNodeEnoent(err)) throw err;\n }\n return { channel: undefined, status: current ? \"deleted\" : \"unchanged\" };\n }\n\n await writeJsonAtomic(path, next);\n return { channel: next, status: \"updated\" };\n } finally {\n await lockHandle.close();\n await unlink(lockPath).catch(() => {});\n }\n }\n\n /**\n * Absolute path to the JSON file for a channel.\n *\n * @param channelId - The channel identifier.\n * @returns Filesystem path under `{root}/server/...`.\n */\n private filePath(channelId: string): string {\n return join(this.root, \"server\", `${channelId.toLowerCase()}.json`);\n }\n\n /**\n * Creates an exclusive lock file, polling until no other process holds it.\n *\n * @param lockPath - Absolute path for the lock file (created with `O_EXCL`).\n * @returns Writable file handle for the lock file; caller must close it to release.\n */\n private async acquireLock(lockPath: string) {\n while (true) {\n try {\n return await open(lockPath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY);\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") {\n throw err;\n }\n await new Promise(resolve => setTimeout(resolve, 10));\n }\n }\n }\n}\n","import { mkdir, readFile, rename, unlink, writeFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\n\n/**\n * Returns true when `err` is a Node.js `ENOENT` filesystem error (file does not exist).\n *\n * @param err - The thrown value to inspect.\n * @returns `true` for `ENOENT`, `false` for any other value or error code.\n */\nexport function isNodeEnoent(err: unknown): boolean {\n if (!err || typeof err !== \"object\" || !(\"code\" in err)) return false;\n return (err as NodeJS.ErrnoException).code === \"ENOENT\";\n}\n\n/**\n * Reads a JSON file and parses it. Returns `undefined` if the file does not exist.\n * Other errors (permission, malformed JSON) are rethrown.\n *\n * @param filePath - Path to the JSON file.\n * @returns Parsed value, or `undefined` for `ENOENT`.\n */\nexport async function readJsonFile<T>(filePath: string): Promise<T | undefined> {\n try {\n const raw = await readFile(filePath, \"utf8\");\n return JSON.parse(raw) as T;\n } catch (err: unknown) {\n if (isNodeEnoent(err)) return undefined;\n throw err;\n }\n}\n\n/**\n * Writes JSON to `filePath` atomically (temp file in the same directory, then rename).\n * Creates parent directories as needed.\n *\n * @param filePath - Destination file path; parent dirs are created if missing.\n * @param value - JSON-serializable value to persist.\n */\nexport async function writeJsonAtomic(filePath: string, value: unknown): Promise<void> {\n const dir = dirname(filePath);\n await mkdir(dir, { recursive: true });\n const tmp = join(dir, `.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);\n const body = `${JSON.stringify(value, null, 2)}\\n`;\n await writeFile(tmp, body, \"utf8\");\n try {\n await rename(tmp, filePath);\n } catch {\n // On Windows, rename() onto an existing file throws EEXIST; unlink + rename is intentional.\n await unlink(filePath).catch(() => {});\n await rename(tmp, filePath);\n }\n}\n"],"mappings":"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","names":["import_promises","import_node_path"]}
@@ -0,0 +1,491 @@
1
+ import { Network, SchemePaymentRequiredContext, SchemeNetworkServer, SchemeServerHooks, PaymentRequirements, DeepReadonly, PaymentPayload, MoneyParser, Price, AssetAmount } from '@payai/x402/types';
2
+ import { FacilitatorClient, SettleContext, SettleResultContext } from '@payai/x402/server';
3
+ import { h as BatchSettlementVoucherClaim, A as AuthorizerSigner } from '../../types-CF8P2-NM.js';
4
+ import { a as Channel, C as ChannelStorage } from '../../storage-Bl6aD0Xg.js';
5
+ export { b as ChannelUpdateResult, I as InMemoryChannelStorage, P as PendingRequest } from '../../storage-Bl6aD0Xg.js';
6
+ import 'viem';
7
+
8
+ interface ChannelManagerConfig {
9
+ scheme: BatchSettlementEvmScheme;
10
+ facilitator: FacilitatorClient;
11
+ receiver: `0x${string}`;
12
+ token: `0x${string}`;
13
+ network: Network;
14
+ }
15
+ type ClaimChannelSelector = (channels: Channel[], context: AutoSettlementContext) => Channel[] | Promise<Channel[]>;
16
+ interface ClaimOptions {
17
+ maxClaimsPerBatch?: number;
18
+ idleSecs?: number;
19
+ selectClaimChannels?: ClaimChannelSelector;
20
+ }
21
+ interface AutoSettlementConfig {
22
+ claimIntervalSecs?: number;
23
+ settleIntervalSecs?: number;
24
+ refundIntervalSecs?: number;
25
+ maxClaimsPerBatch?: number;
26
+ selectClaimChannels?: ClaimChannelSelector;
27
+ shouldSettle?: (context: AutoSettlementContext) => boolean | Promise<boolean>;
28
+ selectRefundChannels?: (channels: Channel[], context: AutoSettlementContext) => Channel[] | Promise<Channel[]>;
29
+ onClaim?: (result: ClaimResult) => void;
30
+ onSettle?: (result: SettleResult) => void;
31
+ onRefund?: (result: RefundResult) => void;
32
+ onError?: (error: unknown) => void;
33
+ }
34
+ interface AutoSettlementContext {
35
+ now: number;
36
+ lastClaimTime: number;
37
+ lastSettleTime: number;
38
+ pendingSettle: boolean;
39
+ }
40
+ interface ClaimResult {
41
+ vouchers: number;
42
+ transaction: string;
43
+ }
44
+ interface SettleResult {
45
+ transaction: string;
46
+ }
47
+ interface RefundResult {
48
+ channel: string;
49
+ transaction: string;
50
+ }
51
+ /**
52
+ * Manages the server-side channel lifecycle for the `batch-settlement` scheme:
53
+ * batch claiming of vouchers, settlement of claimed funds, and cooperative refund.
54
+ *
55
+ * Provides one-shot operations (`claim()`, `settle()`, `claimAndSettle()`,
56
+ * `refundIdleChannels()`) and an optional interval runner.
57
+ */
58
+ declare class BatchSettlementChannelManager {
59
+ private readonly scheme;
60
+ private readonly facilitator;
61
+ private readonly receiver;
62
+ private readonly token;
63
+ private readonly network;
64
+ private timers;
65
+ private lastClaimTime;
66
+ private lastSettleTime;
67
+ private pendingSettle;
68
+ private running;
69
+ private pendingJobs;
70
+ private drainingJobs;
71
+ private autoSettleConfig;
72
+ /**
73
+ * Creates a new channel manager.
74
+ *
75
+ * @param config - Manager configuration: scheme, facilitator, receiver, token, network.
76
+ */
77
+ constructor(config: ChannelManagerConfig);
78
+ /**
79
+ * Collects claimable vouchers and submits them in batches to the facilitator via `claim()`.
80
+ *
81
+ * @param opts - Optional claim execution and target selection options.
82
+ * @param opts.maxClaimsPerBatch - Max vouchers per facilitator `claim` batch.
83
+ * @param opts.idleSecs - When set, only include channels idle for at least this many seconds.
84
+ * @param opts.selectClaimChannels - Optional selector for choosing channels before claimability checks.
85
+ * @returns Array of claim results (one per batch).
86
+ */
87
+ claim(opts?: ClaimOptions): Promise<ClaimResult[]>;
88
+ /**
89
+ * Transfers claimed (but unsettled) funds to the receiver by calling `settle(receiver, token)`.
90
+ *
91
+ * @returns Settle result with the transaction hash.
92
+ */
93
+ settle(): Promise<SettleResult>;
94
+ /**
95
+ * Convenience: claims all eligible vouchers then settles in one call.
96
+ *
97
+ * @param opts - Optional claim execution and target selection options.
98
+ * @param opts.maxClaimsPerBatch - Max vouchers per claim batch before settling.
99
+ * @param opts.idleSecs - When set, only include channels idle for at least this many seconds.
100
+ * @param opts.selectClaimChannels - Optional selector for choosing channels before claimability checks.
101
+ * @returns Combined claim and settle results.
102
+ */
103
+ claimAndSettle(opts?: ClaimOptions): Promise<{
104
+ claims: ClaimResult[];
105
+ settle?: SettleResult;
106
+ }>;
107
+ /**
108
+ * Initiates cooperative refunds for one or more channels.
109
+ *
110
+ * @param channelIds - Specific channels to refund; defaults to all sessions.
111
+ * @returns One result per successfully refunded channel.
112
+ */
113
+ refund(channelIds?: string[]): Promise<RefundResult[]>;
114
+ /**
115
+ * Refunds idle channels with non-zero balances.
116
+ *
117
+ * @param opts - Idle refund options.
118
+ * @param opts.idleSecs - Minimum seconds since the last request.
119
+ * @returns One result per successfully refunded channel.
120
+ */
121
+ refundIdleChannels(opts: {
122
+ idleSecs: number;
123
+ }): Promise<RefundResult[]>;
124
+ /**
125
+ * Collects vouchers that are eligible for onchain claiming.
126
+ *
127
+ * A voucher is claimable when its `chargedCumulativeAmount` exceeds what has already
128
+ * been claimed onchain. An optional idle filter skips sessions that received a
129
+ * request within the last `idleSecs` seconds.
130
+ *
131
+ * @param opts - Optional filtering: `idleSecs` to only return idle channels.
132
+ * @param opts.idleSecs - Minimum seconds since last request for a channel to be included.
133
+ * @returns Array of {@link BatchSettlementVoucherClaim} entries for batch submission.
134
+ */
135
+ getClaimableVouchers(opts?: {
136
+ idleSecs?: number;
137
+ }): Promise<BatchSettlementVoucherClaim[]>;
138
+ /**
139
+ * Returns channels that have a pending payer-initiated withdrawal.
140
+ *
141
+ * @returns All stored channel records with `withdrawRequestedAt` set.
142
+ */
143
+ getWithdrawalPendingSessions(): Promise<Channel[]>;
144
+ /**
145
+ * Starts auto-settlement jobs for configured claim, settle, and refund intervals.
146
+ *
147
+ * @param config - Auto-settlement policy configuration.
148
+ */
149
+ start(config?: AutoSettlementConfig): void;
150
+ /**
151
+ * Stops the auto-settlement loop.
152
+ *
153
+ * @param opts - Stop options.
154
+ * @param opts.flush - When true, run `claimAndSettle` before stopping.
155
+ * @returns Resolves when the loop is stopped (and flush work completes, if requested).
156
+ */
157
+ stop(opts?: {
158
+ flush?: boolean;
159
+ }): Promise<void>;
160
+ /**
161
+ * Refunds a single channel and removes it from storage after success.
162
+ *
163
+ * @param target - Channel to refund.
164
+ * @returns Successful refund transaction.
165
+ */
166
+ private refundChannel;
167
+ /**
168
+ * Starts a recurring timer for one auto job.
169
+ *
170
+ * @param job - Job to enqueue when the interval fires.
171
+ * @param intervalSecs - Timer interval in seconds.
172
+ */
173
+ private startAutoTimer;
174
+ /**
175
+ * Adds an auto job to the coalescing queue.
176
+ *
177
+ * @param job - Job to run.
178
+ */
179
+ private enqueueJob;
180
+ /**
181
+ * Drains queued auto jobs in priority order.
182
+ */
183
+ private drainJobs;
184
+ /**
185
+ * Returns the highest-priority queued auto job.
186
+ *
187
+ * @returns Next job to run.
188
+ */
189
+ private nextPendingJob;
190
+ /**
191
+ * Runs one auto job.
192
+ *
193
+ * @param job - Job to run.
194
+ */
195
+ private runAutoJob;
196
+ /**
197
+ * Runs the claim auto job.
198
+ */
199
+ private runClaimJob;
200
+ /**
201
+ * Runs the settlement auto job.
202
+ */
203
+ private runSettleJob;
204
+ /**
205
+ * Runs the refund auto job.
206
+ */
207
+ private runRefundJob;
208
+ /**
209
+ * Claims vouchers from a provided channel snapshot.
210
+ *
211
+ * @param channels - Channels to inspect for claimable vouchers.
212
+ * @param opts - Claim batching and filtering options.
213
+ * @param opts.maxClaimsPerBatch - Max vouchers per facilitator claim transaction.
214
+ * @param opts.idleSecs - Optional idle filter.
215
+ * @returns Claim results, one per submitted batch.
216
+ */
217
+ private claimFromChannels;
218
+ /**
219
+ * Loads stored channels and applies the configured claim selector, if any.
220
+ *
221
+ * @param opts - Claim options containing an optional target selector.
222
+ * @returns The channel snapshot that should be inspected for claimable vouchers.
223
+ */
224
+ private selectClaimTargets;
225
+ /**
226
+ * Refunds each eligible channel independently.
227
+ *
228
+ * @param channels - Channels to refund.
229
+ * @returns Successful refund results.
230
+ */
231
+ private refundChannels;
232
+ /**
233
+ * Builds an outstanding voucher claim for a refund payload.
234
+ *
235
+ * @param channel - Channel being refunded.
236
+ * @returns Claim payloads needed before refunding unclaimed balance.
237
+ */
238
+ private buildRefundClaims;
239
+ /**
240
+ * Builds the policy context passed to interval hooks.
241
+ *
242
+ * @param now - Current wall-clock time in milliseconds.
243
+ * @returns Auto-settlement policy context.
244
+ */
245
+ private buildAutoSettlementContext;
246
+ /**
247
+ * Collects claimable vouchers from a provided channel snapshot.
248
+ *
249
+ * @param channels - Channels to inspect.
250
+ * @param opts - Optional idle filter.
251
+ * @param opts.idleSecs - Minimum seconds since last request.
252
+ * @returns Claimable voucher payloads.
253
+ */
254
+ private getClaimableVouchersFromChannels;
255
+ /**
256
+ * Filters idle channels that can be cooperatively refunded.
257
+ *
258
+ * @param channels - Channels to inspect.
259
+ * @param idleSecs - Minimum seconds since the last request.
260
+ * @returns Idle refundable channels.
261
+ */
262
+ private getIdleChannelsForRefundFromChannels;
263
+ /**
264
+ * Returns channels that have been idle longer than `idleSecs` and still have
265
+ * a non-zero balance (candidates for cooperative refund).
266
+ *
267
+ * @param idleSecs - Minimum seconds since last request for a session to count as idle.
268
+ * @returns Channels meeting the idle and balance criteria.
269
+ */
270
+ private getIdleChannelsForRefund;
271
+ /**
272
+ * Submits a batch of voucher claims to the facilitator.
273
+ *
274
+ * @param claims - Voucher claims to send in one `type: "claim"` payload.
275
+ * @returns Per-batch claim summary (count and transaction hash).
276
+ */
277
+ private submitClaim;
278
+ /**
279
+ * Builds a settlement payment payload for `settle(receiver, token)`.
280
+ *
281
+ * @returns Payload with `type: "settle"` and receiver/token fields.
282
+ */
283
+ private buildSettlePaymentPayload;
284
+ /**
285
+ * Builds a minimal {@link PaymentRequirements} for channel manager operations.
286
+ *
287
+ * @returns Requirements describing batched operations for this manager.
288
+ */
289
+ private buildPaymentRequirements;
290
+ /**
291
+ * Updates session records after a successful claim submission so that
292
+ * `getClaimableVouchers` no longer returns already-claimed vouchers.
293
+ *
294
+ * @param claims - Voucher claims that were included in the submitted settlement transaction.
295
+ */
296
+ private updateClaimedSessions;
297
+ }
298
+
299
+ /**
300
+ * Adds server channel state to corrective 402 responses for cumulative mismatches.
301
+ *
302
+ * @param scheme - Owning `BatchSettlementEvmScheme` instance for storage access.
303
+ * @param ctx - Payment-required response context.
304
+ */
305
+ declare function handleEnrichPaymentRequiredResponse(scheme: BatchSettlementEvmScheme, ctx: SchemePaymentRequiredContext): Promise<void>;
306
+
307
+ interface BatchSettlementEvmSchemeServerConfig {
308
+ storage?: ChannelStorage;
309
+ receiverAuthorizerSigner?: AuthorizerSigner;
310
+ withdrawDelay?: number;
311
+ onchainStateTtlMs?: number;
312
+ }
313
+ interface BatchSettlementRequestContext {
314
+ channelId?: string;
315
+ pendingId?: string;
316
+ channelSnapshot?: Channel;
317
+ localVerify?: boolean;
318
+ }
319
+ /**
320
+ * Server-side implementation of the `batch-settlement` scheme for EVM networks.
321
+ */
322
+ declare class BatchSettlementEvmScheme implements SchemeNetworkServer {
323
+ readonly scheme: "batch-settlement";
324
+ readonly schemeHooks: SchemeServerHooks;
325
+ private readonly requestContexts;
326
+ private moneyParsers;
327
+ private readonly storage;
328
+ private readonly receiverAuthorizerSigner;
329
+ private readonly receiverAddress;
330
+ private readonly withdrawDelay;
331
+ private readonly onchainStateTtlMs;
332
+ /**
333
+ * Constructs a batched server scheme.
334
+ *
335
+ * @param receiverAddress - The server's receiver address (payTo).
336
+ * @param config - Optional configuration for storage, receiver-authorizer signer, and withdraw delay.
337
+ */
338
+ constructor(receiverAddress: `0x${string}`, config?: BatchSettlementEvmSchemeServerConfig);
339
+ /**
340
+ * Adds server-owned settlement fields before facilitator settlement.
341
+ *
342
+ * @param ctx - Settlement context for the current payment.
343
+ * @returns Additive payload fields, or nothing when no enrichment is needed.
344
+ */
345
+ enrichSettlementPayload: (ctx: SettleContext) => Promise<Record<string, unknown> | void>;
346
+ /**
347
+ * Adds corrective channel state to payment-required responses when available.
348
+ *
349
+ * @param ctx - Payment-required response context for the current request.
350
+ * @returns Updated payment requirements, or nothing when no enrichment is needed.
351
+ */
352
+ enrichPaymentRequiredResponse: (ctx: Parameters<typeof handleEnrichPaymentRequiredResponse>[1]) => Promise<PaymentRequirements[] | void>;
353
+ /**
354
+ * Adds server-owned extra fields after facilitator settlement.
355
+ *
356
+ * @param ctx - Settlement result context for the current payment.
357
+ * @returns Additive response extra fields, or nothing when no enrichment is needed.
358
+ */
359
+ enrichSettlementResponse: (ctx: SettleResultContext) => Promise<Record<string, unknown> | void>;
360
+ /**
361
+ * Merges batch-settlement state into the current request context.
362
+ *
363
+ * @param payload - Request-scoped payment payload object.
364
+ * @param context - Partial context fields to merge.
365
+ */
366
+ mergeRequestContext(payload: DeepReadonly<PaymentPayload>, context: BatchSettlementRequestContext): void;
367
+ /**
368
+ * Reads batch-settlement state for the current request without clearing it.
369
+ *
370
+ * @param payload - Request-scoped payment payload object.
371
+ * @returns Request context, if one was recorded.
372
+ */
373
+ readRequestContext(payload: DeepReadonly<PaymentPayload>): BatchSettlementRequestContext | undefined;
374
+ /**
375
+ * Reads and clears batch-settlement state for the current request.
376
+ *
377
+ * @param payload - Request-scoped payment payload object.
378
+ * @returns Request context, if one was recorded.
379
+ */
380
+ takeRequestContext(payload: DeepReadonly<PaymentPayload>): BatchSettlementRequestContext | undefined;
381
+ /**
382
+ * Stores a channel snapshot for the current settlement request.
383
+ *
384
+ * @param payload - Request-scoped payment payload object.
385
+ * @param channel - Channel state to use during response enrichment.
386
+ */
387
+ rememberChannelSnapshot(payload: DeepReadonly<PaymentPayload>, channel: Channel): void;
388
+ /**
389
+ * Reads and clears a channel snapshot for the current settlement request.
390
+ *
391
+ * @param payload - Request-scoped payment payload object.
392
+ * @returns Stored channel state, if one was recorded.
393
+ */
394
+ takeChannelSnapshot(payload: DeepReadonly<PaymentPayload>): Channel | undefined;
395
+ /**
396
+ * Clears this request's pending reservation without touching newer reservations.
397
+ *
398
+ * @param payload - Request-scoped payment payload object.
399
+ */
400
+ clearPendingRequest(payload: DeepReadonly<PaymentPayload>): Promise<void>;
401
+ /**
402
+ * Registers a custom money parser for converting price strings to token amounts.
403
+ *
404
+ * @param parser - A parser function to try before the default USD→token conversion.
405
+ * @returns `this` for chaining.
406
+ */
407
+ registerMoneyParser(parser: MoneyParser): BatchSettlementEvmScheme;
408
+ /**
409
+ * Resolves a human-readable price (e.g. `"$0.01"`) into an onchain token amount.
410
+ *
411
+ * @param price - A price string, number, or explicit {@link AssetAmount}.
412
+ * @param network - CAIP-2 network identifier for looking up the default asset.
413
+ * @returns Token amount with asset address and metadata.
414
+ */
415
+ parsePrice(price: Price, network: Network): Promise<AssetAmount>;
416
+ /**
417
+ * Injects batched-specific fields into the payment requirements returned to
418
+ * the client (receiverAuthorizer, withdrawDelay, EIP-712 domain info).
419
+ *
420
+ * @param paymentRequirements - Base payment requirements from the middleware.
421
+ * @param supportedKind - Matched scheme/network kind (extra may contain overrides).
422
+ * @param supportedKind.x402Version - Protocol version from the matched kind.
423
+ * @param supportedKind.scheme - Scheme name from the matched kind.
424
+ * @param supportedKind.network - Network identifier from the matched kind.
425
+ * @param supportedKind.extra - Optional extra fields on the matched kind.
426
+ * @param _extensionKeys - Extension keys (unused).
427
+ * @returns Enhanced payment requirements with batched fields in `extra`.
428
+ */
429
+ enhancePaymentRequirements(paymentRequirements: PaymentRequirements, supportedKind: {
430
+ x402Version: number;
431
+ scheme: string;
432
+ network: Network;
433
+ extra?: Record<string, unknown>;
434
+ }, _extensionKeys: string[]): Promise<PaymentRequirements>;
435
+ /**
436
+ * Returns the underlying channel storage instance.
437
+ *
438
+ * @returns The configured {@link ChannelStorage} backend.
439
+ */
440
+ getStorage(): ChannelStorage;
441
+ /**
442
+ * Returns the server's receiver address.
443
+ *
444
+ * @returns Receiver wallet address for the payment channel.
445
+ */
446
+ getReceiverAddress(): `0x${string}`;
447
+ /**
448
+ * Returns the configured withdraw delay (seconds).
449
+ *
450
+ * @returns Withdraw delay in seconds before uncooperative withdrawal is allowed.
451
+ */
452
+ getWithdrawDelay(): number;
453
+ /**
454
+ * Returns how long mirrored onchain channel state is trusted for local voucher verification.
455
+ *
456
+ * @returns Freshness window in milliseconds.
457
+ */
458
+ getOnchainStateTtlMs(): number;
459
+ /**
460
+ * Returns the receiver-authorizer signer, if configured.
461
+ *
462
+ * @returns Receiver-authorizer signer, or `undefined` when not set.
463
+ */
464
+ getReceiverAuthorizerSigner(): AuthorizerSigner | undefined;
465
+ /**
466
+ * Creates a {@link BatchSettlementChannelManager} pre-configured with this scheme's
467
+ * receiver, default token for the given network, and the provided facilitator.
468
+ *
469
+ * @param facilitator - Facilitator client for submitting onchain claims/settlements.
470
+ * @param network - CAIP-2 network identifier (e.g. `"eip155:84532"`).
471
+ * @returns A ready-to-use channel manager.
472
+ */
473
+ createChannelManager(facilitator: FacilitatorClient, network: Network): BatchSettlementChannelManager;
474
+ /**
475
+ * Parses a human-readable money string (e.g. `"$1.50"`) into a decimal number.
476
+ *
477
+ * @param money - Money string (may include `$`) or numeric amount.
478
+ * @returns Parsed finite number.
479
+ */
480
+ private parseMoneyToDecimal;
481
+ /**
482
+ * Converts a decimal dollar amount to the network's default token amount.
483
+ *
484
+ * @param amount - Decimal amount in display units.
485
+ * @param network - Target chain/network for default asset resolution.
486
+ * @returns {@link AssetAmount} with integer token amount, contract address, and metadata.
487
+ */
488
+ private defaultMoneyConversion;
489
+ }
490
+
491
+ export { AuthorizerSigner, type AutoSettlementConfig, type AutoSettlementContext, BatchSettlementChannelManager, BatchSettlementEvmScheme, type BatchSettlementEvmSchemeServerConfig, type BatchSettlementRequestContext, Channel, type ChannelManagerConfig, ChannelStorage, type ClaimChannelSelector, type ClaimOptions, type ClaimResult, type RefundResult, type SettleResult };