@enbox/dwn-sql-store 0.0.2 → 0.0.4

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 (85) hide show
  1. package/README.md +36 -53
  2. package/dist/esm/src/data-store-sql.js +5 -5
  3. package/dist/esm/src/data-store-sql.js.map +1 -1
  4. package/dist/esm/src/dialect/bun-sqlite-adapter.js +46 -0
  5. package/dist/esm/src/dialect/bun-sqlite-adapter.js.map +1 -0
  6. package/dist/esm/src/dialect/mysql-dialect.js +1 -1
  7. package/dist/esm/src/dialect/mysql-dialect.js.map +1 -1
  8. package/dist/esm/src/dialect/postgres-dialect.js +1 -1
  9. package/dist/esm/src/dialect/postgres-dialect.js.map +1 -1
  10. package/dist/esm/src/dialect/sqlite-dialect.js +1 -1
  11. package/dist/esm/src/dialect/sqlite-dialect.js.map +1 -1
  12. package/dist/esm/src/main.js +3 -1
  13. package/dist/esm/src/main.js.map +1 -1
  14. package/dist/esm/src/message-store-sql.js +54 -25
  15. package/dist/esm/src/message-store-sql.js.map +1 -1
  16. package/dist/esm/src/resumable-task-store-sql.js +5 -6
  17. package/dist/esm/src/resumable-task-store-sql.js.map +1 -1
  18. package/dist/esm/src/smt-store-sql.js +151 -0
  19. package/dist/esm/src/smt-store-sql.js.map +1 -0
  20. package/dist/esm/src/state-index-sql.js +234 -0
  21. package/dist/esm/src/state-index-sql.js.map +1 -0
  22. package/dist/esm/src/utils/filter.js +3 -3
  23. package/dist/esm/src/utils/filter.js.map +1 -1
  24. package/dist/esm/src/utils/sanitize.js +7 -8
  25. package/dist/esm/src/utils/sanitize.js.map +1 -1
  26. package/dist/esm/src/utils/tags.js +3 -6
  27. package/dist/esm/src/utils/tags.js.map +1 -1
  28. package/dist/esm/src/utils/transaction.js +3 -21
  29. package/dist/esm/src/utils/transaction.js.map +1 -1
  30. package/dist/types/src/data-store-sql.d.ts +3 -4
  31. package/dist/types/src/data-store-sql.d.ts.map +1 -1
  32. package/dist/types/src/dialect/bun-sqlite-adapter.d.ts +33 -0
  33. package/dist/types/src/dialect/bun-sqlite-adapter.d.ts.map +1 -0
  34. package/dist/types/src/dialect/dialect.d.ts +1 -2
  35. package/dist/types/src/dialect/dialect.d.ts.map +1 -1
  36. package/dist/types/src/dialect/mysql-dialect.d.ts +3 -2
  37. package/dist/types/src/dialect/mysql-dialect.d.ts.map +1 -1
  38. package/dist/types/src/dialect/postgres-dialect.d.ts +3 -2
  39. package/dist/types/src/dialect/postgres-dialect.d.ts.map +1 -1
  40. package/dist/types/src/dialect/sqlite-dialect.d.ts +3 -2
  41. package/dist/types/src/dialect/sqlite-dialect.d.ts.map +1 -1
  42. package/dist/types/src/main.d.ts +3 -1
  43. package/dist/types/src/main.d.ts.map +1 -1
  44. package/dist/types/src/message-store-sql.d.ts +4 -3
  45. package/dist/types/src/message-store-sql.d.ts.map +1 -1
  46. package/dist/types/src/resumable-task-store-sql.d.ts +2 -2
  47. package/dist/types/src/resumable-task-store-sql.d.ts.map +1 -1
  48. package/dist/types/src/smt-store-sql.d.ts +37 -0
  49. package/dist/types/src/smt-store-sql.d.ts.map +1 -0
  50. package/dist/types/src/state-index-sql.d.ts +44 -0
  51. package/dist/types/src/state-index-sql.d.ts.map +1 -0
  52. package/dist/types/src/types.d.ts +24 -42
  53. package/dist/types/src/types.d.ts.map +1 -1
  54. package/dist/types/src/utils/filter.d.ts +3 -3
  55. package/dist/types/src/utils/filter.d.ts.map +1 -1
  56. package/dist/types/src/utils/sanitize.d.ts +2 -2
  57. package/dist/types/src/utils/sanitize.d.ts.map +1 -1
  58. package/dist/types/src/utils/tags.d.ts +3 -5
  59. package/dist/types/src/utils/tags.d.ts.map +1 -1
  60. package/dist/types/src/utils/transaction.d.ts +4 -4
  61. package/dist/types/src/utils/transaction.d.ts.map +1 -1
  62. package/package.json +24 -36
  63. package/src/data-store-sql.ts +11 -9
  64. package/src/dialect/bun-sqlite-adapter.ts +82 -0
  65. package/src/dialect/dialect.ts +4 -5
  66. package/src/dialect/mysql-dialect.ts +8 -6
  67. package/src/dialect/postgres-dialect.ts +11 -6
  68. package/src/dialect/sqlite-dialect.ts +11 -6
  69. package/src/main.ts +4 -2
  70. package/src/message-store-sql.ts +90 -45
  71. package/src/resumable-task-store-sql.ts +9 -7
  72. package/src/smt-store-sql.ts +206 -0
  73. package/src/state-index-sql.ts +283 -0
  74. package/src/types.ts +32 -47
  75. package/src/utils/filter.ts +8 -6
  76. package/src/utils/sanitize.ts +19 -20
  77. package/src/utils/tags.ts +6 -7
  78. package/src/utils/transaction.ts +7 -23
  79. package/dist/cjs/main.js +0 -3784
  80. package/dist/cjs/package.json +0 -1
  81. package/dist/esm/src/event-log-sql.js +0 -169
  82. package/dist/esm/src/event-log-sql.js.map +0 -1
  83. package/dist/types/src/event-log-sql.d.ts +0 -24
  84. package/dist/types/src/event-log-sql.d.ts.map +0 -1
  85. package/src/event-log-sql.ts +0 -227
package/dist/cjs/main.js DELETED
@@ -1,3784 +0,0 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __export = (target, all) => {
8
- for (var name2 in all)
9
- __defProp(target, name2, { get: all[name2], enumerable: true });
10
- };
11
- var __copyProps = (to, from3, except, desc) => {
12
- if (from3 && typeof from3 === "object" || typeof from3 === "function") {
13
- for (let key of __getOwnPropNames(from3))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from3[key], enumerable: !(desc = __getOwnPropDesc(from3, key)) || desc.enumerable });
16
- }
17
- return to;
18
- };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
- // If the importer is in node compatibility mode or this is not an ESM
21
- // file that has been converted to a CommonJS file using a Babel-
22
- // compatible transform (i.e. "__esModule" has not been set), then set
23
- // "default" to the CommonJS "module.exports" for node compatibility.
24
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
- mod
26
- ));
27
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
-
29
- // dist/esm/src/main.js
30
- var main_exports = {};
31
- __export(main_exports, {
32
- DataStoreSql: () => DataStoreSql,
33
- EventLogSql: () => EventLogSql,
34
- MessageStoreSql: () => MessageStoreSql,
35
- MysqlDialect: () => MysqlDialect,
36
- PostgresDialect: () => PostgresDialect,
37
- ResumableTaskStoreSql: () => ResumableTaskStoreSql,
38
- SqliteDialect: () => SqliteDialect
39
- });
40
- module.exports = __toCommonJS(main_exports);
41
-
42
- // dist/esm/src/dialect/mysql-dialect.js
43
- var import_kysely = require("kysely");
44
- var MysqlDialect = class extends import_kysely.MysqlDialect {
45
- name = "MySQL";
46
- isStreamingSupported = true;
47
- async hasTable(db, tableName) {
48
- const result = await db.selectFrom("information_schema.tables").select("table_name").where("table_name", "=", tableName).execute();
49
- return result.length > 0;
50
- }
51
- addAutoIncrementingColumn(builder, columnName, callback) {
52
- return builder.addColumn(columnName, "integer", (col) => {
53
- col = col.autoIncrement();
54
- if (callback) {
55
- col = callback(col);
56
- }
57
- return col;
58
- });
59
- }
60
- addBlobColumn(builder, columnName, callback) {
61
- return builder.addColumn(columnName, "blob", callback);
62
- }
63
- /**
64
- * In MySQL, the ForeignKey name it creates in `mysql` will be in the following format:
65
- * `${referenceTable}_${referenceColumnName}__${tableName}_${columnName}`
66
- * ex: if the reference table is `users` and the reference column is `id` and the table is `profiles` and the column is `userId`,
67
- * the resulting name for the foreign key is: `users_id__profiles_userId`
68
- */
69
- addReferencedColumn(builder, tableName, columnName, columnType, referenceTable, referenceColumnName, onDeleteAction) {
70
- return builder.addColumn(columnName, columnType, (col) => col.notNull()).addForeignKeyConstraint(`${referenceTable}_${referenceColumnName}__${tableName}_${columnName}`, [columnName], referenceTable, [referenceColumnName], (constraint) => constraint.onDelete(onDeleteAction));
71
- }
72
- insertThenReturnId(db, table, values, _returning) {
73
- return db.insertInto(table).values(values);
74
- }
75
- };
76
-
77
- // dist/esm/src/dialect/postgres-dialect.js
78
- var import_kysely2 = require("kysely");
79
- var PostgresDialect = class extends import_kysely2.PostgresDialect {
80
- name = "PostgreSQL";
81
- isStreamingSupported = true;
82
- async hasTable(db, tableName) {
83
- const result = await db.selectFrom("information_schema.tables").select("table_name").where("table_name", "=", tableName).execute();
84
- return result.length > 0;
85
- }
86
- addAutoIncrementingColumn(builder, columnName, callback) {
87
- return builder.addColumn(columnName, "serial", callback);
88
- }
89
- addBlobColumn(builder, columnName, callback) {
90
- return builder.addColumn(columnName, "bytea", callback);
91
- }
92
- addReferencedColumn(builder, _tableName, columnName, columnType, referenceTable, referenceColumnName, onDeleteAction) {
93
- return builder.addColumn(columnName, columnType, (col) => col.notNull().references(`${referenceTable}.${referenceColumnName}`).onDelete(onDeleteAction));
94
- }
95
- insertThenReturnId(db, table, values, returning) {
96
- return db.insertInto(table).values(values).returning(returning);
97
- }
98
- };
99
-
100
- // dist/esm/src/dialect/sqlite-dialect.js
101
- var import_kysely3 = require("kysely");
102
- var SqliteDialect = class extends import_kysely3.SqliteDialect {
103
- name = "SQLite";
104
- isStreamingSupported = false;
105
- async hasTable(db, tableName) {
106
- const result = await db.selectFrom("sqlite_master").select("name").where("type", "=", "table").where("name", "=", tableName).execute();
107
- return result.length > 0;
108
- }
109
- addAutoIncrementingColumn(builder, columnName, callback) {
110
- return builder.addColumn(columnName, "integer", (col) => {
111
- col = col.autoIncrement();
112
- if (callback) {
113
- col = callback(col);
114
- }
115
- return col;
116
- });
117
- }
118
- addBlobColumn(builder, columnName, callback) {
119
- return builder.addColumn(columnName, "blob", callback);
120
- }
121
- addReferencedColumn(builder, _tableName, columnName, columnType, referenceTable, referenceColumnName, onDeleteAction) {
122
- return builder.addColumn(columnName, columnType, (col) => col.notNull().references(`${referenceTable}.${referenceColumnName}`).onDelete(onDeleteAction));
123
- }
124
- insertThenReturnId(db, table, values, returning) {
125
- return db.insertInto(table).values(values).returning(returning);
126
- }
127
- };
128
-
129
- // dist/esm/src/data-store-sql.js
130
- var import_dwn_sdk_js = require("@enbox/dwn-sdk-js");
131
- var import_kysely4 = require("kysely");
132
- var import_readable_stream = require("readable-stream");
133
- var DataStoreSql = class {
134
- #dialect;
135
- #db = null;
136
- constructor(dialect) {
137
- this.#dialect = dialect;
138
- }
139
- async open() {
140
- if (this.#db) {
141
- return;
142
- }
143
- this.#db = new import_kysely4.Kysely({ dialect: this.#dialect });
144
- const tableName = "dataStore";
145
- const tableExists = await this.#dialect.hasTable(this.#db, tableName);
146
- if (tableExists) {
147
- return;
148
- }
149
- let table = this.#db.schema.createTable(tableName).ifNotExists().addColumn("tenant", "varchar(255)", (col) => col.notNull()).addColumn("recordId", "varchar(60)", (col) => col.notNull()).addColumn("dataCid", "varchar(60)", (col) => col.notNull());
150
- table = this.#dialect.addAutoIncrementingColumn(table, "id", (col) => col.primaryKey());
151
- table = this.#dialect.addBlobColumn(table, "data", (col) => col.notNull());
152
- await table.execute();
153
- await this.#db.schema.createIndex("tenant_recordId_dataCid").on(tableName).columns(["tenant", "recordId", "dataCid"]).unique().execute();
154
- }
155
- async close() {
156
- await this.#db?.destroy();
157
- this.#db = null;
158
- }
159
- async get(tenant, recordId, dataCid) {
160
- if (!this.#db) {
161
- throw new Error("Connection to database not open. Call `open` before using `get`.");
162
- }
163
- const result = await this.#db.selectFrom("dataStore").selectAll().where("tenant", "=", tenant).where("recordId", "=", recordId).where("dataCid", "=", dataCid).executeTakeFirst();
164
- if (!result) {
165
- return void 0;
166
- }
167
- return {
168
- dataSize: result.data.length,
169
- dataStream: new import_readable_stream.Readable({
170
- read() {
171
- this.push(Buffer.from(result.data));
172
- this.push(null);
173
- }
174
- })
175
- };
176
- }
177
- async put(tenant, recordId, dataCid, dataStream) {
178
- if (!this.#db) {
179
- throw new Error("Connection to database not open. Call `open` before using `put`.");
180
- }
181
- const bytes = await import_dwn_sdk_js.DataStream.toBytes(dataStream);
182
- const data = Buffer.from(bytes);
183
- await this.#db.insertInto("dataStore").values({ tenant, recordId, dataCid, data }).executeTakeFirstOrThrow();
184
- return {
185
- dataSize: bytes.length
186
- };
187
- }
188
- async delete(tenant, recordId, dataCid) {
189
- if (!this.#db) {
190
- throw new Error("Connection to database not open. Call `open` before using `delete`.");
191
- }
192
- await this.#db.deleteFrom("dataStore").where("tenant", "=", tenant).where("recordId", "=", recordId).where("dataCid", "=", dataCid).execute();
193
- }
194
- async clear() {
195
- if (!this.#db) {
196
- throw new Error("Connection to database not open. Call `open` before using `clear`.");
197
- }
198
- await this.#db.deleteFrom("dataStore").execute();
199
- }
200
- };
201
-
202
- // dist/esm/src/utils/filter.js
203
- var import_kysely5 = require("kysely");
204
-
205
- // dist/esm/src/utils/sanitize.js
206
- function extractTagsAndSanitizeIndexes(records) {
207
- const tags = {};
208
- const indexes = { ...records };
209
- sanitizeIndexes(indexes);
210
- for (let key in indexes) {
211
- if (key.startsWith("tag.")) {
212
- let value = indexes[key];
213
- delete indexes[key];
214
- tags[key.slice(4)] = value;
215
- }
216
- }
217
- return { tags, indexes };
218
- }
219
- function sanitizeIndexes(records) {
220
- for (let key in records) {
221
- let value = records[key];
222
- if (Array.isArray(value)) {
223
- const sanitizedValues = [];
224
- for (const valueItem of value) {
225
- sanitizedValues.push(sanitizedValue(valueItem));
226
- }
227
- records[key] = sanitizedValues;
228
- continue;
229
- }
230
- records[key] = sanitizedValue(value);
231
- }
232
- }
233
- function sanitizedValue(value) {
234
- switch (typeof value) {
235
- case "boolean":
236
- return value ? 1 : 0;
237
- default:
238
- return value;
239
- }
240
- }
241
- function sanitizeFiltersAndSeparateTags(filters) {
242
- const extractedFilters = [];
243
- for (const filter of filters) {
244
- const tagFilter = {};
245
- const nonTagFilter = {};
246
- for (let key in filter) {
247
- const value = sanitizeFilterValue(filter[key]);
248
- if (key.startsWith("tag.")) {
249
- tagFilter[key.slice(4)] = value;
250
- } else {
251
- nonTagFilter[key] = value;
252
- }
253
- }
254
- extractedFilters.push({
255
- tags: tagFilter,
256
- filter: nonTagFilter
257
- });
258
- }
259
- return extractedFilters;
260
- }
261
- function sanitizeFilterValue(value) {
262
- switch (typeof value) {
263
- case "boolean":
264
- return value ? 1 : 0;
265
- default:
266
- return value;
267
- }
268
- }
269
-
270
- // dist/esm/src/utils/filter.js
271
- function filterSelectQuery(filters, query) {
272
- const sanitizedFilters = sanitizeFiltersAndSeparateTags(filters);
273
- return query.where((eb) => (
274
- // evaluate the filters as an OR expression.
275
- eb.or(sanitizedFilters.map(({ filter, tags }) => {
276
- const andOperands = [];
277
- processFilter(eb, andOperands, filter);
278
- processTags(eb, andOperands, tags);
279
- return eb.and(andOperands);
280
- }))
281
- ));
282
- }
283
- function processFilter(eb, andOperands, filter) {
284
- for (let property in filter) {
285
- const value = filter[property];
286
- const column = new import_kysely5.DynamicModule().ref(property);
287
- if (Array.isArray(value)) {
288
- andOperands.push(eb(column, "in", value));
289
- } else if (typeof value === "object") {
290
- if (value.gt) {
291
- andOperands.push(eb(column, ">", sanitizedValue(value.gt)));
292
- }
293
- if (value.gte) {
294
- andOperands.push(eb(column, ">=", sanitizedValue(value.gte)));
295
- }
296
- if (value.lt) {
297
- andOperands.push(eb(column, "<", sanitizedValue(value.lt)));
298
- }
299
- if (value.lte) {
300
- andOperands.push(eb(column, "<=", sanitizedValue(value.lte)));
301
- }
302
- } else {
303
- andOperands.push(eb(column, "=", sanitizedValue(value)));
304
- }
305
- }
306
- }
307
- function processTags(eb, andOperands, tags) {
308
- const tagColumn = new import_kysely5.DynamicModule().ref("tag");
309
- const valueNumber = new import_kysely5.DynamicModule().ref("valueNumber");
310
- const valueString = new import_kysely5.DynamicModule().ref("valueString");
311
- for (let property in tags) {
312
- andOperands.push(eb(tagColumn, "=", property));
313
- const value = tags[property];
314
- if (Array.isArray(value)) {
315
- if (value.some((val) => typeof val === "number")) {
316
- andOperands.push(eb(valueNumber, "in", value));
317
- } else {
318
- andOperands.push(eb(valueString, "in", value.map((v) => String(v))));
319
- }
320
- } else if (typeof value === "object") {
321
- if (value.gt) {
322
- if (typeof value.gt === "number") {
323
- andOperands.push(eb(valueNumber, ">", value.gt));
324
- } else {
325
- andOperands.push(eb(valueString, ">", String(value.gt)));
326
- }
327
- }
328
- if (value.gte) {
329
- if (typeof value.gte === "number") {
330
- andOperands.push(eb(valueNumber, ">=", value.gte));
331
- } else {
332
- andOperands.push(eb(valueString, ">=", String(value.gte)));
333
- }
334
- }
335
- if (value.lt) {
336
- if (typeof value.lt === "number") {
337
- andOperands.push(eb(valueNumber, "<", value.lt));
338
- } else {
339
- andOperands.push(eb(valueString, "<", String(value.lt)));
340
- }
341
- }
342
- if (value.lte) {
343
- if (typeof value.lte === "number") {
344
- andOperands.push(eb(valueNumber, "<=", value.lte));
345
- } else {
346
- andOperands.push(eb(valueString, "<=", String(value.lte)));
347
- }
348
- }
349
- } else {
350
- if (typeof value === "number") {
351
- andOperands.push(eb(valueNumber, "=", value));
352
- } else {
353
- andOperands.push(eb(valueString, "=", String(value)));
354
- }
355
- }
356
- }
357
- }
358
-
359
- // dist/esm/src/event-log-sql.js
360
- var import_kysely6 = require("kysely");
361
-
362
- // dist/esm/src/utils/transaction.js
363
- async function executeWithRetryIfDatabaseIsLocked(database, operation) {
364
- let retryCount = 0;
365
- let success = false;
366
- while (!success) {
367
- try {
368
- await database.transaction().execute(operation);
369
- success = true;
370
- } catch (error) {
371
- if (error.code === "SQLITE_BUSY") {
372
- retryCount++;
373
- console.log(`Database is locked when attempting SQL operation, retrying #${retryCount}...`);
374
- } else {
375
- throw error;
376
- }
377
- }
378
- }
379
- }
380
-
381
- // dist/esm/src/utils/tags.js
382
- var TagTables = class {
383
- dialect;
384
- table;
385
- /**
386
- * @param dialect the target dialect, necessary for returning the `insertId`
387
- * @param table the DB Table in order to index the tags and values in the correct tables. Choice between `messageStoreMessages` and `eventLogMessages`
388
- */
389
- constructor(dialect, table) {
390
- this.dialect = dialect;
391
- this.table = table;
392
- }
393
- /**
394
- * Inserts the given tags associated with the given foreign `insertId`.
395
- */
396
- async executeTagsInsert(foreignInsertId, tags, tx) {
397
- const tagTable = this.table === "messageStoreMessages" ? "messageStoreRecordsTags" : "eventLogRecordsTags";
398
- const foreignKeyReference = tagTable === "messageStoreRecordsTags" ? { messageInsertId: foreignInsertId } : { eventWatermark: foreignInsertId };
399
- for (const tag in tags) {
400
- const tagValues = tags[tag];
401
- const values = Array.isArray(tagValues) ? tagValues : [tagValues];
402
- for (const value of values) {
403
- const tagInsertValue = sanitizedValue(value);
404
- const insertValues = {
405
- tag,
406
- valueNumber: typeof tagInsertValue === "number" ? tagInsertValue : null,
407
- valueString: typeof tagInsertValue === "string" ? tagInsertValue : null,
408
- ...foreignKeyReference
409
- };
410
- await this.dialect.insertThenReturnId(tx, tagTable, insertValues, "id as insertId").executeTakeFirstOrThrow();
411
- }
412
- }
413
- }
414
- };
415
-
416
- // dist/esm/src/event-log-sql.js
417
- var EventLogSql = class {
418
- #dialect;
419
- #db = null;
420
- #tags;
421
- constructor(dialect) {
422
- this.#dialect = dialect;
423
- this.#tags = new TagTables(dialect, "eventLogMessages");
424
- }
425
- async open() {
426
- if (this.#db) {
427
- return;
428
- }
429
- this.#db = new import_kysely6.Kysely({ dialect: this.#dialect });
430
- let createTable = this.#db.schema.createTable("eventLogMessages").ifNotExists().addColumn("tenant", "varchar(255)", (col) => col.notNull()).addColumn("messageCid", "varchar(60)", (col) => col.notNull()).addColumn("interface", "varchar(20)").addColumn("method", "varchar(20)").addColumn("recordId", "varchar(60)").addColumn("entryId", "varchar(60)").addColumn("parentId", "varchar(60)").addColumn("protocol", "varchar(200)").addColumn("protocolPath", "varchar(200)").addColumn("contextId", "varchar(500)").addColumn("schema", "varchar(200)").addColumn("author", "varchar(255)").addColumn("recipient", "varchar(255)").addColumn("messageTimestamp", "varchar(30)").addColumn("dateCreated", "varchar(30)").addColumn("datePublished", "varchar(30)").addColumn("isLatestBaseState", "boolean").addColumn("published", "boolean").addColumn("prune", "boolean").addColumn("dataFormat", "varchar(30)").addColumn("dataCid", "varchar(60)").addColumn("dataSize", "integer").addColumn("attester", "text").addColumn("permissionGrantId", "varchar(60)").addColumn("latest", "text");
431
- let createRecordsTagsTable = this.#db.schema.createTable("eventLogRecordsTags").ifNotExists().addColumn("tag", "text", (col) => col.notNull()).addColumn("valueString", "text").addColumn("valueNumber", "decimal");
432
- createTable = this.#dialect.addAutoIncrementingColumn(createTable, "watermark", (col) => col.primaryKey());
433
- createRecordsTagsTable = this.#dialect.addAutoIncrementingColumn(createRecordsTagsTable, "id", (col) => col.primaryKey());
434
- createRecordsTagsTable = this.#dialect.addReferencedColumn(createRecordsTagsTable, "eventLogRecordsTags", "eventWatermark", "integer", "eventLogMessages", "watermark", "cascade");
435
- await createTable.execute();
436
- await createRecordsTagsTable.execute();
437
- }
438
- async close() {
439
- await this.#db?.destroy();
440
- this.#db = null;
441
- }
442
- async append(tenant, messageCid, indexes) {
443
- if (!this.#db) {
444
- throw new Error("Connection to database not open. Call `open` before using `append`.");
445
- }
446
- const putEventOperation = this.constructPutEventOperation({ tenant, messageCid, indexes });
447
- await executeWithRetryIfDatabaseIsLocked(this.#db, putEventOperation);
448
- }
449
- /**
450
- * Constructs a transactional operation to insert an event into the database.
451
- */
452
- constructPutEventOperation(queryOptions) {
453
- const { tenant, messageCid, indexes } = queryOptions;
454
- const { indexes: appendIndexes, tags } = extractTagsAndSanitizeIndexes(indexes);
455
- return async (tx) => {
456
- const eventIndexValues = {
457
- tenant,
458
- messageCid,
459
- ...appendIndexes
460
- };
461
- const result = await this.#dialect.insertThenReturnId(tx, "eventLogMessages", eventIndexValues, "watermark as insertId").executeTakeFirstOrThrow();
462
- if (Object.keys(tags).length > 0) {
463
- await this.#tags.executeTagsInsert(result.insertId, tags, tx);
464
- }
465
- };
466
- }
467
- async getEvents(tenant, cursor) {
468
- return this.queryEvents(tenant, [], cursor);
469
- }
470
- async queryEvents(tenant, filters, cursor) {
471
- if (!this.#db) {
472
- throw new Error("Connection to database not open. Call `open` before using `queryEvents`.");
473
- }
474
- let query = this.#db.selectFrom("eventLogMessages").leftJoin("eventLogRecordsTags", "eventLogRecordsTags.eventWatermark", "eventLogMessages.watermark").select("messageCid").distinct().select("watermark").where("tenant", "=", tenant);
475
- if (filters.length > 0) {
476
- query = filterSelectQuery(filters, query);
477
- }
478
- if (cursor !== void 0) {
479
- const cursorValue = cursor.value;
480
- const cursorMessageCid = cursor.messageCid;
481
- query = query.where(({ eb, refTuple, tuple }) => {
482
- return eb(refTuple("watermark", "messageCid"), ">", tuple(cursorValue, cursorMessageCid));
483
- });
484
- }
485
- query = query.orderBy("watermark", "asc").orderBy("messageCid", "asc");
486
- const events = [];
487
- let returnCursor;
488
- if (this.#dialect.isStreamingSupported) {
489
- for await (let { messageCid, watermark: value } of query.stream()) {
490
- events.push(messageCid);
491
- returnCursor = { messageCid, value };
492
- }
493
- } else {
494
- const results = await query.execute();
495
- for (let { messageCid, watermark: value } of results) {
496
- events.push(messageCid);
497
- returnCursor = { messageCid, value };
498
- }
499
- }
500
- return { events, cursor: returnCursor };
501
- }
502
- async deleteEventsByCid(tenant, messageCids) {
503
- if (!this.#db) {
504
- throw new Error("Connection to database not open. Call `open` before using `deleteEventsByCid`.");
505
- }
506
- if (messageCids.length === 0) {
507
- return;
508
- }
509
- await this.#db.deleteFrom("eventLogMessages").where("tenant", "=", tenant).where("messageCid", "in", messageCids).execute();
510
- }
511
- async clear() {
512
- if (!this.#db) {
513
- throw new Error("Connection to database not open. Call `open` before using `clear`.");
514
- }
515
- await this.#db.deleteFrom("eventLogMessages").execute();
516
- }
517
- };
518
-
519
- // dist/esm/src/message-store-sql.js
520
- var import_dwn_sdk_js2 = require("@enbox/dwn-sdk-js");
521
- var import_kysely7 = require("kysely");
522
-
523
- // ../../node_modules/.pnpm/multiformats@12.0.1/node_modules/multiformats/vendor/varint.js
524
- var encode_1 = encode;
525
- var MSB = 128;
526
- var REST = 127;
527
- var MSBALL = ~REST;
528
- var INT = Math.pow(2, 31);
529
- function encode(num, out, offset) {
530
- out = out || [];
531
- offset = offset || 0;
532
- var oldOffset = offset;
533
- while (num >= INT) {
534
- out[offset++] = num & 255 | MSB;
535
- num /= 128;
536
- }
537
- while (num & MSBALL) {
538
- out[offset++] = num & 255 | MSB;
539
- num >>>= 7;
540
- }
541
- out[offset] = num | 0;
542
- encode.bytes = offset - oldOffset + 1;
543
- return out;
544
- }
545
- var decode = read;
546
- var MSB$1 = 128;
547
- var REST$1 = 127;
548
- function read(buf2, offset) {
549
- var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf2.length;
550
- do {
551
- if (counter >= l) {
552
- read.bytes = 0;
553
- throw new RangeError("Could not decode varint");
554
- }
555
- b = buf2[counter++];
556
- res += shift < 28 ? (b & REST$1) << shift : (b & REST$1) * Math.pow(2, shift);
557
- shift += 7;
558
- } while (b >= MSB$1);
559
- read.bytes = counter - offset;
560
- return res;
561
- }
562
- var N1 = Math.pow(2, 7);
563
- var N2 = Math.pow(2, 14);
564
- var N3 = Math.pow(2, 21);
565
- var N4 = Math.pow(2, 28);
566
- var N5 = Math.pow(2, 35);
567
- var N6 = Math.pow(2, 42);
568
- var N7 = Math.pow(2, 49);
569
- var N8 = Math.pow(2, 56);
570
- var N9 = Math.pow(2, 63);
571
- var length = function(value) {
572
- return value < N1 ? 1 : value < N2 ? 2 : value < N3 ? 3 : value < N4 ? 4 : value < N5 ? 5 : value < N6 ? 6 : value < N7 ? 7 : value < N8 ? 8 : value < N9 ? 9 : 10;
573
- };
574
- var varint = {
575
- encode: encode_1,
576
- decode,
577
- encodingLength: length
578
- };
579
- var _brrp_varint = varint;
580
- var varint_default = _brrp_varint;
581
-
582
- // ../../node_modules/.pnpm/multiformats@12.0.1/node_modules/multiformats/src/varint.js
583
- var decode2 = (data, offset = 0) => {
584
- const code2 = varint_default.decode(data, offset);
585
- return [code2, varint_default.decode.bytes];
586
- };
587
- var encodeTo = (int, target, offset = 0) => {
588
- varint_default.encode(int, target, offset);
589
- return target;
590
- };
591
- var encodingLength = (int) => {
592
- return varint_default.encodingLength(int);
593
- };
594
-
595
- // ../../node_modules/.pnpm/multiformats@12.0.1/node_modules/multiformats/src/bytes.js
596
- var empty = new Uint8Array(0);
597
- var equals = (aa, bb) => {
598
- if (aa === bb)
599
- return true;
600
- if (aa.byteLength !== bb.byteLength) {
601
- return false;
602
- }
603
- for (let ii = 0; ii < aa.byteLength; ii++) {
604
- if (aa[ii] !== bb[ii]) {
605
- return false;
606
- }
607
- }
608
- return true;
609
- };
610
- var coerce = (o) => {
611
- if (o instanceof Uint8Array && o.constructor.name === "Uint8Array")
612
- return o;
613
- if (o instanceof ArrayBuffer)
614
- return new Uint8Array(o);
615
- if (ArrayBuffer.isView(o)) {
616
- return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
617
- }
618
- throw new Error("Unknown type, must be binary type");
619
- };
620
-
621
- // ../../node_modules/.pnpm/multiformats@12.0.1/node_modules/multiformats/src/hashes/digest.js
622
- var create = (code2, digest) => {
623
- const size = digest.byteLength;
624
- const sizeOffset = encodingLength(code2);
625
- const digestOffset = sizeOffset + encodingLength(size);
626
- const bytes = new Uint8Array(digestOffset + size);
627
- encodeTo(code2, bytes, 0);
628
- encodeTo(size, bytes, sizeOffset);
629
- bytes.set(digest, digestOffset);
630
- return new Digest(code2, size, digest, bytes);
631
- };
632
- var decode3 = (multihash) => {
633
- const bytes = coerce(multihash);
634
- const [code2, sizeOffset] = decode2(bytes);
635
- const [size, digestOffset] = decode2(bytes.subarray(sizeOffset));
636
- const digest = bytes.subarray(sizeOffset + digestOffset);
637
- if (digest.byteLength !== size) {
638
- throw new Error("Incorrect length");
639
- }
640
- return new Digest(code2, size, digest, bytes);
641
- };
642
- var equals2 = (a, b) => {
643
- if (a === b) {
644
- return true;
645
- } else {
646
- const data = (
647
- /** @type {{code?:unknown, size?:unknown, bytes?:unknown}} */
648
- b
649
- );
650
- return a.code === data.code && a.size === data.size && data.bytes instanceof Uint8Array && equals(a.bytes, data.bytes);
651
- }
652
- };
653
- var Digest = class {
654
- /**
655
- * Creates a multihash digest.
656
- *
657
- * @param {Code} code
658
- * @param {Size} size
659
- * @param {Uint8Array} digest
660
- * @param {Uint8Array} bytes
661
- */
662
- constructor(code2, size, digest, bytes) {
663
- this.code = code2;
664
- this.size = size;
665
- this.digest = digest;
666
- this.bytes = bytes;
667
- }
668
- };
669
-
670
- // ../../node_modules/.pnpm/multiformats@12.0.1/node_modules/multiformats/vendor/base-x.js
671
- function base(ALPHABET, name2) {
672
- if (ALPHABET.length >= 255) {
673
- throw new TypeError("Alphabet too long");
674
- }
675
- var BASE_MAP = new Uint8Array(256);
676
- for (var j = 0; j < BASE_MAP.length; j++) {
677
- BASE_MAP[j] = 255;
678
- }
679
- for (var i = 0; i < ALPHABET.length; i++) {
680
- var x = ALPHABET.charAt(i);
681
- var xc = x.charCodeAt(0);
682
- if (BASE_MAP[xc] !== 255) {
683
- throw new TypeError(x + " is ambiguous");
684
- }
685
- BASE_MAP[xc] = i;
686
- }
687
- var BASE = ALPHABET.length;
688
- var LEADER = ALPHABET.charAt(0);
689
- var FACTOR = Math.log(BASE) / Math.log(256);
690
- var iFACTOR = Math.log(256) / Math.log(BASE);
691
- function encode6(source) {
692
- if (source instanceof Uint8Array)
693
- ;
694
- else if (ArrayBuffer.isView(source)) {
695
- source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
696
- } else if (Array.isArray(source)) {
697
- source = Uint8Array.from(source);
698
- }
699
- if (!(source instanceof Uint8Array)) {
700
- throw new TypeError("Expected Uint8Array");
701
- }
702
- if (source.length === 0) {
703
- return "";
704
- }
705
- var zeroes = 0;
706
- var length2 = 0;
707
- var pbegin = 0;
708
- var pend = source.length;
709
- while (pbegin !== pend && source[pbegin] === 0) {
710
- pbegin++;
711
- zeroes++;
712
- }
713
- var size = (pend - pbegin) * iFACTOR + 1 >>> 0;
714
- var b58 = new Uint8Array(size);
715
- while (pbegin !== pend) {
716
- var carry = source[pbegin];
717
- var i2 = 0;
718
- for (var it1 = size - 1; (carry !== 0 || i2 < length2) && it1 !== -1; it1--, i2++) {
719
- carry += 256 * b58[it1] >>> 0;
720
- b58[it1] = carry % BASE >>> 0;
721
- carry = carry / BASE >>> 0;
722
- }
723
- if (carry !== 0) {
724
- throw new Error("Non-zero carry");
725
- }
726
- length2 = i2;
727
- pbegin++;
728
- }
729
- var it2 = size - length2;
730
- while (it2 !== size && b58[it2] === 0) {
731
- it2++;
732
- }
733
- var str = LEADER.repeat(zeroes);
734
- for (; it2 < size; ++it2) {
735
- str += ALPHABET.charAt(b58[it2]);
736
- }
737
- return str;
738
- }
739
- function decodeUnsafe(source) {
740
- if (typeof source !== "string") {
741
- throw new TypeError("Expected String");
742
- }
743
- if (source.length === 0) {
744
- return new Uint8Array();
745
- }
746
- var psz = 0;
747
- if (source[psz] === " ") {
748
- return;
749
- }
750
- var zeroes = 0;
751
- var length2 = 0;
752
- while (source[psz] === LEADER) {
753
- zeroes++;
754
- psz++;
755
- }
756
- var size = (source.length - psz) * FACTOR + 1 >>> 0;
757
- var b256 = new Uint8Array(size);
758
- while (source[psz]) {
759
- var carry = BASE_MAP[source.charCodeAt(psz)];
760
- if (carry === 255) {
761
- return;
762
- }
763
- var i2 = 0;
764
- for (var it3 = size - 1; (carry !== 0 || i2 < length2) && it3 !== -1; it3--, i2++) {
765
- carry += BASE * b256[it3] >>> 0;
766
- b256[it3] = carry % 256 >>> 0;
767
- carry = carry / 256 >>> 0;
768
- }
769
- if (carry !== 0) {
770
- throw new Error("Non-zero carry");
771
- }
772
- length2 = i2;
773
- psz++;
774
- }
775
- if (source[psz] === " ") {
776
- return;
777
- }
778
- var it4 = size - length2;
779
- while (it4 !== size && b256[it4] === 0) {
780
- it4++;
781
- }
782
- var vch = new Uint8Array(zeroes + (size - it4));
783
- var j2 = zeroes;
784
- while (it4 !== size) {
785
- vch[j2++] = b256[it4++];
786
- }
787
- return vch;
788
- }
789
- function decode8(string) {
790
- var buffer2 = decodeUnsafe(string);
791
- if (buffer2) {
792
- return buffer2;
793
- }
794
- throw new Error(`Non-${name2} character`);
795
- }
796
- return {
797
- encode: encode6,
798
- decodeUnsafe,
799
- decode: decode8
800
- };
801
- }
802
- var src = base;
803
- var _brrp__multiformats_scope_baseX = src;
804
- var base_x_default = _brrp__multiformats_scope_baseX;
805
-
806
- // ../../node_modules/.pnpm/multiformats@12.0.1/node_modules/multiformats/src/bases/base.js
807
- var Encoder = class {
808
- /**
809
- * @param {Base} name
810
- * @param {Prefix} prefix
811
- * @param {(bytes:Uint8Array) => string} baseEncode
812
- */
813
- constructor(name2, prefix, baseEncode) {
814
- this.name = name2;
815
- this.prefix = prefix;
816
- this.baseEncode = baseEncode;
817
- }
818
- /**
819
- * @param {Uint8Array} bytes
820
- * @returns {API.Multibase<Prefix>}
821
- */
822
- encode(bytes) {
823
- if (bytes instanceof Uint8Array) {
824
- return `${this.prefix}${this.baseEncode(bytes)}`;
825
- } else {
826
- throw Error("Unknown type, must be binary type");
827
- }
828
- }
829
- };
830
- var Decoder = class {
831
- /**
832
- * @param {Base} name
833
- * @param {Prefix} prefix
834
- * @param {(text:string) => Uint8Array} baseDecode
835
- */
836
- constructor(name2, prefix, baseDecode) {
837
- this.name = name2;
838
- this.prefix = prefix;
839
- if (prefix.codePointAt(0) === void 0) {
840
- throw new Error("Invalid prefix character");
841
- }
842
- this.prefixCodePoint = /** @type {number} */
843
- prefix.codePointAt(0);
844
- this.baseDecode = baseDecode;
845
- }
846
- /**
847
- * @param {string} text
848
- */
849
- decode(text) {
850
- if (typeof text === "string") {
851
- if (text.codePointAt(0) !== this.prefixCodePoint) {
852
- throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
853
- }
854
- return this.baseDecode(text.slice(this.prefix.length));
855
- } else {
856
- throw Error("Can only multibase decode strings");
857
- }
858
- }
859
- /**
860
- * @template {string} OtherPrefix
861
- * @param {API.UnibaseDecoder<OtherPrefix>|ComposedDecoder<OtherPrefix>} decoder
862
- * @returns {ComposedDecoder<Prefix|OtherPrefix>}
863
- */
864
- or(decoder) {
865
- return or(this, decoder);
866
- }
867
- };
868
- var ComposedDecoder = class {
869
- /**
870
- * @param {Decoders<Prefix>} decoders
871
- */
872
- constructor(decoders) {
873
- this.decoders = decoders;
874
- }
875
- /**
876
- * @template {string} OtherPrefix
877
- * @param {API.UnibaseDecoder<OtherPrefix>|ComposedDecoder<OtherPrefix>} decoder
878
- * @returns {ComposedDecoder<Prefix|OtherPrefix>}
879
- */
880
- or(decoder) {
881
- return or(this, decoder);
882
- }
883
- /**
884
- * @param {string} input
885
- * @returns {Uint8Array}
886
- */
887
- decode(input) {
888
- const prefix = (
889
- /** @type {Prefix} */
890
- input[0]
891
- );
892
- const decoder = this.decoders[prefix];
893
- if (decoder) {
894
- return decoder.decode(input);
895
- } else {
896
- throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
897
- }
898
- }
899
- };
900
- var or = (left, right) => new ComposedDecoder(
901
- /** @type {Decoders<L|R>} */
902
- {
903
- ...left.decoders || { [
904
- /** @type API.UnibaseDecoder<L> */
905
- left.prefix
906
- ]: left },
907
- ...right.decoders || { [
908
- /** @type API.UnibaseDecoder<R> */
909
- right.prefix
910
- ]: right }
911
- }
912
- );
913
- var Codec = class {
914
- /**
915
- * @param {Base} name
916
- * @param {Prefix} prefix
917
- * @param {(bytes:Uint8Array) => string} baseEncode
918
- * @param {(text:string) => Uint8Array} baseDecode
919
- */
920
- constructor(name2, prefix, baseEncode, baseDecode) {
921
- this.name = name2;
922
- this.prefix = prefix;
923
- this.baseEncode = baseEncode;
924
- this.baseDecode = baseDecode;
925
- this.encoder = new Encoder(name2, prefix, baseEncode);
926
- this.decoder = new Decoder(name2, prefix, baseDecode);
927
- }
928
- /**
929
- * @param {Uint8Array} input
930
- */
931
- encode(input) {
932
- return this.encoder.encode(input);
933
- }
934
- /**
935
- * @param {string} input
936
- */
937
- decode(input) {
938
- return this.decoder.decode(input);
939
- }
940
- };
941
- var from = ({ name: name2, prefix, encode: encode6, decode: decode8 }) => new Codec(name2, prefix, encode6, decode8);
942
- var baseX = ({ prefix, name: name2, alphabet }) => {
943
- const { encode: encode6, decode: decode8 } = base_x_default(alphabet, name2);
944
- return from({
945
- prefix,
946
- name: name2,
947
- encode: encode6,
948
- /**
949
- * @param {string} text
950
- */
951
- decode: (text) => coerce(decode8(text))
952
- });
953
- };
954
- var decode4 = (string, alphabet, bitsPerChar, name2) => {
955
- const codes = {};
956
- for (let i = 0; i < alphabet.length; ++i) {
957
- codes[alphabet[i]] = i;
958
- }
959
- let end = string.length;
960
- while (string[end - 1] === "=") {
961
- --end;
962
- }
963
- const out = new Uint8Array(end * bitsPerChar / 8 | 0);
964
- let bits = 0;
965
- let buffer2 = 0;
966
- let written = 0;
967
- for (let i = 0; i < end; ++i) {
968
- const value = codes[string[i]];
969
- if (value === void 0) {
970
- throw new SyntaxError(`Non-${name2} character`);
971
- }
972
- buffer2 = buffer2 << bitsPerChar | value;
973
- bits += bitsPerChar;
974
- if (bits >= 8) {
975
- bits -= 8;
976
- out[written++] = 255 & buffer2 >> bits;
977
- }
978
- }
979
- if (bits >= bitsPerChar || 255 & buffer2 << 8 - bits) {
980
- throw new SyntaxError("Unexpected end of data");
981
- }
982
- return out;
983
- };
984
- var encode2 = (data, alphabet, bitsPerChar) => {
985
- const pad = alphabet[alphabet.length - 1] === "=";
986
- const mask = (1 << bitsPerChar) - 1;
987
- let out = "";
988
- let bits = 0;
989
- let buffer2 = 0;
990
- for (let i = 0; i < data.length; ++i) {
991
- buffer2 = buffer2 << 8 | data[i];
992
- bits += 8;
993
- while (bits > bitsPerChar) {
994
- bits -= bitsPerChar;
995
- out += alphabet[mask & buffer2 >> bits];
996
- }
997
- }
998
- if (bits) {
999
- out += alphabet[mask & buffer2 << bitsPerChar - bits];
1000
- }
1001
- if (pad) {
1002
- while (out.length * bitsPerChar & 7) {
1003
- out += "=";
1004
- }
1005
- }
1006
- return out;
1007
- };
1008
- var rfc4648 = ({ name: name2, prefix, bitsPerChar, alphabet }) => {
1009
- return from({
1010
- prefix,
1011
- name: name2,
1012
- encode(input) {
1013
- return encode2(input, alphabet, bitsPerChar);
1014
- },
1015
- decode(input) {
1016
- return decode4(input, alphabet, bitsPerChar, name2);
1017
- }
1018
- });
1019
- };
1020
-
1021
- // ../../node_modules/.pnpm/multiformats@12.0.1/node_modules/multiformats/src/bases/base58.js
1022
- var base58btc = baseX({
1023
- name: "base58btc",
1024
- prefix: "z",
1025
- alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
1026
- });
1027
- var base58flickr = baseX({
1028
- name: "base58flickr",
1029
- prefix: "Z",
1030
- alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
1031
- });
1032
-
1033
- // ../../node_modules/.pnpm/multiformats@12.0.1/node_modules/multiformats/src/bases/base32.js
1034
- var base32 = rfc4648({
1035
- prefix: "b",
1036
- name: "base32",
1037
- alphabet: "abcdefghijklmnopqrstuvwxyz234567",
1038
- bitsPerChar: 5
1039
- });
1040
- var base32upper = rfc4648({
1041
- prefix: "B",
1042
- name: "base32upper",
1043
- alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",
1044
- bitsPerChar: 5
1045
- });
1046
- var base32pad = rfc4648({
1047
- prefix: "c",
1048
- name: "base32pad",
1049
- alphabet: "abcdefghijklmnopqrstuvwxyz234567=",
1050
- bitsPerChar: 5
1051
- });
1052
- var base32padupper = rfc4648({
1053
- prefix: "C",
1054
- name: "base32padupper",
1055
- alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",
1056
- bitsPerChar: 5
1057
- });
1058
- var base32hex = rfc4648({
1059
- prefix: "v",
1060
- name: "base32hex",
1061
- alphabet: "0123456789abcdefghijklmnopqrstuv",
1062
- bitsPerChar: 5
1063
- });
1064
- var base32hexupper = rfc4648({
1065
- prefix: "V",
1066
- name: "base32hexupper",
1067
- alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV",
1068
- bitsPerChar: 5
1069
- });
1070
- var base32hexpad = rfc4648({
1071
- prefix: "t",
1072
- name: "base32hexpad",
1073
- alphabet: "0123456789abcdefghijklmnopqrstuv=",
1074
- bitsPerChar: 5
1075
- });
1076
- var base32hexpadupper = rfc4648({
1077
- prefix: "T",
1078
- name: "base32hexpadupper",
1079
- alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=",
1080
- bitsPerChar: 5
1081
- });
1082
- var base32z = rfc4648({
1083
- prefix: "h",
1084
- name: "base32z",
1085
- alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769",
1086
- bitsPerChar: 5
1087
- });
1088
-
1089
- // ../../node_modules/.pnpm/multiformats@12.0.1/node_modules/multiformats/src/cid.js
1090
- var format = (link, base2) => {
1091
- const { bytes, version } = link;
1092
- switch (version) {
1093
- case 0:
1094
- return toStringV0(
1095
- bytes,
1096
- baseCache(link),
1097
- /** @type {API.MultibaseEncoder<"z">} */
1098
- base2 || base58btc.encoder
1099
- );
1100
- default:
1101
- return toStringV1(
1102
- bytes,
1103
- baseCache(link),
1104
- /** @type {API.MultibaseEncoder<Prefix>} */
1105
- base2 || base32.encoder
1106
- );
1107
- }
1108
- };
1109
- var cache = /* @__PURE__ */ new WeakMap();
1110
- var baseCache = (cid) => {
1111
- const baseCache2 = cache.get(cid);
1112
- if (baseCache2 == null) {
1113
- const baseCache3 = /* @__PURE__ */ new Map();
1114
- cache.set(cid, baseCache3);
1115
- return baseCache3;
1116
- }
1117
- return baseCache2;
1118
- };
1119
- var CID = class _CID {
1120
- /**
1121
- * @param {Version} version - Version of the CID
1122
- * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
1123
- * @param {API.MultihashDigest<Alg>} multihash - (Multi)hash of the of the content.
1124
- * @param {Uint8Array} bytes
1125
- *
1126
- */
1127
- constructor(version, code2, multihash, bytes) {
1128
- this.code = code2;
1129
- this.version = version;
1130
- this.multihash = multihash;
1131
- this.bytes = bytes;
1132
- this["/"] = bytes;
1133
- }
1134
- /**
1135
- * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
1136
- * please either use `CID.asCID(cid)` or switch to new signalling mechanism
1137
- *
1138
- * @deprecated
1139
- */
1140
- get asCID() {
1141
- return this;
1142
- }
1143
- // ArrayBufferView
1144
- get byteOffset() {
1145
- return this.bytes.byteOffset;
1146
- }
1147
- // ArrayBufferView
1148
- get byteLength() {
1149
- return this.bytes.byteLength;
1150
- }
1151
- /**
1152
- * @returns {CID<Data, API.DAG_PB, API.SHA_256, 0>}
1153
- */
1154
- toV0() {
1155
- switch (this.version) {
1156
- case 0: {
1157
- return (
1158
- /** @type {CID<Data, API.DAG_PB, API.SHA_256, 0>} */
1159
- this
1160
- );
1161
- }
1162
- case 1: {
1163
- const { code: code2, multihash } = this;
1164
- if (code2 !== DAG_PB_CODE) {
1165
- throw new Error("Cannot convert a non dag-pb CID to CIDv0");
1166
- }
1167
- if (multihash.code !== SHA_256_CODE) {
1168
- throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");
1169
- }
1170
- return (
1171
- /** @type {CID<Data, API.DAG_PB, API.SHA_256, 0>} */
1172
- _CID.createV0(
1173
- /** @type {API.MultihashDigest<API.SHA_256>} */
1174
- multihash
1175
- )
1176
- );
1177
- }
1178
- default: {
1179
- throw Error(
1180
- `Can not convert CID version ${this.version} to version 0. This is a bug please report`
1181
- );
1182
- }
1183
- }
1184
- }
1185
- /**
1186
- * @returns {CID<Data, Format, Alg, 1>}
1187
- */
1188
- toV1() {
1189
- switch (this.version) {
1190
- case 0: {
1191
- const { code: code2, digest } = this.multihash;
1192
- const multihash = create(code2, digest);
1193
- return (
1194
- /** @type {CID<Data, Format, Alg, 1>} */
1195
- _CID.createV1(this.code, multihash)
1196
- );
1197
- }
1198
- case 1: {
1199
- return (
1200
- /** @type {CID<Data, Format, Alg, 1>} */
1201
- this
1202
- );
1203
- }
1204
- default: {
1205
- throw Error(
1206
- `Can not convert CID version ${this.version} to version 1. This is a bug please report`
1207
- );
1208
- }
1209
- }
1210
- }
1211
- /**
1212
- * @param {unknown} other
1213
- * @returns {other is CID<Data, Format, Alg, Version>}
1214
- */
1215
- equals(other) {
1216
- return _CID.equals(this, other);
1217
- }
1218
- /**
1219
- * @template {unknown} Data
1220
- * @template {number} Format
1221
- * @template {number} Alg
1222
- * @template {API.Version} Version
1223
- * @param {API.Link<Data, Format, Alg, Version>} self
1224
- * @param {unknown} other
1225
- * @returns {other is CID}
1226
- */
1227
- static equals(self, other) {
1228
- const unknown = (
1229
- /** @type {{code?:unknown, version?:unknown, multihash?:unknown}} */
1230
- other
1231
- );
1232
- return unknown && self.code === unknown.code && self.version === unknown.version && equals2(self.multihash, unknown.multihash);
1233
- }
1234
- /**
1235
- * @param {API.MultibaseEncoder<string>} [base]
1236
- * @returns {string}
1237
- */
1238
- toString(base2) {
1239
- return format(this, base2);
1240
- }
1241
- toJSON() {
1242
- return { "/": format(this) };
1243
- }
1244
- link() {
1245
- return this;
1246
- }
1247
- get [Symbol.toStringTag]() {
1248
- return "CID";
1249
- }
1250
- // Legacy
1251
- [Symbol.for("nodejs.util.inspect.custom")]() {
1252
- return `CID(${this.toString()})`;
1253
- }
1254
- /**
1255
- * Takes any input `value` and returns a `CID` instance if it was
1256
- * a `CID` otherwise returns `null`. If `value` is instanceof `CID`
1257
- * it will return value back. If `value` is not instance of this CID
1258
- * class, but is compatible CID it will return new instance of this
1259
- * `CID` class. Otherwise returns null.
1260
- *
1261
- * This allows two different incompatible versions of CID library to
1262
- * co-exist and interop as long as binary interface is compatible.
1263
- *
1264
- * @template {unknown} Data
1265
- * @template {number} Format
1266
- * @template {number} Alg
1267
- * @template {API.Version} Version
1268
- * @template {unknown} U
1269
- * @param {API.Link<Data, Format, Alg, Version>|U} input
1270
- * @returns {CID<Data, Format, Alg, Version>|null}
1271
- */
1272
- static asCID(input) {
1273
- if (input == null) {
1274
- return null;
1275
- }
1276
- const value = (
1277
- /** @type {any} */
1278
- input
1279
- );
1280
- if (value instanceof _CID) {
1281
- return value;
1282
- } else if (value["/"] != null && value["/"] === value.bytes || value.asCID === value) {
1283
- const { version, code: code2, multihash, bytes } = value;
1284
- return new _CID(
1285
- version,
1286
- code2,
1287
- /** @type {API.MultihashDigest<Alg>} */
1288
- multihash,
1289
- bytes || encodeCID(version, code2, multihash.bytes)
1290
- );
1291
- } else if (value[cidSymbol] === true) {
1292
- const { version, multihash, code: code2 } = value;
1293
- const digest = (
1294
- /** @type {API.MultihashDigest<Alg>} */
1295
- decode3(multihash)
1296
- );
1297
- return _CID.create(version, code2, digest);
1298
- } else {
1299
- return null;
1300
- }
1301
- }
1302
- /**
1303
- *
1304
- * @template {unknown} Data
1305
- * @template {number} Format
1306
- * @template {number} Alg
1307
- * @template {API.Version} Version
1308
- * @param {Version} version - Version of the CID
1309
- * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
1310
- * @param {API.MultihashDigest<Alg>} digest - (Multi)hash of the of the content.
1311
- * @returns {CID<Data, Format, Alg, Version>}
1312
- */
1313
- static create(version, code2, digest) {
1314
- if (typeof code2 !== "number") {
1315
- throw new Error("String codecs are no longer supported");
1316
- }
1317
- if (!(digest.bytes instanceof Uint8Array)) {
1318
- throw new Error("Invalid digest");
1319
- }
1320
- switch (version) {
1321
- case 0: {
1322
- if (code2 !== DAG_PB_CODE) {
1323
- throw new Error(
1324
- `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`
1325
- );
1326
- } else {
1327
- return new _CID(version, code2, digest, digest.bytes);
1328
- }
1329
- }
1330
- case 1: {
1331
- const bytes = encodeCID(version, code2, digest.bytes);
1332
- return new _CID(version, code2, digest, bytes);
1333
- }
1334
- default: {
1335
- throw new Error("Invalid version");
1336
- }
1337
- }
1338
- }
1339
- /**
1340
- * Simplified version of `create` for CIDv0.
1341
- *
1342
- * @template {unknown} [T=unknown]
1343
- * @param {API.MultihashDigest<typeof SHA_256_CODE>} digest - Multihash.
1344
- * @returns {CID<T, typeof DAG_PB_CODE, typeof SHA_256_CODE, 0>}
1345
- */
1346
- static createV0(digest) {
1347
- return _CID.create(0, DAG_PB_CODE, digest);
1348
- }
1349
- /**
1350
- * Simplified version of `create` for CIDv1.
1351
- *
1352
- * @template {unknown} Data
1353
- * @template {number} Code
1354
- * @template {number} Alg
1355
- * @param {Code} code - Content encoding format code.
1356
- * @param {API.MultihashDigest<Alg>} digest - Miltihash of the content.
1357
- * @returns {CID<Data, Code, Alg, 1>}
1358
- */
1359
- static createV1(code2, digest) {
1360
- return _CID.create(1, code2, digest);
1361
- }
1362
- /**
1363
- * Decoded a CID from its binary representation. The byte array must contain
1364
- * only the CID with no additional bytes.
1365
- *
1366
- * An error will be thrown if the bytes provided do not contain a valid
1367
- * binary representation of a CID.
1368
- *
1369
- * @template {unknown} Data
1370
- * @template {number} Code
1371
- * @template {number} Alg
1372
- * @template {API.Version} Ver
1373
- * @param {API.ByteView<API.Link<Data, Code, Alg, Ver>>} bytes
1374
- * @returns {CID<Data, Code, Alg, Ver>}
1375
- */
1376
- static decode(bytes) {
1377
- const [cid, remainder] = _CID.decodeFirst(bytes);
1378
- if (remainder.length) {
1379
- throw new Error("Incorrect length");
1380
- }
1381
- return cid;
1382
- }
1383
- /**
1384
- * Decoded a CID from its binary representation at the beginning of a byte
1385
- * array.
1386
- *
1387
- * Returns an array with the first element containing the CID and the second
1388
- * element containing the remainder of the original byte array. The remainder
1389
- * will be a zero-length byte array if the provided bytes only contained a
1390
- * binary CID representation.
1391
- *
1392
- * @template {unknown} T
1393
- * @template {number} C
1394
- * @template {number} A
1395
- * @template {API.Version} V
1396
- * @param {API.ByteView<API.Link<T, C, A, V>>} bytes
1397
- * @returns {[CID<T, C, A, V>, Uint8Array]}
1398
- */
1399
- static decodeFirst(bytes) {
1400
- const specs = _CID.inspectBytes(bytes);
1401
- const prefixSize = specs.size - specs.multihashSize;
1402
- const multihashBytes = coerce(
1403
- bytes.subarray(prefixSize, prefixSize + specs.multihashSize)
1404
- );
1405
- if (multihashBytes.byteLength !== specs.multihashSize) {
1406
- throw new Error("Incorrect length");
1407
- }
1408
- const digestBytes = multihashBytes.subarray(
1409
- specs.multihashSize - specs.digestSize
1410
- );
1411
- const digest = new Digest(
1412
- specs.multihashCode,
1413
- specs.digestSize,
1414
- digestBytes,
1415
- multihashBytes
1416
- );
1417
- const cid = specs.version === 0 ? _CID.createV0(
1418
- /** @type {API.MultihashDigest<API.SHA_256>} */
1419
- digest
1420
- ) : _CID.createV1(specs.codec, digest);
1421
- return [
1422
- /** @type {CID<T, C, A, V>} */
1423
- cid,
1424
- bytes.subarray(specs.size)
1425
- ];
1426
- }
1427
- /**
1428
- * Inspect the initial bytes of a CID to determine its properties.
1429
- *
1430
- * Involves decoding up to 4 varints. Typically this will require only 4 to 6
1431
- * bytes but for larger multicodec code values and larger multihash digest
1432
- * lengths these varints can be quite large. It is recommended that at least
1433
- * 10 bytes be made available in the `initialBytes` argument for a complete
1434
- * inspection.
1435
- *
1436
- * @template {unknown} T
1437
- * @template {number} C
1438
- * @template {number} A
1439
- * @template {API.Version} V
1440
- * @param {API.ByteView<API.Link<T, C, A, V>>} initialBytes
1441
- * @returns {{ version:V, codec:C, multihashCode:A, digestSize:number, multihashSize:number, size:number }}
1442
- */
1443
- static inspectBytes(initialBytes) {
1444
- let offset = 0;
1445
- const next = () => {
1446
- const [i, length2] = decode2(initialBytes.subarray(offset));
1447
- offset += length2;
1448
- return i;
1449
- };
1450
- let version = (
1451
- /** @type {V} */
1452
- next()
1453
- );
1454
- let codec = (
1455
- /** @type {C} */
1456
- DAG_PB_CODE
1457
- );
1458
- if (
1459
- /** @type {number} */
1460
- version === 18
1461
- ) {
1462
- version = /** @type {V} */
1463
- 0;
1464
- offset = 0;
1465
- } else {
1466
- codec = /** @type {C} */
1467
- next();
1468
- }
1469
- if (version !== 0 && version !== 1) {
1470
- throw new RangeError(`Invalid CID version ${version}`);
1471
- }
1472
- const prefixSize = offset;
1473
- const multihashCode = (
1474
- /** @type {A} */
1475
- next()
1476
- );
1477
- const digestSize = next();
1478
- const size = offset + digestSize;
1479
- const multihashSize = size - prefixSize;
1480
- return { version, codec, multihashCode, digestSize, multihashSize, size };
1481
- }
1482
- /**
1483
- * Takes cid in a string representation and creates an instance. If `base`
1484
- * decoder is not provided will use a default from the configuration. It will
1485
- * throw an error if encoding of the CID is not compatible with supplied (or
1486
- * a default decoder).
1487
- *
1488
- * @template {string} Prefix
1489
- * @template {unknown} Data
1490
- * @template {number} Code
1491
- * @template {number} Alg
1492
- * @template {API.Version} Ver
1493
- * @param {API.ToString<API.Link<Data, Code, Alg, Ver>, Prefix>} source
1494
- * @param {API.MultibaseDecoder<Prefix>} [base]
1495
- * @returns {CID<Data, Code, Alg, Ver>}
1496
- */
1497
- static parse(source, base2) {
1498
- const [prefix, bytes] = parseCIDtoBytes(source, base2);
1499
- const cid = _CID.decode(bytes);
1500
- if (cid.version === 0 && source[0] !== "Q") {
1501
- throw Error("Version 0 CID string must not include multibase prefix");
1502
- }
1503
- baseCache(cid).set(prefix, source);
1504
- return cid;
1505
- }
1506
- };
1507
- var parseCIDtoBytes = (source, base2) => {
1508
- switch (source[0]) {
1509
- case "Q": {
1510
- const decoder = base2 || base58btc;
1511
- return [
1512
- /** @type {Prefix} */
1513
- base58btc.prefix,
1514
- decoder.decode(`${base58btc.prefix}${source}`)
1515
- ];
1516
- }
1517
- case base58btc.prefix: {
1518
- const decoder = base2 || base58btc;
1519
- return [
1520
- /** @type {Prefix} */
1521
- base58btc.prefix,
1522
- decoder.decode(source)
1523
- ];
1524
- }
1525
- case base32.prefix: {
1526
- const decoder = base2 || base32;
1527
- return [
1528
- /** @type {Prefix} */
1529
- base32.prefix,
1530
- decoder.decode(source)
1531
- ];
1532
- }
1533
- default: {
1534
- if (base2 == null) {
1535
- throw Error(
1536
- "To parse non base32 or base58btc encoded CID multibase decoder must be provided"
1537
- );
1538
- }
1539
- return [
1540
- /** @type {Prefix} */
1541
- source[0],
1542
- base2.decode(source)
1543
- ];
1544
- }
1545
- }
1546
- };
1547
- var toStringV0 = (bytes, cache2, base2) => {
1548
- const { prefix } = base2;
1549
- if (prefix !== base58btc.prefix) {
1550
- throw Error(`Cannot string encode V0 in ${base2.name} encoding`);
1551
- }
1552
- const cid = cache2.get(prefix);
1553
- if (cid == null) {
1554
- const cid2 = base2.encode(bytes).slice(1);
1555
- cache2.set(prefix, cid2);
1556
- return cid2;
1557
- } else {
1558
- return cid;
1559
- }
1560
- };
1561
- var toStringV1 = (bytes, cache2, base2) => {
1562
- const { prefix } = base2;
1563
- const cid = cache2.get(prefix);
1564
- if (cid == null) {
1565
- const cid2 = base2.encode(bytes);
1566
- cache2.set(prefix, cid2);
1567
- return cid2;
1568
- } else {
1569
- return cid;
1570
- }
1571
- };
1572
- var DAG_PB_CODE = 112;
1573
- var SHA_256_CODE = 18;
1574
- var encodeCID = (version, code2, multihash) => {
1575
- const codeOffset = encodingLength(version);
1576
- const hashOffset = codeOffset + encodingLength(code2);
1577
- const bytes = new Uint8Array(hashOffset + multihash.byteLength);
1578
- encodeTo(version, bytes, 0);
1579
- encodeTo(code2, bytes, codeOffset);
1580
- bytes.set(multihash, hashOffset);
1581
- return bytes;
1582
- };
1583
- var cidSymbol = Symbol.for("@ipld/js-cid/CID");
1584
-
1585
- // ../../node_modules/.pnpm/multiformats@12.0.1/node_modules/multiformats/src/hashes/hasher.js
1586
- var from2 = ({ name: name2, code: code2, encode: encode6 }) => new Hasher(name2, code2, encode6);
1587
- var Hasher = class {
1588
- /**
1589
- *
1590
- * @param {Name} name
1591
- * @param {Code} code
1592
- * @param {(input: Uint8Array) => Await<Uint8Array>} encode
1593
- */
1594
- constructor(name2, code2, encode6) {
1595
- this.name = name2;
1596
- this.code = code2;
1597
- this.encode = encode6;
1598
- }
1599
- /**
1600
- * @param {Uint8Array} input
1601
- * @returns {Await<Digest.Digest<Code, number>>}
1602
- */
1603
- digest(input) {
1604
- if (input instanceof Uint8Array) {
1605
- const result = this.encode(input);
1606
- return result instanceof Uint8Array ? create(this.code, result) : result.then((digest) => create(this.code, digest));
1607
- } else {
1608
- throw Error("Unknown type, must be binary type");
1609
- }
1610
- }
1611
- };
1612
-
1613
- // ../../node_modules/.pnpm/multiformats@12.0.1/node_modules/multiformats/src/block.js
1614
- function readonly({ enumerable = true, configurable = false } = {}) {
1615
- return { enumerable, configurable, writable: false };
1616
- }
1617
- function* linksWithin(path, value) {
1618
- if (value != null && typeof value === "object") {
1619
- if (Array.isArray(value)) {
1620
- for (const [index, element] of value.entries()) {
1621
- const elementPath = [...path, index];
1622
- const cid = CID.asCID(element);
1623
- if (cid) {
1624
- yield [elementPath.join("/"), cid];
1625
- } else if (typeof element === "object") {
1626
- yield* links(element, elementPath);
1627
- }
1628
- }
1629
- } else {
1630
- const cid = CID.asCID(value);
1631
- if (cid) {
1632
- yield [path.join("/"), cid];
1633
- } else {
1634
- yield* links(value, path);
1635
- }
1636
- }
1637
- }
1638
- }
1639
- function* links(source, base2) {
1640
- if (source == null || source instanceof Uint8Array) {
1641
- return;
1642
- }
1643
- const cid = CID.asCID(source);
1644
- if (cid) {
1645
- yield [base2.join("/"), cid];
1646
- }
1647
- for (const [key, value] of Object.entries(source)) {
1648
- const path = (
1649
- /** @type {[string|number, string]} */
1650
- [...base2, key]
1651
- );
1652
- yield* linksWithin(path, value);
1653
- }
1654
- }
1655
- function* treeWithin(path, value) {
1656
- if (Array.isArray(value)) {
1657
- for (const [index, element] of value.entries()) {
1658
- const elementPath = [...path, index];
1659
- yield elementPath.join("/");
1660
- if (typeof element === "object" && !CID.asCID(element)) {
1661
- yield* tree(element, elementPath);
1662
- }
1663
- }
1664
- } else {
1665
- yield* tree(value, path);
1666
- }
1667
- }
1668
- function* tree(source, base2) {
1669
- if (source == null || typeof source !== "object") {
1670
- return;
1671
- }
1672
- for (const [key, value] of Object.entries(source)) {
1673
- const path = (
1674
- /** @type {[string|number, string]} */
1675
- [...base2, key]
1676
- );
1677
- yield path.join("/");
1678
- if (value != null && !(value instanceof Uint8Array) && typeof value === "object" && !CID.asCID(value)) {
1679
- yield* treeWithin(path, value);
1680
- }
1681
- }
1682
- }
1683
- function get(source, path) {
1684
- let node = (
1685
- /** @type {Record<string, any>} */
1686
- source
1687
- );
1688
- for (const [index, key] of path.entries()) {
1689
- node = node[key];
1690
- if (node == null) {
1691
- throw new Error(`Object has no property at ${path.slice(0, index + 1).map((part) => `[${JSON.stringify(part)}]`).join("")}`);
1692
- }
1693
- const cid = CID.asCID(node);
1694
- if (cid) {
1695
- return { value: cid, remaining: path.slice(index + 1).join("/") };
1696
- }
1697
- }
1698
- return { value: node };
1699
- }
1700
- var Block = class {
1701
- /**
1702
- * @param {object} options
1703
- * @param {CID<T, C, A, V>} options.cid
1704
- * @param {API.ByteView<T>} options.bytes
1705
- * @param {T} options.value
1706
- */
1707
- constructor({ cid, bytes, value }) {
1708
- if (!cid || !bytes || typeof value === "undefined") {
1709
- throw new Error("Missing required argument");
1710
- }
1711
- this.cid = cid;
1712
- this.bytes = bytes;
1713
- this.value = value;
1714
- this.asBlock = this;
1715
- Object.defineProperties(this, {
1716
- cid: readonly(),
1717
- bytes: readonly(),
1718
- value: readonly(),
1719
- asBlock: readonly()
1720
- });
1721
- }
1722
- links() {
1723
- return links(this.value, []);
1724
- }
1725
- tree() {
1726
- return tree(this.value, []);
1727
- }
1728
- /**
1729
- *
1730
- * @param {string} [path]
1731
- * @returns {API.BlockCursorView<unknown>}
1732
- */
1733
- get(path = "/") {
1734
- return get(this.value, path.split("/").filter(Boolean));
1735
- }
1736
- };
1737
- async function encode3({ value, codec, hasher }) {
1738
- if (typeof value === "undefined")
1739
- throw new Error('Missing required argument "value"');
1740
- if (!codec || !hasher)
1741
- throw new Error("Missing required argument: codec or hasher");
1742
- const bytes = codec.encode(value);
1743
- const hash = await hasher.digest(bytes);
1744
- const cid = CID.create(
1745
- 1,
1746
- codec.code,
1747
- hash
1748
- );
1749
- return new Block({ value, bytes, cid });
1750
- }
1751
- async function decode5({ bytes, codec, hasher }) {
1752
- if (!bytes)
1753
- throw new Error('Missing required argument "bytes"');
1754
- if (!codec || !hasher)
1755
- throw new Error("Missing required argument: codec or hasher");
1756
- const value = codec.decode(bytes);
1757
- const hash = await hasher.digest(bytes);
1758
- const cid = CID.create(1, codec.code, hash);
1759
- return new Block({ value, bytes, cid });
1760
- }
1761
-
1762
- // ../../node_modules/.pnpm/@ipld+dag-cbor@9.0.5/node_modules/@ipld/dag-cbor/src/index.js
1763
- var src_exports = {};
1764
- __export(src_exports, {
1765
- code: () => code,
1766
- decode: () => decode7,
1767
- encode: () => encode5,
1768
- name: () => name
1769
- });
1770
-
1771
- // ../../node_modules/.pnpm/cborg@4.2.12/node_modules/cborg/lib/is.js
1772
- var typeofs = [
1773
- "string",
1774
- "number",
1775
- "bigint",
1776
- "symbol"
1777
- ];
1778
- var objectTypeNames = [
1779
- "Function",
1780
- "Generator",
1781
- "AsyncGenerator",
1782
- "GeneratorFunction",
1783
- "AsyncGeneratorFunction",
1784
- "AsyncFunction",
1785
- "Observable",
1786
- "Array",
1787
- "Buffer",
1788
- "Object",
1789
- "RegExp",
1790
- "Date",
1791
- "Error",
1792
- "Map",
1793
- "Set",
1794
- "WeakMap",
1795
- "WeakSet",
1796
- "ArrayBuffer",
1797
- "SharedArrayBuffer",
1798
- "DataView",
1799
- "Promise",
1800
- "URL",
1801
- "HTMLElement",
1802
- "Int8Array",
1803
- "Uint8Array",
1804
- "Uint8ClampedArray",
1805
- "Int16Array",
1806
- "Uint16Array",
1807
- "Int32Array",
1808
- "Uint32Array",
1809
- "Float32Array",
1810
- "Float64Array",
1811
- "BigInt64Array",
1812
- "BigUint64Array"
1813
- ];
1814
- function is(value) {
1815
- if (value === null) {
1816
- return "null";
1817
- }
1818
- if (value === void 0) {
1819
- return "undefined";
1820
- }
1821
- if (value === true || value === false) {
1822
- return "boolean";
1823
- }
1824
- const typeOf = typeof value;
1825
- if (typeofs.includes(typeOf)) {
1826
- return typeOf;
1827
- }
1828
- if (typeOf === "function") {
1829
- return "Function";
1830
- }
1831
- if (Array.isArray(value)) {
1832
- return "Array";
1833
- }
1834
- if (isBuffer(value)) {
1835
- return "Buffer";
1836
- }
1837
- const objectType = getObjectType(value);
1838
- if (objectType) {
1839
- return objectType;
1840
- }
1841
- return "Object";
1842
- }
1843
- function isBuffer(value) {
1844
- return value && value.constructor && value.constructor.isBuffer && value.constructor.isBuffer.call(null, value);
1845
- }
1846
- function getObjectType(value) {
1847
- const objectTypeName = Object.prototype.toString.call(value).slice(8, -1);
1848
- if (objectTypeNames.includes(objectTypeName)) {
1849
- return objectTypeName;
1850
- }
1851
- return void 0;
1852
- }
1853
-
1854
- // ../../node_modules/.pnpm/cborg@4.2.12/node_modules/cborg/lib/token.js
1855
- var Type = class {
1856
- /**
1857
- * @param {number} major
1858
- * @param {string} name
1859
- * @param {boolean} terminal
1860
- */
1861
- constructor(major, name2, terminal) {
1862
- this.major = major;
1863
- this.majorEncoded = major << 5;
1864
- this.name = name2;
1865
- this.terminal = terminal;
1866
- }
1867
- /* c8 ignore next 3 */
1868
- toString() {
1869
- return `Type[${this.major}].${this.name}`;
1870
- }
1871
- /**
1872
- * @param {Type} typ
1873
- * @returns {number}
1874
- */
1875
- compare(typ) {
1876
- return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0;
1877
- }
1878
- };
1879
- Type.uint = new Type(0, "uint", true);
1880
- Type.negint = new Type(1, "negint", true);
1881
- Type.bytes = new Type(2, "bytes", true);
1882
- Type.string = new Type(3, "string", true);
1883
- Type.array = new Type(4, "array", false);
1884
- Type.map = new Type(5, "map", false);
1885
- Type.tag = new Type(6, "tag", false);
1886
- Type.float = new Type(7, "float", true);
1887
- Type.false = new Type(7, "false", true);
1888
- Type.true = new Type(7, "true", true);
1889
- Type.null = new Type(7, "null", true);
1890
- Type.undefined = new Type(7, "undefined", true);
1891
- Type.break = new Type(7, "break", true);
1892
- var Token = class {
1893
- /**
1894
- * @param {Type} type
1895
- * @param {any} [value]
1896
- * @param {number} [encodedLength]
1897
- */
1898
- constructor(type, value, encodedLength) {
1899
- this.type = type;
1900
- this.value = value;
1901
- this.encodedLength = encodedLength;
1902
- this.encodedBytes = void 0;
1903
- this.byteValue = void 0;
1904
- }
1905
- /* c8 ignore next 3 */
1906
- toString() {
1907
- return `Token[${this.type}].${this.value}`;
1908
- }
1909
- };
1910
-
1911
- // ../../node_modules/.pnpm/cborg@4.2.12/node_modules/cborg/lib/byte-utils.js
1912
- var useBuffer = globalThis.process && // @ts-ignore
1913
- !globalThis.process.browser && // @ts-ignore
1914
- globalThis.Buffer && // @ts-ignore
1915
- typeof globalThis.Buffer.isBuffer === "function";
1916
- var textDecoder = new TextDecoder();
1917
- var textEncoder = new TextEncoder();
1918
- function isBuffer2(buf2) {
1919
- return useBuffer && globalThis.Buffer.isBuffer(buf2);
1920
- }
1921
- function asU8A(buf2) {
1922
- if (!(buf2 instanceof Uint8Array)) {
1923
- return Uint8Array.from(buf2);
1924
- }
1925
- return isBuffer2(buf2) ? new Uint8Array(buf2.buffer, buf2.byteOffset, buf2.byteLength) : buf2;
1926
- }
1927
- var toString = useBuffer ? (
1928
- // eslint-disable-line operator-linebreak
1929
- /**
1930
- * @param {Uint8Array} bytes
1931
- * @param {number} start
1932
- * @param {number} end
1933
- */
1934
- (bytes, start, end) => {
1935
- return end - start > 64 ? (
1936
- // eslint-disable-line operator-linebreak
1937
- // @ts-ignore
1938
- globalThis.Buffer.from(bytes.subarray(start, end)).toString("utf8")
1939
- ) : utf8Slice(bytes, start, end);
1940
- }
1941
- ) : (
1942
- // eslint-disable-line operator-linebreak
1943
- /**
1944
- * @param {Uint8Array} bytes
1945
- * @param {number} start
1946
- * @param {number} end
1947
- */
1948
- (bytes, start, end) => {
1949
- return end - start > 64 ? textDecoder.decode(bytes.subarray(start, end)) : utf8Slice(bytes, start, end);
1950
- }
1951
- );
1952
- var fromString = useBuffer ? (
1953
- // eslint-disable-line operator-linebreak
1954
- /**
1955
- * @param {string} string
1956
- */
1957
- (string) => {
1958
- return string.length > 64 ? (
1959
- // eslint-disable-line operator-linebreak
1960
- // @ts-ignore
1961
- globalThis.Buffer.from(string)
1962
- ) : utf8ToBytes(string);
1963
- }
1964
- ) : (
1965
- // eslint-disable-line operator-linebreak
1966
- /**
1967
- * @param {string} string
1968
- */
1969
- (string) => {
1970
- return string.length > 64 ? textEncoder.encode(string) : utf8ToBytes(string);
1971
- }
1972
- );
1973
- var fromArray = (arr) => {
1974
- return Uint8Array.from(arr);
1975
- };
1976
- var slice = useBuffer ? (
1977
- // eslint-disable-line operator-linebreak
1978
- /**
1979
- * @param {Uint8Array} bytes
1980
- * @param {number} start
1981
- * @param {number} end
1982
- */
1983
- (bytes, start, end) => {
1984
- if (isBuffer2(bytes)) {
1985
- return new Uint8Array(bytes.subarray(start, end));
1986
- }
1987
- return bytes.slice(start, end);
1988
- }
1989
- ) : (
1990
- // eslint-disable-line operator-linebreak
1991
- /**
1992
- * @param {Uint8Array} bytes
1993
- * @param {number} start
1994
- * @param {number} end
1995
- */
1996
- (bytes, start, end) => {
1997
- return bytes.slice(start, end);
1998
- }
1999
- );
2000
- var concat = useBuffer ? (
2001
- // eslint-disable-line operator-linebreak
2002
- /**
2003
- * @param {Uint8Array[]} chunks
2004
- * @param {number} length
2005
- * @returns {Uint8Array}
2006
- */
2007
- (chunks, length2) => {
2008
- chunks = chunks.map((c) => c instanceof Uint8Array ? c : (
2009
- // eslint-disable-line operator-linebreak
2010
- // @ts-ignore
2011
- globalThis.Buffer.from(c)
2012
- ));
2013
- return asU8A(globalThis.Buffer.concat(chunks, length2));
2014
- }
2015
- ) : (
2016
- // eslint-disable-line operator-linebreak
2017
- /**
2018
- * @param {Uint8Array[]} chunks
2019
- * @param {number} length
2020
- * @returns {Uint8Array}
2021
- */
2022
- (chunks, length2) => {
2023
- const out = new Uint8Array(length2);
2024
- let off = 0;
2025
- for (let b of chunks) {
2026
- if (off + b.length > out.length) {
2027
- b = b.subarray(0, out.length - off);
2028
- }
2029
- out.set(b, off);
2030
- off += b.length;
2031
- }
2032
- return out;
2033
- }
2034
- );
2035
- var alloc = useBuffer ? (
2036
- // eslint-disable-line operator-linebreak
2037
- /**
2038
- * @param {number} size
2039
- * @returns {Uint8Array}
2040
- */
2041
- (size) => {
2042
- return globalThis.Buffer.allocUnsafe(size);
2043
- }
2044
- ) : (
2045
- // eslint-disable-line operator-linebreak
2046
- /**
2047
- * @param {number} size
2048
- * @returns {Uint8Array}
2049
- */
2050
- (size) => {
2051
- return new Uint8Array(size);
2052
- }
2053
- );
2054
- function compare(b1, b2) {
2055
- if (isBuffer2(b1) && isBuffer2(b2)) {
2056
- return b1.compare(b2);
2057
- }
2058
- for (let i = 0; i < b1.length; i++) {
2059
- if (b1[i] === b2[i]) {
2060
- continue;
2061
- }
2062
- return b1[i] < b2[i] ? -1 : 1;
2063
- }
2064
- return 0;
2065
- }
2066
- function utf8ToBytes(str) {
2067
- const out = [];
2068
- let p = 0;
2069
- for (let i = 0; i < str.length; i++) {
2070
- let c = str.charCodeAt(i);
2071
- if (c < 128) {
2072
- out[p++] = c;
2073
- } else if (c < 2048) {
2074
- out[p++] = c >> 6 | 192;
2075
- out[p++] = c & 63 | 128;
2076
- } else if ((c & 64512) === 55296 && i + 1 < str.length && (str.charCodeAt(i + 1) & 64512) === 56320) {
2077
- c = 65536 + ((c & 1023) << 10) + (str.charCodeAt(++i) & 1023);
2078
- out[p++] = c >> 18 | 240;
2079
- out[p++] = c >> 12 & 63 | 128;
2080
- out[p++] = c >> 6 & 63 | 128;
2081
- out[p++] = c & 63 | 128;
2082
- } else {
2083
- out[p++] = c >> 12 | 224;
2084
- out[p++] = c >> 6 & 63 | 128;
2085
- out[p++] = c & 63 | 128;
2086
- }
2087
- }
2088
- return out;
2089
- }
2090
- function utf8Slice(buf2, offset, end) {
2091
- const res = [];
2092
- while (offset < end) {
2093
- const firstByte = buf2[offset];
2094
- let codePoint = null;
2095
- let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;
2096
- if (offset + bytesPerSequence <= end) {
2097
- let secondByte, thirdByte, fourthByte, tempCodePoint;
2098
- switch (bytesPerSequence) {
2099
- case 1:
2100
- if (firstByte < 128) {
2101
- codePoint = firstByte;
2102
- }
2103
- break;
2104
- case 2:
2105
- secondByte = buf2[offset + 1];
2106
- if ((secondByte & 192) === 128) {
2107
- tempCodePoint = (firstByte & 31) << 6 | secondByte & 63;
2108
- if (tempCodePoint > 127) {
2109
- codePoint = tempCodePoint;
2110
- }
2111
- }
2112
- break;
2113
- case 3:
2114
- secondByte = buf2[offset + 1];
2115
- thirdByte = buf2[offset + 2];
2116
- if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) {
2117
- tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63;
2118
- if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) {
2119
- codePoint = tempCodePoint;
2120
- }
2121
- }
2122
- break;
2123
- case 4:
2124
- secondByte = buf2[offset + 1];
2125
- thirdByte = buf2[offset + 2];
2126
- fourthByte = buf2[offset + 3];
2127
- if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) {
2128
- tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63;
2129
- if (tempCodePoint > 65535 && tempCodePoint < 1114112) {
2130
- codePoint = tempCodePoint;
2131
- }
2132
- }
2133
- }
2134
- }
2135
- if (codePoint === null) {
2136
- codePoint = 65533;
2137
- bytesPerSequence = 1;
2138
- } else if (codePoint > 65535) {
2139
- codePoint -= 65536;
2140
- res.push(codePoint >>> 10 & 1023 | 55296);
2141
- codePoint = 56320 | codePoint & 1023;
2142
- }
2143
- res.push(codePoint);
2144
- offset += bytesPerSequence;
2145
- }
2146
- return decodeCodePointsArray(res);
2147
- }
2148
- var MAX_ARGUMENTS_LENGTH = 4096;
2149
- function decodeCodePointsArray(codePoints) {
2150
- const len = codePoints.length;
2151
- if (len <= MAX_ARGUMENTS_LENGTH) {
2152
- return String.fromCharCode.apply(String, codePoints);
2153
- }
2154
- let res = "";
2155
- let i = 0;
2156
- while (i < len) {
2157
- res += String.fromCharCode.apply(
2158
- String,
2159
- codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
2160
- );
2161
- }
2162
- return res;
2163
- }
2164
-
2165
- // ../../node_modules/.pnpm/cborg@4.2.12/node_modules/cborg/lib/bl.js
2166
- var defaultChunkSize = 256;
2167
- var Bl = class {
2168
- /**
2169
- * @param {number} [chunkSize]
2170
- */
2171
- constructor(chunkSize = defaultChunkSize) {
2172
- this.chunkSize = chunkSize;
2173
- this.cursor = 0;
2174
- this.maxCursor = -1;
2175
- this.chunks = [];
2176
- this._initReuseChunk = null;
2177
- }
2178
- reset() {
2179
- this.cursor = 0;
2180
- this.maxCursor = -1;
2181
- if (this.chunks.length) {
2182
- this.chunks = [];
2183
- }
2184
- if (this._initReuseChunk !== null) {
2185
- this.chunks.push(this._initReuseChunk);
2186
- this.maxCursor = this._initReuseChunk.length - 1;
2187
- }
2188
- }
2189
- /**
2190
- * @param {Uint8Array|number[]} bytes
2191
- */
2192
- push(bytes) {
2193
- let topChunk = this.chunks[this.chunks.length - 1];
2194
- const newMax = this.cursor + bytes.length;
2195
- if (newMax <= this.maxCursor + 1) {
2196
- const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1;
2197
- topChunk.set(bytes, chunkPos);
2198
- } else {
2199
- if (topChunk) {
2200
- const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1;
2201
- if (chunkPos < topChunk.length) {
2202
- this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos);
2203
- this.maxCursor = this.cursor - 1;
2204
- }
2205
- }
2206
- if (bytes.length < 64 && bytes.length < this.chunkSize) {
2207
- topChunk = alloc(this.chunkSize);
2208
- this.chunks.push(topChunk);
2209
- this.maxCursor += topChunk.length;
2210
- if (this._initReuseChunk === null) {
2211
- this._initReuseChunk = topChunk;
2212
- }
2213
- topChunk.set(bytes, 0);
2214
- } else {
2215
- this.chunks.push(bytes);
2216
- this.maxCursor += bytes.length;
2217
- }
2218
- }
2219
- this.cursor += bytes.length;
2220
- }
2221
- /**
2222
- * @param {boolean} [reset]
2223
- * @returns {Uint8Array}
2224
- */
2225
- toBytes(reset = false) {
2226
- let byts;
2227
- if (this.chunks.length === 1) {
2228
- const chunk = this.chunks[0];
2229
- if (reset && this.cursor > chunk.length / 2) {
2230
- byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor);
2231
- this._initReuseChunk = null;
2232
- this.chunks = [];
2233
- } else {
2234
- byts = slice(chunk, 0, this.cursor);
2235
- }
2236
- } else {
2237
- byts = concat(this.chunks, this.cursor);
2238
- }
2239
- if (reset) {
2240
- this.reset();
2241
- }
2242
- return byts;
2243
- }
2244
- };
2245
-
2246
- // ../../node_modules/.pnpm/cborg@4.2.12/node_modules/cborg/lib/common.js
2247
- var decodeErrPrefix = "CBOR decode error:";
2248
- var encodeErrPrefix = "CBOR encode error:";
2249
- var uintMinorPrefixBytes = [];
2250
- uintMinorPrefixBytes[23] = 1;
2251
- uintMinorPrefixBytes[24] = 2;
2252
- uintMinorPrefixBytes[25] = 3;
2253
- uintMinorPrefixBytes[26] = 5;
2254
- uintMinorPrefixBytes[27] = 9;
2255
- function assertEnoughData(data, pos, need) {
2256
- if (data.length - pos < need) {
2257
- throw new Error(`${decodeErrPrefix} not enough data for type`);
2258
- }
2259
- }
2260
-
2261
- // ../../node_modules/.pnpm/cborg@4.2.12/node_modules/cborg/lib/0uint.js
2262
- var uintBoundaries = [24, 256, 65536, 4294967296, BigInt("18446744073709551616")];
2263
- function readUint8(data, offset, options) {
2264
- assertEnoughData(data, offset, 1);
2265
- const value = data[offset];
2266
- if (options.strict === true && value < uintBoundaries[0]) {
2267
- throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
2268
- }
2269
- return value;
2270
- }
2271
- function readUint16(data, offset, options) {
2272
- assertEnoughData(data, offset, 2);
2273
- const value = data[offset] << 8 | data[offset + 1];
2274
- if (options.strict === true && value < uintBoundaries[1]) {
2275
- throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
2276
- }
2277
- return value;
2278
- }
2279
- function readUint32(data, offset, options) {
2280
- assertEnoughData(data, offset, 4);
2281
- const value = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3];
2282
- if (options.strict === true && value < uintBoundaries[2]) {
2283
- throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
2284
- }
2285
- return value;
2286
- }
2287
- function readUint64(data, offset, options) {
2288
- assertEnoughData(data, offset, 8);
2289
- const hi = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3];
2290
- const lo = data[offset + 4] * 16777216 + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7];
2291
- const value = (BigInt(hi) << BigInt(32)) + BigInt(lo);
2292
- if (options.strict === true && value < uintBoundaries[3]) {
2293
- throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`);
2294
- }
2295
- if (value <= Number.MAX_SAFE_INTEGER) {
2296
- return Number(value);
2297
- }
2298
- if (options.allowBigInt === true) {
2299
- return value;
2300
- }
2301
- throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`);
2302
- }
2303
- function decodeUint8(data, pos, _minor, options) {
2304
- return new Token(Type.uint, readUint8(data, pos + 1, options), 2);
2305
- }
2306
- function decodeUint16(data, pos, _minor, options) {
2307
- return new Token(Type.uint, readUint16(data, pos + 1, options), 3);
2308
- }
2309
- function decodeUint32(data, pos, _minor, options) {
2310
- return new Token(Type.uint, readUint32(data, pos + 1, options), 5);
2311
- }
2312
- function decodeUint64(data, pos, _minor, options) {
2313
- return new Token(Type.uint, readUint64(data, pos + 1, options), 9);
2314
- }
2315
- function encodeUint(buf2, token) {
2316
- return encodeUintValue(buf2, 0, token.value);
2317
- }
2318
- function encodeUintValue(buf2, major, uint) {
2319
- if (uint < uintBoundaries[0]) {
2320
- const nuint = Number(uint);
2321
- buf2.push([major | nuint]);
2322
- } else if (uint < uintBoundaries[1]) {
2323
- const nuint = Number(uint);
2324
- buf2.push([major | 24, nuint]);
2325
- } else if (uint < uintBoundaries[2]) {
2326
- const nuint = Number(uint);
2327
- buf2.push([major | 25, nuint >>> 8, nuint & 255]);
2328
- } else if (uint < uintBoundaries[3]) {
2329
- const nuint = Number(uint);
2330
- buf2.push([major | 26, nuint >>> 24 & 255, nuint >>> 16 & 255, nuint >>> 8 & 255, nuint & 255]);
2331
- } else {
2332
- const buint = BigInt(uint);
2333
- if (buint < uintBoundaries[4]) {
2334
- const set = [major | 27, 0, 0, 0, 0, 0, 0, 0];
2335
- let lo = Number(buint & BigInt(4294967295));
2336
- let hi = Number(buint >> BigInt(32) & BigInt(4294967295));
2337
- set[8] = lo & 255;
2338
- lo = lo >> 8;
2339
- set[7] = lo & 255;
2340
- lo = lo >> 8;
2341
- set[6] = lo & 255;
2342
- lo = lo >> 8;
2343
- set[5] = lo & 255;
2344
- set[4] = hi & 255;
2345
- hi = hi >> 8;
2346
- set[3] = hi & 255;
2347
- hi = hi >> 8;
2348
- set[2] = hi & 255;
2349
- hi = hi >> 8;
2350
- set[1] = hi & 255;
2351
- buf2.push(set);
2352
- } else {
2353
- throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`);
2354
- }
2355
- }
2356
- }
2357
- encodeUint.encodedSize = function encodedSize(token) {
2358
- return encodeUintValue.encodedSize(token.value);
2359
- };
2360
- encodeUintValue.encodedSize = function encodedSize2(uint) {
2361
- if (uint < uintBoundaries[0]) {
2362
- return 1;
2363
- }
2364
- if (uint < uintBoundaries[1]) {
2365
- return 2;
2366
- }
2367
- if (uint < uintBoundaries[2]) {
2368
- return 3;
2369
- }
2370
- if (uint < uintBoundaries[3]) {
2371
- return 5;
2372
- }
2373
- return 9;
2374
- };
2375
- encodeUint.compareTokens = function compareTokens(tok1, tok2) {
2376
- return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : (
2377
- /* c8 ignore next */
2378
- 0
2379
- );
2380
- };
2381
-
2382
- // ../../node_modules/.pnpm/cborg@4.2.12/node_modules/cborg/lib/1negint.js
2383
- function decodeNegint8(data, pos, _minor, options) {
2384
- return new Token(Type.negint, -1 - readUint8(data, pos + 1, options), 2);
2385
- }
2386
- function decodeNegint16(data, pos, _minor, options) {
2387
- return new Token(Type.negint, -1 - readUint16(data, pos + 1, options), 3);
2388
- }
2389
- function decodeNegint32(data, pos, _minor, options) {
2390
- return new Token(Type.negint, -1 - readUint32(data, pos + 1, options), 5);
2391
- }
2392
- var neg1b = BigInt(-1);
2393
- var pos1b = BigInt(1);
2394
- function decodeNegint64(data, pos, _minor, options) {
2395
- const int = readUint64(data, pos + 1, options);
2396
- if (typeof int !== "bigint") {
2397
- const value = -1 - int;
2398
- if (value >= Number.MIN_SAFE_INTEGER) {
2399
- return new Token(Type.negint, value, 9);
2400
- }
2401
- }
2402
- if (options.allowBigInt !== true) {
2403
- throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`);
2404
- }
2405
- return new Token(Type.negint, neg1b - BigInt(int), 9);
2406
- }
2407
- function encodeNegint(buf2, token) {
2408
- const negint = token.value;
2409
- const unsigned = typeof negint === "bigint" ? negint * neg1b - pos1b : negint * -1 - 1;
2410
- encodeUintValue(buf2, token.type.majorEncoded, unsigned);
2411
- }
2412
- encodeNegint.encodedSize = function encodedSize3(token) {
2413
- const negint = token.value;
2414
- const unsigned = typeof negint === "bigint" ? negint * neg1b - pos1b : negint * -1 - 1;
2415
- if (unsigned < uintBoundaries[0]) {
2416
- return 1;
2417
- }
2418
- if (unsigned < uintBoundaries[1]) {
2419
- return 2;
2420
- }
2421
- if (unsigned < uintBoundaries[2]) {
2422
- return 3;
2423
- }
2424
- if (unsigned < uintBoundaries[3]) {
2425
- return 5;
2426
- }
2427
- return 9;
2428
- };
2429
- encodeNegint.compareTokens = function compareTokens2(tok1, tok2) {
2430
- return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : (
2431
- /* c8 ignore next */
2432
- 0
2433
- );
2434
- };
2435
-
2436
- // ../../node_modules/.pnpm/cborg@4.2.12/node_modules/cborg/lib/2bytes.js
2437
- function toToken(data, pos, prefix, length2) {
2438
- assertEnoughData(data, pos, prefix + length2);
2439
- const buf2 = slice(data, pos + prefix, pos + prefix + length2);
2440
- return new Token(Type.bytes, buf2, prefix + length2);
2441
- }
2442
- function decodeBytesCompact(data, pos, minor, _options) {
2443
- return toToken(data, pos, 1, minor);
2444
- }
2445
- function decodeBytes8(data, pos, _minor, options) {
2446
- return toToken(data, pos, 2, readUint8(data, pos + 1, options));
2447
- }
2448
- function decodeBytes16(data, pos, _minor, options) {
2449
- return toToken(data, pos, 3, readUint16(data, pos + 1, options));
2450
- }
2451
- function decodeBytes32(data, pos, _minor, options) {
2452
- return toToken(data, pos, 5, readUint32(data, pos + 1, options));
2453
- }
2454
- function decodeBytes64(data, pos, _minor, options) {
2455
- const l = readUint64(data, pos + 1, options);
2456
- if (typeof l === "bigint") {
2457
- throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`);
2458
- }
2459
- return toToken(data, pos, 9, l);
2460
- }
2461
- function tokenBytes(token) {
2462
- if (token.encodedBytes === void 0) {
2463
- token.encodedBytes = token.type === Type.string ? fromString(token.value) : token.value;
2464
- }
2465
- return token.encodedBytes;
2466
- }
2467
- function encodeBytes(buf2, token) {
2468
- const bytes = tokenBytes(token);
2469
- encodeUintValue(buf2, token.type.majorEncoded, bytes.length);
2470
- buf2.push(bytes);
2471
- }
2472
- encodeBytes.encodedSize = function encodedSize4(token) {
2473
- const bytes = tokenBytes(token);
2474
- return encodeUintValue.encodedSize(bytes.length) + bytes.length;
2475
- };
2476
- encodeBytes.compareTokens = function compareTokens3(tok1, tok2) {
2477
- return compareBytes(tokenBytes(tok1), tokenBytes(tok2));
2478
- };
2479
- function compareBytes(b1, b2) {
2480
- return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2);
2481
- }
2482
-
2483
- // ../../node_modules/.pnpm/cborg@4.2.12/node_modules/cborg/lib/3string.js
2484
- function toToken2(data, pos, prefix, length2, options) {
2485
- const totLength = prefix + length2;
2486
- assertEnoughData(data, pos, totLength);
2487
- const tok = new Token(Type.string, toString(data, pos + prefix, pos + totLength), totLength);
2488
- if (options.retainStringBytes === true) {
2489
- tok.byteValue = slice(data, pos + prefix, pos + totLength);
2490
- }
2491
- return tok;
2492
- }
2493
- function decodeStringCompact(data, pos, minor, options) {
2494
- return toToken2(data, pos, 1, minor, options);
2495
- }
2496
- function decodeString8(data, pos, _minor, options) {
2497
- return toToken2(data, pos, 2, readUint8(data, pos + 1, options), options);
2498
- }
2499
- function decodeString16(data, pos, _minor, options) {
2500
- return toToken2(data, pos, 3, readUint16(data, pos + 1, options), options);
2501
- }
2502
- function decodeString32(data, pos, _minor, options) {
2503
- return toToken2(data, pos, 5, readUint32(data, pos + 1, options), options);
2504
- }
2505
- function decodeString64(data, pos, _minor, options) {
2506
- const l = readUint64(data, pos + 1, options);
2507
- if (typeof l === "bigint") {
2508
- throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`);
2509
- }
2510
- return toToken2(data, pos, 9, l, options);
2511
- }
2512
- var encodeString = encodeBytes;
2513
-
2514
- // ../../node_modules/.pnpm/cborg@4.2.12/node_modules/cborg/lib/4array.js
2515
- function toToken3(_data, _pos, prefix, length2) {
2516
- return new Token(Type.array, length2, prefix);
2517
- }
2518
- function decodeArrayCompact(data, pos, minor, _options) {
2519
- return toToken3(data, pos, 1, minor);
2520
- }
2521
- function decodeArray8(data, pos, _minor, options) {
2522
- return toToken3(data, pos, 2, readUint8(data, pos + 1, options));
2523
- }
2524
- function decodeArray16(data, pos, _minor, options) {
2525
- return toToken3(data, pos, 3, readUint16(data, pos + 1, options));
2526
- }
2527
- function decodeArray32(data, pos, _minor, options) {
2528
- return toToken3(data, pos, 5, readUint32(data, pos + 1, options));
2529
- }
2530
- function decodeArray64(data, pos, _minor, options) {
2531
- const l = readUint64(data, pos + 1, options);
2532
- if (typeof l === "bigint") {
2533
- throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`);
2534
- }
2535
- return toToken3(data, pos, 9, l);
2536
- }
2537
- function decodeArrayIndefinite(data, pos, _minor, options) {
2538
- if (options.allowIndefinite === false) {
2539
- throw new Error(`${decodeErrPrefix} indefinite length items not allowed`);
2540
- }
2541
- return toToken3(data, pos, 1, Infinity);
2542
- }
2543
- function encodeArray(buf2, token) {
2544
- encodeUintValue(buf2, Type.array.majorEncoded, token.value);
2545
- }
2546
- encodeArray.compareTokens = encodeUint.compareTokens;
2547
- encodeArray.encodedSize = function encodedSize5(token) {
2548
- return encodeUintValue.encodedSize(token.value);
2549
- };
2550
-
2551
- // ../../node_modules/.pnpm/cborg@4.2.12/node_modules/cborg/lib/5map.js
2552
- function toToken4(_data, _pos, prefix, length2) {
2553
- return new Token(Type.map, length2, prefix);
2554
- }
2555
- function decodeMapCompact(data, pos, minor, _options) {
2556
- return toToken4(data, pos, 1, minor);
2557
- }
2558
- function decodeMap8(data, pos, _minor, options) {
2559
- return toToken4(data, pos, 2, readUint8(data, pos + 1, options));
2560
- }
2561
- function decodeMap16(data, pos, _minor, options) {
2562
- return toToken4(data, pos, 3, readUint16(data, pos + 1, options));
2563
- }
2564
- function decodeMap32(data, pos, _minor, options) {
2565
- return toToken4(data, pos, 5, readUint32(data, pos + 1, options));
2566
- }
2567
- function decodeMap64(data, pos, _minor, options) {
2568
- const l = readUint64(data, pos + 1, options);
2569
- if (typeof l === "bigint") {
2570
- throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`);
2571
- }
2572
- return toToken4(data, pos, 9, l);
2573
- }
2574
- function decodeMapIndefinite(data, pos, _minor, options) {
2575
- if (options.allowIndefinite === false) {
2576
- throw new Error(`${decodeErrPrefix} indefinite length items not allowed`);
2577
- }
2578
- return toToken4(data, pos, 1, Infinity);
2579
- }
2580
- function encodeMap(buf2, token) {
2581
- encodeUintValue(buf2, Type.map.majorEncoded, token.value);
2582
- }
2583
- encodeMap.compareTokens = encodeUint.compareTokens;
2584
- encodeMap.encodedSize = function encodedSize6(token) {
2585
- return encodeUintValue.encodedSize(token.value);
2586
- };
2587
-
2588
- // ../../node_modules/.pnpm/cborg@4.2.12/node_modules/cborg/lib/6tag.js
2589
- function decodeTagCompact(_data, _pos, minor, _options) {
2590
- return new Token(Type.tag, minor, 1);
2591
- }
2592
- function decodeTag8(data, pos, _minor, options) {
2593
- return new Token(Type.tag, readUint8(data, pos + 1, options), 2);
2594
- }
2595
- function decodeTag16(data, pos, _minor, options) {
2596
- return new Token(Type.tag, readUint16(data, pos + 1, options), 3);
2597
- }
2598
- function decodeTag32(data, pos, _minor, options) {
2599
- return new Token(Type.tag, readUint32(data, pos + 1, options), 5);
2600
- }
2601
- function decodeTag64(data, pos, _minor, options) {
2602
- return new Token(Type.tag, readUint64(data, pos + 1, options), 9);
2603
- }
2604
- function encodeTag(buf2, token) {
2605
- encodeUintValue(buf2, Type.tag.majorEncoded, token.value);
2606
- }
2607
- encodeTag.compareTokens = encodeUint.compareTokens;
2608
- encodeTag.encodedSize = function encodedSize7(token) {
2609
- return encodeUintValue.encodedSize(token.value);
2610
- };
2611
-
2612
- // ../../node_modules/.pnpm/cborg@4.2.12/node_modules/cborg/lib/7float.js
2613
- var MINOR_FALSE = 20;
2614
- var MINOR_TRUE = 21;
2615
- var MINOR_NULL = 22;
2616
- var MINOR_UNDEFINED = 23;
2617
- function decodeUndefined(_data, _pos, _minor, options) {
2618
- if (options.allowUndefined === false) {
2619
- throw new Error(`${decodeErrPrefix} undefined values are not supported`);
2620
- } else if (options.coerceUndefinedToNull === true) {
2621
- return new Token(Type.null, null, 1);
2622
- }
2623
- return new Token(Type.undefined, void 0, 1);
2624
- }
2625
- function decodeBreak(_data, _pos, _minor, options) {
2626
- if (options.allowIndefinite === false) {
2627
- throw new Error(`${decodeErrPrefix} indefinite length items not allowed`);
2628
- }
2629
- return new Token(Type.break, void 0, 1);
2630
- }
2631
- function createToken(value, bytes, options) {
2632
- if (options) {
2633
- if (options.allowNaN === false && Number.isNaN(value)) {
2634
- throw new Error(`${decodeErrPrefix} NaN values are not supported`);
2635
- }
2636
- if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {
2637
- throw new Error(`${decodeErrPrefix} Infinity values are not supported`);
2638
- }
2639
- }
2640
- return new Token(Type.float, value, bytes);
2641
- }
2642
- function decodeFloat16(data, pos, _minor, options) {
2643
- return createToken(readFloat16(data, pos + 1), 3, options);
2644
- }
2645
- function decodeFloat32(data, pos, _minor, options) {
2646
- return createToken(readFloat32(data, pos + 1), 5, options);
2647
- }
2648
- function decodeFloat64(data, pos, _minor, options) {
2649
- return createToken(readFloat64(data, pos + 1), 9, options);
2650
- }
2651
- function encodeFloat(buf2, token, options) {
2652
- const float = token.value;
2653
- if (float === false) {
2654
- buf2.push([Type.float.majorEncoded | MINOR_FALSE]);
2655
- } else if (float === true) {
2656
- buf2.push([Type.float.majorEncoded | MINOR_TRUE]);
2657
- } else if (float === null) {
2658
- buf2.push([Type.float.majorEncoded | MINOR_NULL]);
2659
- } else if (float === void 0) {
2660
- buf2.push([Type.float.majorEncoded | MINOR_UNDEFINED]);
2661
- } else {
2662
- let decoded;
2663
- let success = false;
2664
- if (!options || options.float64 !== true) {
2665
- encodeFloat16(float);
2666
- decoded = readFloat16(ui8a, 1);
2667
- if (float === decoded || Number.isNaN(float)) {
2668
- ui8a[0] = 249;
2669
- buf2.push(ui8a.slice(0, 3));
2670
- success = true;
2671
- } else {
2672
- encodeFloat32(float);
2673
- decoded = readFloat32(ui8a, 1);
2674
- if (float === decoded) {
2675
- ui8a[0] = 250;
2676
- buf2.push(ui8a.slice(0, 5));
2677
- success = true;
2678
- }
2679
- }
2680
- }
2681
- if (!success) {
2682
- encodeFloat64(float);
2683
- decoded = readFloat64(ui8a, 1);
2684
- ui8a[0] = 251;
2685
- buf2.push(ui8a.slice(0, 9));
2686
- }
2687
- }
2688
- }
2689
- encodeFloat.encodedSize = function encodedSize8(token, options) {
2690
- const float = token.value;
2691
- if (float === false || float === true || float === null || float === void 0) {
2692
- return 1;
2693
- }
2694
- if (!options || options.float64 !== true) {
2695
- encodeFloat16(float);
2696
- let decoded = readFloat16(ui8a, 1);
2697
- if (float === decoded || Number.isNaN(float)) {
2698
- return 3;
2699
- }
2700
- encodeFloat32(float);
2701
- decoded = readFloat32(ui8a, 1);
2702
- if (float === decoded) {
2703
- return 5;
2704
- }
2705
- }
2706
- return 9;
2707
- };
2708
- var buffer = new ArrayBuffer(9);
2709
- var dataView = new DataView(buffer, 1);
2710
- var ui8a = new Uint8Array(buffer, 0);
2711
- function encodeFloat16(inp) {
2712
- if (inp === Infinity) {
2713
- dataView.setUint16(0, 31744, false);
2714
- } else if (inp === -Infinity) {
2715
- dataView.setUint16(0, 64512, false);
2716
- } else if (Number.isNaN(inp)) {
2717
- dataView.setUint16(0, 32256, false);
2718
- } else {
2719
- dataView.setFloat32(0, inp);
2720
- const valu32 = dataView.getUint32(0);
2721
- const exponent = (valu32 & 2139095040) >> 23;
2722
- const mantissa = valu32 & 8388607;
2723
- if (exponent === 255) {
2724
- dataView.setUint16(0, 31744, false);
2725
- } else if (exponent === 0) {
2726
- dataView.setUint16(0, (inp & 2147483648) >> 16 | mantissa >> 13, false);
2727
- } else {
2728
- const logicalExponent = exponent - 127;
2729
- if (logicalExponent < -24) {
2730
- dataView.setUint16(0, 0);
2731
- } else if (logicalExponent < -14) {
2732
- dataView.setUint16(0, (valu32 & 2147483648) >> 16 | /* sign bit */
2733
- 1 << 24 + logicalExponent, false);
2734
- } else {
2735
- dataView.setUint16(0, (valu32 & 2147483648) >> 16 | logicalExponent + 15 << 10 | mantissa >> 13, false);
2736
- }
2737
- }
2738
- }
2739
- }
2740
- function readFloat16(ui8a2, pos) {
2741
- if (ui8a2.length - pos < 2) {
2742
- throw new Error(`${decodeErrPrefix} not enough data for float16`);
2743
- }
2744
- const half = (ui8a2[pos] << 8) + ui8a2[pos + 1];
2745
- if (half === 31744) {
2746
- return Infinity;
2747
- }
2748
- if (half === 64512) {
2749
- return -Infinity;
2750
- }
2751
- if (half === 32256) {
2752
- return NaN;
2753
- }
2754
- const exp = half >> 10 & 31;
2755
- const mant = half & 1023;
2756
- let val;
2757
- if (exp === 0) {
2758
- val = mant * 2 ** -24;
2759
- } else if (exp !== 31) {
2760
- val = (mant + 1024) * 2 ** (exp - 25);
2761
- } else {
2762
- val = mant === 0 ? Infinity : NaN;
2763
- }
2764
- return half & 32768 ? -val : val;
2765
- }
2766
- function encodeFloat32(inp) {
2767
- dataView.setFloat32(0, inp, false);
2768
- }
2769
- function readFloat32(ui8a2, pos) {
2770
- if (ui8a2.length - pos < 4) {
2771
- throw new Error(`${decodeErrPrefix} not enough data for float32`);
2772
- }
2773
- const offset = (ui8a2.byteOffset || 0) + pos;
2774
- return new DataView(ui8a2.buffer, offset, 4).getFloat32(0, false);
2775
- }
2776
- function encodeFloat64(inp) {
2777
- dataView.setFloat64(0, inp, false);
2778
- }
2779
- function readFloat64(ui8a2, pos) {
2780
- if (ui8a2.length - pos < 8) {
2781
- throw new Error(`${decodeErrPrefix} not enough data for float64`);
2782
- }
2783
- const offset = (ui8a2.byteOffset || 0) + pos;
2784
- return new DataView(ui8a2.buffer, offset, 8).getFloat64(0, false);
2785
- }
2786
- encodeFloat.compareTokens = encodeUint.compareTokens;
2787
-
2788
- // ../../node_modules/.pnpm/cborg@4.2.12/node_modules/cborg/lib/jump.js
2789
- function invalidMinor(data, pos, minor) {
2790
- throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`);
2791
- }
2792
- function errorer(msg) {
2793
- return () => {
2794
- throw new Error(`${decodeErrPrefix} ${msg}`);
2795
- };
2796
- }
2797
- var jump = [];
2798
- for (let i = 0; i <= 23; i++) {
2799
- jump[i] = invalidMinor;
2800
- }
2801
- jump[24] = decodeUint8;
2802
- jump[25] = decodeUint16;
2803
- jump[26] = decodeUint32;
2804
- jump[27] = decodeUint64;
2805
- jump[28] = invalidMinor;
2806
- jump[29] = invalidMinor;
2807
- jump[30] = invalidMinor;
2808
- jump[31] = invalidMinor;
2809
- for (let i = 32; i <= 55; i++) {
2810
- jump[i] = invalidMinor;
2811
- }
2812
- jump[56] = decodeNegint8;
2813
- jump[57] = decodeNegint16;
2814
- jump[58] = decodeNegint32;
2815
- jump[59] = decodeNegint64;
2816
- jump[60] = invalidMinor;
2817
- jump[61] = invalidMinor;
2818
- jump[62] = invalidMinor;
2819
- jump[63] = invalidMinor;
2820
- for (let i = 64; i <= 87; i++) {
2821
- jump[i] = decodeBytesCompact;
2822
- }
2823
- jump[88] = decodeBytes8;
2824
- jump[89] = decodeBytes16;
2825
- jump[90] = decodeBytes32;
2826
- jump[91] = decodeBytes64;
2827
- jump[92] = invalidMinor;
2828
- jump[93] = invalidMinor;
2829
- jump[94] = invalidMinor;
2830
- jump[95] = errorer("indefinite length bytes/strings are not supported");
2831
- for (let i = 96; i <= 119; i++) {
2832
- jump[i] = decodeStringCompact;
2833
- }
2834
- jump[120] = decodeString8;
2835
- jump[121] = decodeString16;
2836
- jump[122] = decodeString32;
2837
- jump[123] = decodeString64;
2838
- jump[124] = invalidMinor;
2839
- jump[125] = invalidMinor;
2840
- jump[126] = invalidMinor;
2841
- jump[127] = errorer("indefinite length bytes/strings are not supported");
2842
- for (let i = 128; i <= 151; i++) {
2843
- jump[i] = decodeArrayCompact;
2844
- }
2845
- jump[152] = decodeArray8;
2846
- jump[153] = decodeArray16;
2847
- jump[154] = decodeArray32;
2848
- jump[155] = decodeArray64;
2849
- jump[156] = invalidMinor;
2850
- jump[157] = invalidMinor;
2851
- jump[158] = invalidMinor;
2852
- jump[159] = decodeArrayIndefinite;
2853
- for (let i = 160; i <= 183; i++) {
2854
- jump[i] = decodeMapCompact;
2855
- }
2856
- jump[184] = decodeMap8;
2857
- jump[185] = decodeMap16;
2858
- jump[186] = decodeMap32;
2859
- jump[187] = decodeMap64;
2860
- jump[188] = invalidMinor;
2861
- jump[189] = invalidMinor;
2862
- jump[190] = invalidMinor;
2863
- jump[191] = decodeMapIndefinite;
2864
- for (let i = 192; i <= 215; i++) {
2865
- jump[i] = decodeTagCompact;
2866
- }
2867
- jump[216] = decodeTag8;
2868
- jump[217] = decodeTag16;
2869
- jump[218] = decodeTag32;
2870
- jump[219] = decodeTag64;
2871
- jump[220] = invalidMinor;
2872
- jump[221] = invalidMinor;
2873
- jump[222] = invalidMinor;
2874
- jump[223] = invalidMinor;
2875
- for (let i = 224; i <= 243; i++) {
2876
- jump[i] = errorer("simple values are not supported");
2877
- }
2878
- jump[244] = invalidMinor;
2879
- jump[245] = invalidMinor;
2880
- jump[246] = invalidMinor;
2881
- jump[247] = decodeUndefined;
2882
- jump[248] = errorer("simple values are not supported");
2883
- jump[249] = decodeFloat16;
2884
- jump[250] = decodeFloat32;
2885
- jump[251] = decodeFloat64;
2886
- jump[252] = invalidMinor;
2887
- jump[253] = invalidMinor;
2888
- jump[254] = invalidMinor;
2889
- jump[255] = decodeBreak;
2890
- var quick = [];
2891
- for (let i = 0; i < 24; i++) {
2892
- quick[i] = new Token(Type.uint, i, 1);
2893
- }
2894
- for (let i = -1; i >= -24; i--) {
2895
- quick[31 - i] = new Token(Type.negint, i, 1);
2896
- }
2897
- quick[64] = new Token(Type.bytes, new Uint8Array(0), 1);
2898
- quick[96] = new Token(Type.string, "", 1);
2899
- quick[128] = new Token(Type.array, 0, 1);
2900
- quick[160] = new Token(Type.map, 0, 1);
2901
- quick[244] = new Token(Type.false, false, 1);
2902
- quick[245] = new Token(Type.true, true, 1);
2903
- quick[246] = new Token(Type.null, null, 1);
2904
- function quickEncodeToken(token) {
2905
- switch (token.type) {
2906
- case Type.false:
2907
- return fromArray([244]);
2908
- case Type.true:
2909
- return fromArray([245]);
2910
- case Type.null:
2911
- return fromArray([246]);
2912
- case Type.bytes:
2913
- if (!token.value.length) {
2914
- return fromArray([64]);
2915
- }
2916
- return;
2917
- case Type.string:
2918
- if (token.value === "") {
2919
- return fromArray([96]);
2920
- }
2921
- return;
2922
- case Type.array:
2923
- if (token.value === 0) {
2924
- return fromArray([128]);
2925
- }
2926
- return;
2927
- case Type.map:
2928
- if (token.value === 0) {
2929
- return fromArray([160]);
2930
- }
2931
- return;
2932
- case Type.uint:
2933
- if (token.value < 24) {
2934
- return fromArray([Number(token.value)]);
2935
- }
2936
- return;
2937
- case Type.negint:
2938
- if (token.value >= -24) {
2939
- return fromArray([31 - Number(token.value)]);
2940
- }
2941
- }
2942
- }
2943
-
2944
- // ../../node_modules/.pnpm/cborg@4.2.12/node_modules/cborg/lib/encode.js
2945
- var defaultEncodeOptions = {
2946
- float64: false,
2947
- mapSorter,
2948
- quickEncodeToken
2949
- };
2950
- function makeCborEncoders() {
2951
- const encoders = [];
2952
- encoders[Type.uint.major] = encodeUint;
2953
- encoders[Type.negint.major] = encodeNegint;
2954
- encoders[Type.bytes.major] = encodeBytes;
2955
- encoders[Type.string.major] = encodeString;
2956
- encoders[Type.array.major] = encodeArray;
2957
- encoders[Type.map.major] = encodeMap;
2958
- encoders[Type.tag.major] = encodeTag;
2959
- encoders[Type.float.major] = encodeFloat;
2960
- return encoders;
2961
- }
2962
- var cborEncoders = makeCborEncoders();
2963
- var buf = new Bl();
2964
- var Ref = class _Ref {
2965
- /**
2966
- * @param {object|any[]} obj
2967
- * @param {Reference|undefined} parent
2968
- */
2969
- constructor(obj, parent) {
2970
- this.obj = obj;
2971
- this.parent = parent;
2972
- }
2973
- /**
2974
- * @param {object|any[]} obj
2975
- * @returns {boolean}
2976
- */
2977
- includes(obj) {
2978
- let p = this;
2979
- do {
2980
- if (p.obj === obj) {
2981
- return true;
2982
- }
2983
- } while (p = p.parent);
2984
- return false;
2985
- }
2986
- /**
2987
- * @param {Reference|undefined} stack
2988
- * @param {object|any[]} obj
2989
- * @returns {Reference}
2990
- */
2991
- static createCheck(stack, obj) {
2992
- if (stack && stack.includes(obj)) {
2993
- throw new Error(`${encodeErrPrefix} object contains circular references`);
2994
- }
2995
- return new _Ref(obj, stack);
2996
- }
2997
- };
2998
- var simpleTokens = {
2999
- null: new Token(Type.null, null),
3000
- undefined: new Token(Type.undefined, void 0),
3001
- true: new Token(Type.true, true),
3002
- false: new Token(Type.false, false),
3003
- emptyArray: new Token(Type.array, 0),
3004
- emptyMap: new Token(Type.map, 0)
3005
- };
3006
- var typeEncoders = {
3007
- /**
3008
- * @param {any} obj
3009
- * @param {string} _typ
3010
- * @param {EncodeOptions} _options
3011
- * @param {Reference} [_refStack]
3012
- * @returns {TokenOrNestedTokens}
3013
- */
3014
- number(obj, _typ, _options, _refStack) {
3015
- if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {
3016
- return new Token(Type.float, obj);
3017
- } else if (obj >= 0) {
3018
- return new Token(Type.uint, obj);
3019
- } else {
3020
- return new Token(Type.negint, obj);
3021
- }
3022
- },
3023
- /**
3024
- * @param {any} obj
3025
- * @param {string} _typ
3026
- * @param {EncodeOptions} _options
3027
- * @param {Reference} [_refStack]
3028
- * @returns {TokenOrNestedTokens}
3029
- */
3030
- bigint(obj, _typ, _options, _refStack) {
3031
- if (obj >= BigInt(0)) {
3032
- return new Token(Type.uint, obj);
3033
- } else {
3034
- return new Token(Type.negint, obj);
3035
- }
3036
- },
3037
- /**
3038
- * @param {any} obj
3039
- * @param {string} _typ
3040
- * @param {EncodeOptions} _options
3041
- * @param {Reference} [_refStack]
3042
- * @returns {TokenOrNestedTokens}
3043
- */
3044
- Uint8Array(obj, _typ, _options, _refStack) {
3045
- return new Token(Type.bytes, obj);
3046
- },
3047
- /**
3048
- * @param {any} obj
3049
- * @param {string} _typ
3050
- * @param {EncodeOptions} _options
3051
- * @param {Reference} [_refStack]
3052
- * @returns {TokenOrNestedTokens}
3053
- */
3054
- string(obj, _typ, _options, _refStack) {
3055
- return new Token(Type.string, obj);
3056
- },
3057
- /**
3058
- * @param {any} obj
3059
- * @param {string} _typ
3060
- * @param {EncodeOptions} _options
3061
- * @param {Reference} [_refStack]
3062
- * @returns {TokenOrNestedTokens}
3063
- */
3064
- boolean(obj, _typ, _options, _refStack) {
3065
- return obj ? simpleTokens.true : simpleTokens.false;
3066
- },
3067
- /**
3068
- * @param {any} _obj
3069
- * @param {string} _typ
3070
- * @param {EncodeOptions} _options
3071
- * @param {Reference} [_refStack]
3072
- * @returns {TokenOrNestedTokens}
3073
- */
3074
- null(_obj, _typ, _options, _refStack) {
3075
- return simpleTokens.null;
3076
- },
3077
- /**
3078
- * @param {any} _obj
3079
- * @param {string} _typ
3080
- * @param {EncodeOptions} _options
3081
- * @param {Reference} [_refStack]
3082
- * @returns {TokenOrNestedTokens}
3083
- */
3084
- undefined(_obj, _typ, _options, _refStack) {
3085
- return simpleTokens.undefined;
3086
- },
3087
- /**
3088
- * @param {any} obj
3089
- * @param {string} _typ
3090
- * @param {EncodeOptions} _options
3091
- * @param {Reference} [_refStack]
3092
- * @returns {TokenOrNestedTokens}
3093
- */
3094
- ArrayBuffer(obj, _typ, _options, _refStack) {
3095
- return new Token(Type.bytes, new Uint8Array(obj));
3096
- },
3097
- /**
3098
- * @param {any} obj
3099
- * @param {string} _typ
3100
- * @param {EncodeOptions} _options
3101
- * @param {Reference} [_refStack]
3102
- * @returns {TokenOrNestedTokens}
3103
- */
3104
- DataView(obj, _typ, _options, _refStack) {
3105
- return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength));
3106
- },
3107
- /**
3108
- * @param {any} obj
3109
- * @param {string} _typ
3110
- * @param {EncodeOptions} options
3111
- * @param {Reference} [refStack]
3112
- * @returns {TokenOrNestedTokens}
3113
- */
3114
- Array(obj, _typ, options, refStack) {
3115
- if (!obj.length) {
3116
- if (options.addBreakTokens === true) {
3117
- return [simpleTokens.emptyArray, new Token(Type.break)];
3118
- }
3119
- return simpleTokens.emptyArray;
3120
- }
3121
- refStack = Ref.createCheck(refStack, obj);
3122
- const entries = [];
3123
- let i = 0;
3124
- for (const e of obj) {
3125
- entries[i++] = objectToTokens(e, options, refStack);
3126
- }
3127
- if (options.addBreakTokens) {
3128
- return [new Token(Type.array, obj.length), entries, new Token(Type.break)];
3129
- }
3130
- return [new Token(Type.array, obj.length), entries];
3131
- },
3132
- /**
3133
- * @param {any} obj
3134
- * @param {string} typ
3135
- * @param {EncodeOptions} options
3136
- * @param {Reference} [refStack]
3137
- * @returns {TokenOrNestedTokens}
3138
- */
3139
- Object(obj, typ, options, refStack) {
3140
- const isMap = typ !== "Object";
3141
- const keys = isMap ? obj.keys() : Object.keys(obj);
3142
- const length2 = isMap ? obj.size : keys.length;
3143
- if (!length2) {
3144
- if (options.addBreakTokens === true) {
3145
- return [simpleTokens.emptyMap, new Token(Type.break)];
3146
- }
3147
- return simpleTokens.emptyMap;
3148
- }
3149
- refStack = Ref.createCheck(refStack, obj);
3150
- const entries = [];
3151
- let i = 0;
3152
- for (const key of keys) {
3153
- entries[i++] = [
3154
- objectToTokens(key, options, refStack),
3155
- objectToTokens(isMap ? obj.get(key) : obj[key], options, refStack)
3156
- ];
3157
- }
3158
- sortMapEntries(entries, options);
3159
- if (options.addBreakTokens) {
3160
- return [new Token(Type.map, length2), entries, new Token(Type.break)];
3161
- }
3162
- return [new Token(Type.map, length2), entries];
3163
- }
3164
- };
3165
- typeEncoders.Map = typeEncoders.Object;
3166
- typeEncoders.Buffer = typeEncoders.Uint8Array;
3167
- for (const typ of "Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" ")) {
3168
- typeEncoders[`${typ}Array`] = typeEncoders.DataView;
3169
- }
3170
- function objectToTokens(obj, options = {}, refStack) {
3171
- const typ = is(obj);
3172
- const customTypeEncoder = options && options.typeEncoders && /** @type {OptionalTypeEncoder} */
3173
- options.typeEncoders[typ] || typeEncoders[typ];
3174
- if (typeof customTypeEncoder === "function") {
3175
- const tokens = customTypeEncoder(obj, typ, options, refStack);
3176
- if (tokens != null) {
3177
- return tokens;
3178
- }
3179
- }
3180
- const typeEncoder = typeEncoders[typ];
3181
- if (!typeEncoder) {
3182
- throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`);
3183
- }
3184
- return typeEncoder(obj, typ, options, refStack);
3185
- }
3186
- function sortMapEntries(entries, options) {
3187
- if (options.mapSorter) {
3188
- entries.sort(options.mapSorter);
3189
- }
3190
- }
3191
- function mapSorter(e1, e2) {
3192
- const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0];
3193
- const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0];
3194
- if (keyToken1.type !== keyToken2.type) {
3195
- return keyToken1.type.compare(keyToken2.type);
3196
- }
3197
- const major = keyToken1.type.major;
3198
- const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2);
3199
- if (tcmp === 0) {
3200
- console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone");
3201
- }
3202
- return tcmp;
3203
- }
3204
- function tokensToEncoded(buf2, tokens, encoders, options) {
3205
- if (Array.isArray(tokens)) {
3206
- for (const token of tokens) {
3207
- tokensToEncoded(buf2, token, encoders, options);
3208
- }
3209
- } else {
3210
- encoders[tokens.type.major](buf2, tokens, options);
3211
- }
3212
- }
3213
- function encodeCustom(data, encoders, options) {
3214
- const tokens = objectToTokens(data, options);
3215
- if (!Array.isArray(tokens) && options.quickEncodeToken) {
3216
- const quickBytes = options.quickEncodeToken(tokens);
3217
- if (quickBytes) {
3218
- return quickBytes;
3219
- }
3220
- const encoder = encoders[tokens.type.major];
3221
- if (encoder.encodedSize) {
3222
- const size = encoder.encodedSize(tokens, options);
3223
- const buf2 = new Bl(size);
3224
- encoder(buf2, tokens, options);
3225
- if (buf2.chunks.length !== 1) {
3226
- throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`);
3227
- }
3228
- return asU8A(buf2.chunks[0]);
3229
- }
3230
- }
3231
- buf.reset();
3232
- tokensToEncoded(buf, tokens, encoders, options);
3233
- return buf.toBytes(true);
3234
- }
3235
- function encode4(data, options) {
3236
- options = Object.assign({}, defaultEncodeOptions, options);
3237
- return encodeCustom(data, cborEncoders, options);
3238
- }
3239
-
3240
- // ../../node_modules/.pnpm/cborg@4.2.12/node_modules/cborg/lib/decode.js
3241
- var defaultDecodeOptions = {
3242
- strict: false,
3243
- allowIndefinite: true,
3244
- allowUndefined: true,
3245
- allowBigInt: true
3246
- };
3247
- var Tokeniser = class {
3248
- /**
3249
- * @param {Uint8Array} data
3250
- * @param {DecodeOptions} options
3251
- */
3252
- constructor(data, options = {}) {
3253
- this._pos = 0;
3254
- this.data = data;
3255
- this.options = options;
3256
- }
3257
- pos() {
3258
- return this._pos;
3259
- }
3260
- done() {
3261
- return this._pos >= this.data.length;
3262
- }
3263
- next() {
3264
- const byt = this.data[this._pos];
3265
- let token = quick[byt];
3266
- if (token === void 0) {
3267
- const decoder = jump[byt];
3268
- if (!decoder) {
3269
- throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, "0")})`);
3270
- }
3271
- const minor = byt & 31;
3272
- token = decoder(this.data, this._pos, minor, this.options);
3273
- }
3274
- this._pos += token.encodedLength;
3275
- return token;
3276
- }
3277
- };
3278
- var DONE = Symbol.for("DONE");
3279
- var BREAK = Symbol.for("BREAK");
3280
- function tokenToArray(token, tokeniser, options) {
3281
- const arr = [];
3282
- for (let i = 0; i < token.value; i++) {
3283
- const value = tokensToObject(tokeniser, options);
3284
- if (value === BREAK) {
3285
- if (token.value === Infinity) {
3286
- break;
3287
- }
3288
- throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`);
3289
- }
3290
- if (value === DONE) {
3291
- throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`);
3292
- }
3293
- arr[i] = value;
3294
- }
3295
- return arr;
3296
- }
3297
- function tokenToMap(token, tokeniser, options) {
3298
- const useMaps = options.useMaps === true;
3299
- const obj = useMaps ? void 0 : {};
3300
- const m = useMaps ? /* @__PURE__ */ new Map() : void 0;
3301
- for (let i = 0; i < token.value; i++) {
3302
- const key = tokensToObject(tokeniser, options);
3303
- if (key === BREAK) {
3304
- if (token.value === Infinity) {
3305
- break;
3306
- }
3307
- throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`);
3308
- }
3309
- if (key === DONE) {
3310
- throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`);
3311
- }
3312
- if (useMaps !== true && typeof key !== "string") {
3313
- throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`);
3314
- }
3315
- if (options.rejectDuplicateMapKeys === true) {
3316
- if (useMaps && m.has(key) || !useMaps && key in obj) {
3317
- throw new Error(`${decodeErrPrefix} found repeat map key "${key}"`);
3318
- }
3319
- }
3320
- const value = tokensToObject(tokeniser, options);
3321
- if (value === DONE) {
3322
- throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`);
3323
- }
3324
- if (useMaps) {
3325
- m.set(key, value);
3326
- } else {
3327
- obj[key] = value;
3328
- }
3329
- }
3330
- return useMaps ? m : obj;
3331
- }
3332
- function tokensToObject(tokeniser, options) {
3333
- if (tokeniser.done()) {
3334
- return DONE;
3335
- }
3336
- const token = tokeniser.next();
3337
- if (token.type === Type.break) {
3338
- return BREAK;
3339
- }
3340
- if (token.type.terminal) {
3341
- return token.value;
3342
- }
3343
- if (token.type === Type.array) {
3344
- return tokenToArray(token, tokeniser, options);
3345
- }
3346
- if (token.type === Type.map) {
3347
- return tokenToMap(token, tokeniser, options);
3348
- }
3349
- if (token.type === Type.tag) {
3350
- if (options.tags && typeof options.tags[token.value] === "function") {
3351
- const tagged = tokensToObject(tokeniser, options);
3352
- return options.tags[token.value](tagged);
3353
- }
3354
- throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`);
3355
- }
3356
- throw new Error("unsupported");
3357
- }
3358
- function decodeFirst(data, options) {
3359
- if (!(data instanceof Uint8Array)) {
3360
- throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`);
3361
- }
3362
- options = Object.assign({}, defaultDecodeOptions, options);
3363
- const tokeniser = options.tokenizer || new Tokeniser(data, options);
3364
- const decoded = tokensToObject(tokeniser, options);
3365
- if (decoded === DONE) {
3366
- throw new Error(`${decodeErrPrefix} did not find any content to decode`);
3367
- }
3368
- if (decoded === BREAK) {
3369
- throw new Error(`${decodeErrPrefix} got unexpected break`);
3370
- }
3371
- return [decoded, data.subarray(tokeniser.pos())];
3372
- }
3373
- function decode6(data, options) {
3374
- const [decoded, remainder] = decodeFirst(data, options);
3375
- if (remainder.length > 0) {
3376
- throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`);
3377
- }
3378
- return decoded;
3379
- }
3380
-
3381
- // ../../node_modules/.pnpm/@ipld+dag-cbor@9.0.5/node_modules/@ipld/dag-cbor/src/index.js
3382
- var CID_CBOR_TAG = 42;
3383
- function cidEncoder(obj) {
3384
- if (obj.asCID !== obj && obj["/"] !== obj.bytes) {
3385
- return null;
3386
- }
3387
- const cid = CID.asCID(obj);
3388
- if (!cid) {
3389
- return null;
3390
- }
3391
- const bytes = new Uint8Array(cid.bytes.byteLength + 1);
3392
- bytes.set(cid.bytes, 1);
3393
- return [
3394
- new Token(Type.tag, CID_CBOR_TAG),
3395
- new Token(Type.bytes, bytes)
3396
- ];
3397
- }
3398
- function undefinedEncoder() {
3399
- throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded");
3400
- }
3401
- function numberEncoder(num) {
3402
- if (Number.isNaN(num)) {
3403
- throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");
3404
- }
3405
- if (num === Infinity || num === -Infinity) {
3406
- throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");
3407
- }
3408
- return null;
3409
- }
3410
- var encodeOptions = {
3411
- float64: true,
3412
- typeEncoders: {
3413
- Object: cidEncoder,
3414
- undefined: undefinedEncoder,
3415
- number: numberEncoder
3416
- }
3417
- };
3418
- function cidDecoder(bytes) {
3419
- if (bytes[0] !== 0) {
3420
- throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");
3421
- }
3422
- return CID.decode(bytes.subarray(1));
3423
- }
3424
- var decodeOptions = {
3425
- allowIndefinite: false,
3426
- coerceUndefinedToNull: true,
3427
- allowNaN: false,
3428
- allowInfinity: false,
3429
- allowBigInt: true,
3430
- // this will lead to BigInt for ints outside of
3431
- // safe-integer range, which may surprise users
3432
- strict: true,
3433
- useMaps: false,
3434
- rejectDuplicateMapKeys: true,
3435
- /** @type {import('cborg').TagDecoder[]} */
3436
- tags: []
3437
- };
3438
- decodeOptions.tags[CID_CBOR_TAG] = cidDecoder;
3439
- var name = "dag-cbor";
3440
- var code = 113;
3441
- var encode5 = (node) => encode4(node, encodeOptions);
3442
- var decode7 = (data) => decode6(data, decodeOptions);
3443
-
3444
- // ../../node_modules/.pnpm/multiformats@12.0.1/node_modules/multiformats/src/hashes/sha2.js
3445
- var import_crypto = __toESM(require("crypto"), 1);
3446
- var sha256 = from2({
3447
- name: "sha2-256",
3448
- code: 18,
3449
- encode: (input) => coerce(import_crypto.default.createHash("sha256").update(input).digest())
3450
- });
3451
- var sha512 = from2({
3452
- name: "sha2-512",
3453
- code: 19,
3454
- encode: (input) => coerce(import_crypto.default.createHash("sha512").update(input).digest())
3455
- });
3456
-
3457
- // dist/esm/src/message-store-sql.js
3458
- var MessageStoreSql = class {
3459
- #dialect;
3460
- #tags;
3461
- #db = null;
3462
- constructor(dialect) {
3463
- this.#dialect = dialect;
3464
- this.#tags = new TagTables(dialect, "messageStoreMessages");
3465
- }
3466
- async open() {
3467
- if (this.#db) {
3468
- return;
3469
- }
3470
- this.#db = new import_kysely7.Kysely({ dialect: this.#dialect });
3471
- const messagesTableName = "messageStoreMessages";
3472
- const messagesTableExists = await this.#dialect.hasTable(this.#db, messagesTableName);
3473
- if (!messagesTableExists) {
3474
- let createMessagesTable = this.#db.schema.createTable(messagesTableName).ifNotExists().addColumn("tenant", "varchar(255)", (col) => col.notNull()).addColumn("messageCid", "varchar(60)", (col) => col.notNull()).addColumn("interface", "varchar(20)").addColumn("method", "varchar(20)").addColumn("recordId", "varchar(60)").addColumn("entryId", "varchar(60)").addColumn("parentId", "varchar(60)").addColumn("protocol", "varchar(200)").addColumn("protocolPath", "varchar(200)").addColumn("contextId", "varchar(500)").addColumn("schema", "varchar(200)").addColumn("author", "varchar(255)").addColumn("recipient", "varchar(255)").addColumn("messageTimestamp", "varchar(30)").addColumn("dateCreated", "varchar(30)").addColumn("datePublished", "varchar(30)").addColumn("isLatestBaseState", "boolean").addColumn("published", "boolean").addColumn("prune", "boolean").addColumn("dataFormat", "varchar(30)").addColumn("dataCid", "varchar(60)").addColumn("dataSize", "integer").addColumn("encodedData", "text").addColumn("attester", "text").addColumn("permissionGrantId", "varchar(60)").addColumn("latest", "text");
3475
- createMessagesTable = this.#dialect.addAutoIncrementingColumn(createMessagesTable, "id", (col) => col.primaryKey());
3476
- createMessagesTable = this.#dialect.addBlobColumn(createMessagesTable, "encodedMessageBytes", (col) => col.notNull());
3477
- await createMessagesTable.execute();
3478
- await this.createIndexes(this.#db, messagesTableName, [
3479
- ["tenant"],
3480
- ["tenant", "recordId"],
3481
- ["tenant", "parentId"],
3482
- ["tenant", "protocol", "published", "messageTimestamp"],
3483
- ["tenant", "interface"],
3484
- ["tenant", "contextId", "messageTimestamp"],
3485
- ["tenant", "permissionGrantId"]
3486
- // for deleting grant-authorized messages though pending https://github.com/TBD54566975/dwn-sdk-js/issues/716
3487
- // other potential indexes
3488
- // ['tenant', 'author'],
3489
- // ['tenant', 'recipient'],
3490
- // ['tenant', 'schema', 'dataFormat'],
3491
- // ['tenant', 'dateCreated'],
3492
- // ['tenant', 'datePublished'],
3493
- // ['tenant', 'messageCid'],
3494
- // ['tenant', 'protocolPath'],
3495
- ]);
3496
- }
3497
- const tagsTableName = "messageStoreRecordsTags";
3498
- const tagsTableExists = await this.#dialect.hasTable(this.#db, tagsTableName);
3499
- if (!tagsTableExists) {
3500
- let createRecordsTagsTable = this.#db.schema.createTable(tagsTableName).ifNotExists().addColumn("tag", "varchar(30)", (col) => col.notNull()).addColumn("valueString", "varchar(200)").addColumn("valueNumber", "decimal");
3501
- const foreignMessageInsertId = "messageInsertId";
3502
- createRecordsTagsTable = this.#dialect.addAutoIncrementingColumn(createRecordsTagsTable, "id", (col) => col.primaryKey());
3503
- createRecordsTagsTable = this.#dialect.addReferencedColumn(createRecordsTagsTable, tagsTableName, foreignMessageInsertId, "integer", "messageStoreMessages", "id", "cascade");
3504
- await createRecordsTagsTable.execute();
3505
- await this.createIndexes(this.#db, tagsTableName, [
3506
- [foreignMessageInsertId],
3507
- ["tag", "valueString"],
3508
- ["tag", "valueNumber"]
3509
- ]);
3510
- }
3511
- }
3512
- /**
3513
- * Creates indexes on the given table.
3514
- * @param tableName The name of the table to create the indexes on.
3515
- * @param indexes Each inner array represents a single index and contains the column names to be indexed as a composite index.
3516
- * If the inner array contains only one element, it will be treated as a single column index.
3517
- */
3518
- async createIndexes(database, tableName, indexes) {
3519
- for (const columnNames of indexes) {
3520
- const indexName = "index_" + columnNames.join("_");
3521
- await database.schema.createIndex(indexName).on(tableName).columns(columnNames).execute();
3522
- }
3523
- }
3524
- async close() {
3525
- await this.#db?.destroy();
3526
- this.#db = null;
3527
- }
3528
- async put(tenant, message, indexes, options) {
3529
- if (!this.#db) {
3530
- throw new Error("Connection to database not open. Call `open` before using `put`.");
3531
- }
3532
- options?.signal?.throwIfAborted();
3533
- const getEncodedData = (message2) => {
3534
- let encodedData2 = null;
3535
- if (message2.descriptor.interface === import_dwn_sdk_js2.DwnInterfaceName.Records && message2.descriptor.method === import_dwn_sdk_js2.DwnMethodName.Write) {
3536
- const data = message2.encodedData;
3537
- if (data) {
3538
- delete message2.encodedData;
3539
- encodedData2 = data;
3540
- }
3541
- }
3542
- return { message: message2, encodedData: encodedData2 };
3543
- };
3544
- const { message: messageToProcess, encodedData } = getEncodedData(message);
3545
- const encodedMessageBlock = await (0, import_dwn_sdk_js2.executeUnlessAborted)(encode3({ value: messageToProcess, codec: src_exports, hasher: sha256 }), options?.signal);
3546
- const messageCid = encodedMessageBlock.cid.toString();
3547
- const encodedMessageBytes = Buffer.from(encodedMessageBlock.bytes);
3548
- const putMessageOperation = this.constructPutMessageOperation({ tenant, messageCid, encodedMessageBytes, encodedData, indexes });
3549
- await executeWithRetryIfDatabaseIsLocked(this.#db, putMessageOperation);
3550
- }
3551
- /**
3552
- * Constructs the transactional operation to insert the given message into the database.
3553
- */
3554
- constructPutMessageOperation(queryOptions) {
3555
- const { tenant, messageCid, encodedMessageBytes, encodedData, indexes } = queryOptions;
3556
- const { indexes: putIndexes, tags } = extractTagsAndSanitizeIndexes(indexes);
3557
- return async (tx) => {
3558
- const messageIndexValues = {
3559
- tenant,
3560
- messageCid,
3561
- encodedMessageBytes,
3562
- encodedData,
3563
- ...putIndexes
3564
- };
3565
- const result = await this.#dialect.insertThenReturnId(tx, "messageStoreMessages", messageIndexValues, "id as insertId").executeTakeFirstOrThrow();
3566
- if (Object.keys(tags).length > 0) {
3567
- await this.#tags.executeTagsInsert(result.insertId, tags, tx);
3568
- }
3569
- };
3570
- }
3571
- async get(tenant, cid, options) {
3572
- if (!this.#db) {
3573
- throw new Error("Connection to database not open. Call `open` before using `get`.");
3574
- }
3575
- options?.signal?.throwIfAborted();
3576
- const result = await (0, import_dwn_sdk_js2.executeUnlessAborted)(this.#db.selectFrom("messageStoreMessages").selectAll().where("tenant", "=", tenant).where("messageCid", "=", cid).executeTakeFirst(), options?.signal);
3577
- if (!result) {
3578
- return void 0;
3579
- }
3580
- return this.parseEncodedMessage(result.encodedMessageBytes, result.encodedData, options);
3581
- }
3582
- async query(tenant, filters, messageSort, pagination, options) {
3583
- if (!this.#db) {
3584
- throw new Error("Connection to database not open. Call `open` before using `query`.");
3585
- }
3586
- options?.signal?.throwIfAborted();
3587
- const { property: sortProperty, direction: sortDirection } = this.extractSortProperties(messageSort);
3588
- let query = this.#db.selectFrom("messageStoreMessages").leftJoin("messageStoreRecordsTags", "messageStoreRecordsTags.messageInsertId", "messageStoreMessages.id").select("messageCid").distinct().select([
3589
- "encodedMessageBytes",
3590
- "encodedData",
3591
- sortProperty
3592
- ]).where("tenant", "=", tenant);
3593
- query = filterSelectQuery(filters, query);
3594
- if (pagination?.cursor !== void 0) {
3595
- const cursorValue = pagination.cursor.value;
3596
- const cursorMessageId = pagination.cursor.messageCid;
3597
- query = query.where(({ eb, refTuple, tuple }) => {
3598
- const direction = sortDirection === import_dwn_sdk_js2.SortDirection.Ascending ? ">" : "<";
3599
- return eb(refTuple(sortProperty, "messageCid"), direction, tuple(cursorValue, cursorMessageId));
3600
- });
3601
- }
3602
- const orderDirection = sortDirection === import_dwn_sdk_js2.SortDirection.Ascending ? "asc" : "desc";
3603
- query = query.orderBy(sortProperty, orderDirection).orderBy("messageCid", orderDirection);
3604
- if (pagination?.limit !== void 0 && pagination?.limit > 0) {
3605
- query = query.limit(pagination.limit + 1);
3606
- }
3607
- const results = await (0, import_dwn_sdk_js2.executeUnlessAborted)(query.execute(), options?.signal);
3608
- return this.processPaginationResults(results, sortProperty, pagination?.limit, options);
3609
- }
3610
- async delete(tenant, cid, options) {
3611
- if (!this.#db) {
3612
- throw new Error("Connection to database not open. Call `open` before using `delete`.");
3613
- }
3614
- options?.signal?.throwIfAborted();
3615
- await (0, import_dwn_sdk_js2.executeUnlessAborted)(this.#db.deleteFrom("messageStoreMessages").where("tenant", "=", tenant).where("messageCid", "=", cid).execute(), options?.signal);
3616
- }
3617
- async clear() {
3618
- if (!this.#db) {
3619
- throw new Error("Connection to database not open. Call `open` before using `clear`.");
3620
- }
3621
- await this.#db.deleteFrom("messageStoreMessages").execute();
3622
- }
3623
- async parseEncodedMessage(encodedMessageBytes, encodedData, options) {
3624
- options?.signal?.throwIfAborted();
3625
- const decodedBlock = await decode5({
3626
- bytes: encodedMessageBytes,
3627
- codec: src_exports,
3628
- hasher: sha256
3629
- });
3630
- const message = decodedBlock.value;
3631
- if (message !== void 0 && encodedData !== void 0 && encodedData !== null) {
3632
- message.encodedData = encodedData;
3633
- }
3634
- return message;
3635
- }
3636
- /**
3637
- * Processes the paginated query results.
3638
- * Builds a pagination cursor if there are additional messages to paginate.
3639
- * Accepts more messages than the limit, as we query for additional records to check if we should paginate.
3640
- *
3641
- * @param messages a list of messages, potentially larger than the provided limit.
3642
- * @param limit the maximum number of messages to be returned
3643
- *
3644
- * @returns the pruned message results and an optional pagination cursor
3645
- */
3646
- async processPaginationResults(results, sortProperty, limit, options) {
3647
- let cursor;
3648
- if (limit !== void 0 && results.length > limit) {
3649
- results = results.slice(0, limit);
3650
- const lastMessage = results.at(-1);
3651
- const cursorValue = lastMessage[sortProperty];
3652
- cursor = { messageCid: lastMessage.messageCid, value: cursorValue };
3653
- }
3654
- const messages = results.map((r) => this.parseEncodedMessage(r.encodedMessageBytes, r.encodedData, options));
3655
- return { messages: await Promise.all(messages), cursor };
3656
- }
3657
- /**
3658
- * Extracts the appropriate sort property and direction given a MessageSort object.
3659
- */
3660
- extractSortProperties(messageSort) {
3661
- if (messageSort?.dateCreated !== void 0) {
3662
- return { property: "dateCreated", direction: messageSort.dateCreated };
3663
- } else if (messageSort?.datePublished !== void 0) {
3664
- return { property: "datePublished", direction: messageSort.datePublished };
3665
- } else if (messageSort?.messageTimestamp !== void 0) {
3666
- return { property: "messageTimestamp", direction: messageSort.messageTimestamp };
3667
- } else {
3668
- return { property: "messageTimestamp", direction: import_dwn_sdk_js2.SortDirection.Ascending };
3669
- }
3670
- }
3671
- };
3672
-
3673
- // dist/esm/src/resumable-task-store-sql.js
3674
- var import_kysely8 = require("kysely");
3675
- var import_dwn_sdk_js3 = require("@enbox/dwn-sdk-js");
3676
- var ResumableTaskStoreSql = class _ResumableTaskStoreSql {
3677
- static taskTimeoutInSeconds = 60;
3678
- #dialect;
3679
- #db = null;
3680
- constructor(dialect) {
3681
- this.#dialect = dialect;
3682
- }
3683
- async open() {
3684
- if (this.#db) {
3685
- return;
3686
- }
3687
- this.#db = new import_kysely8.Kysely({ dialect: this.#dialect });
3688
- const tableName = "resumableTasks";
3689
- const tableExists = await this.#dialect.hasTable(this.#db, tableName);
3690
- if (tableExists) {
3691
- return;
3692
- }
3693
- let table = this.#db.schema.createTable(tableName).ifNotExists().addColumn("id", "varchar(255)", (col) => col.primaryKey()).addColumn("task", "text").addColumn("timeout", "bigint").addColumn("retryCount", "integer");
3694
- await table.execute();
3695
- await this.#db.schema.createIndex("index_timeout").on("resumableTasks").column("timeout").execute();
3696
- }
3697
- async close() {
3698
- await this.#db?.destroy();
3699
- this.#db = null;
3700
- }
3701
- async register(task, timeoutInSeconds) {
3702
- if (!this.#db) {
3703
- throw new Error("Connection to database not open. Call `open` before using `register`.");
3704
- }
3705
- const id = await import_dwn_sdk_js3.Cid.computeCid(task);
3706
- const timeout = Date.now() + timeoutInSeconds * 1e3;
3707
- const taskString = JSON.stringify(task);
3708
- const retryCount = 0;
3709
- const taskEntryInDatabase = { id, task: taskString, timeout, retryCount };
3710
- await this.#db.insertInto("resumableTasks").values(taskEntryInDatabase).execute();
3711
- return {
3712
- id,
3713
- task,
3714
- retryCount,
3715
- timeout
3716
- };
3717
- }
3718
- async grab(count) {
3719
- if (!this.#db) {
3720
- throw new Error("Connection to database not open. Call `open` before using `grab`.");
3721
- }
3722
- const now = Date.now();
3723
- const newTimeout = now + _ResumableTaskStoreSql.taskTimeoutInSeconds * 1e3;
3724
- let tasks = [];
3725
- const operation = async (transaction) => {
3726
- tasks = await transaction.selectFrom("resumableTasks").selectAll().where("timeout", "<=", now).limit(count).execute();
3727
- if (tasks.length > 0) {
3728
- const ids = tasks.map((task) => task.id);
3729
- await transaction.updateTable("resumableTasks").set({ timeout: newTimeout }).where((eb) => eb("id", "in", ids)).execute();
3730
- }
3731
- };
3732
- await executeWithRetryIfDatabaseIsLocked(this.#db, operation);
3733
- const tasksToReturn = tasks.map((task) => {
3734
- return {
3735
- id: task.id,
3736
- task: JSON.parse(task.task),
3737
- retryCount: task.retryCount,
3738
- timeout: task.timeout
3739
- };
3740
- });
3741
- return tasksToReturn;
3742
- }
3743
- async read(taskId) {
3744
- if (!this.#db) {
3745
- throw new Error("Connection to database not open. Call `open` before using `read`.");
3746
- }
3747
- const task = await this.#db.selectFrom("resumableTasks").selectAll().where("id", "=", taskId).executeTakeFirst();
3748
- if (task !== void 0) {
3749
- if (typeof task.timeout !== "number") {
3750
- task.timeout = parseInt(task.timeout, 10);
3751
- }
3752
- }
3753
- return task;
3754
- }
3755
- async extend(taskId, timeoutInSeconds) {
3756
- if (!this.#db) {
3757
- throw new Error("Connection to database not open. Call `open` before using `extend`.");
3758
- }
3759
- const timeout = Date.now() + timeoutInSeconds * 1e3;
3760
- await this.#db.updateTable("resumableTasks").set({ timeout }).where("id", "=", taskId).execute();
3761
- }
3762
- async delete(taskId) {
3763
- if (!this.#db) {
3764
- throw new Error("Connection to database not open. Call `open` before using `delete`.");
3765
- }
3766
- await this.#db.deleteFrom("resumableTasks").where("id", "=", taskId).execute();
3767
- }
3768
- async clear() {
3769
- if (!this.#db) {
3770
- throw new Error("Connection to database not open. Call `open` before using `clear`.");
3771
- }
3772
- await this.#db.deleteFrom("resumableTasks").execute();
3773
- }
3774
- };
3775
- // Annotate the CommonJS export names for ESM import in node:
3776
- 0 && (module.exports = {
3777
- DataStoreSql,
3778
- EventLogSql,
3779
- MessageStoreSql,
3780
- MysqlDialect,
3781
- PostgresDialect,
3782
- ResumableTaskStoreSql,
3783
- SqliteDialect
3784
- });