@arkiv-network/sdk 0.6.8-dev.1 → 0.6.8-dev.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +52 -16
  2. package/dist/chains/index.d.cts +25 -25
  3. package/dist/chains/index.d.cts.map +1 -1
  4. package/dist/chains/index.d.ts +25 -25
  5. package/dist/consts-AUoL-v42.cjs +18 -0
  6. package/dist/consts-BV4PR-de.js +7 -0
  7. package/dist/consts-BV4PR-de.js.map +1 -0
  8. package/dist/{query-CO6f35AE.d.cts → entity-BSU5-vyY.d.cts} +68 -31
  9. package/dist/entity-BSU5-vyY.d.cts.map +1 -0
  10. package/dist/{query-BhdmAzYg.d.ts → entity-CHiZ2Qu1.d.ts} +68 -31
  11. package/dist/entity-CHiZ2Qu1.d.ts.map +1 -0
  12. package/dist/{queryBuilder-BvoQXa_u.d.ts → index-CzqHiUAo.d.ts} +202 -74
  13. package/dist/index-CzqHiUAo.d.ts.map +1 -0
  14. package/dist/{queryBuilder-zTsKXctT.d.cts → index-gj33r3rd.d.cts} +202 -74
  15. package/dist/index-gj33r3rd.d.cts.map +1 -0
  16. package/dist/index.cjs +63 -28
  17. package/dist/index.d.cts +90 -4
  18. package/dist/index.d.cts.map +1 -1
  19. package/dist/index.d.ts +91 -5
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +58 -21
  22. package/dist/index.js.map +1 -1
  23. package/dist/{payload-Da9gJMG5.d.ts → payload-B2kFJyah.d.ts} +1 -1
  24. package/dist/{payload-Da9gJMG5.d.ts.map → payload-B2kFJyah.d.ts.map} +1 -1
  25. package/dist/payload-Claf2jUO.js +13 -0
  26. package/dist/payload-Claf2jUO.js.map +1 -0
  27. package/dist/{payload-vwU3Rc6P.cjs → payload-DpA5PA-w.cjs} +0 -17
  28. package/dist/query/index.cjs +6 -2
  29. package/dist/query/index.d.cts +3 -3
  30. package/dist/query/index.d.ts +3 -3
  31. package/dist/query/index.js +3 -2
  32. package/dist/query/index.js.map +1 -1
  33. package/dist/{queryBuilder-DM-YO1Y7.cjs → queryBuilder-CTPwve9u.cjs} +229 -70
  34. package/dist/{queryBuilder-DonAg1aq.js → queryBuilder-D-ACo-g_.js} +201 -72
  35. package/dist/queryBuilder-D-ACo-g_.js.map +1 -0
  36. package/dist/types/index.d.cts +1 -1
  37. package/dist/types/index.d.ts +1 -1
  38. package/dist/utils/index.cjs +4 -10
  39. package/dist/utils/index.d.cts +0 -1
  40. package/dist/utils/index.d.cts.map +1 -1
  41. package/dist/utils/index.d.ts +1 -2
  42. package/dist/utils/index.d.ts.map +1 -1
  43. package/dist/utils/index.js +2 -3
  44. package/dist/utils/index.js.map +1 -1
  45. package/package.json +11 -15
  46. package/src/actions/public/buildQuery.ts +4 -0
  47. package/src/actions/wallet/createEntity.ts +12 -2
  48. package/src/actions/wallet/extendEntity.ts +6 -1
  49. package/src/actions/wallet/updateEntity.ts +12 -2
  50. package/src/clients/createPublicClient.test.ts +2 -0
  51. package/src/clients/decorators/arkivPublic.ts +67 -1
  52. package/src/clients/decorators/arkivWallet.ts +18 -0
  53. package/src/errors.ts +18 -0
  54. package/src/index.ts +0 -3
  55. package/src/query/engine.ts +22 -13
  56. package/src/query/index.ts +1 -0
  57. package/src/query/queryBuilder.ts +189 -94
  58. package/src/query/queryResult.ts +13 -7
  59. package/src/query/selectQueryBuilder.test.ts +210 -0
  60. package/src/query/selection.test.ts +120 -0
  61. package/src/query/selection.ts +116 -0
  62. package/src/types/attributes.ts +12 -0
  63. package/src/utils/arkivTransactions.test.ts +62 -0
  64. package/src/utils/arkivTransactions.ts +36 -27
  65. package/src/utils/index.ts +0 -1
  66. package/src/utils/validation.test.ts +60 -0
  67. package/src/utils/validation.ts +32 -0
  68. package/dist/accounts/index.cjs +0 -9
  69. package/dist/accounts/index.d.cts +0 -1
  70. package/dist/accounts/index.d.ts +0 -1
  71. package/dist/accounts/index.js +0 -1
  72. package/dist/payload-DKBYYjeA.js +0 -18
  73. package/dist/payload-DKBYYjeA.js.map +0 -1
  74. package/dist/query-BhdmAzYg.d.ts.map +0 -1
  75. package/dist/query-CO6f35AE.d.cts.map +0 -1
  76. package/dist/queryBuilder-BvoQXa_u.d.ts.map +0 -1
  77. package/dist/queryBuilder-DonAg1aq.js.map +0 -1
  78. package/dist/queryBuilder-zTsKXctT.d.cts.map +0 -1
  79. package/src/accounts/index.ts +0 -1
@@ -1,3 +1,4 @@
1
+ import { n as BLOCK_TIME } from "./consts-BV4PR-de.js";
1
2
  import { bytesToString, hexToNumber, numberToHex, toBytes } from "viem";
2
3
 
3
4
  //#region src/utils/logger.ts
@@ -120,6 +121,18 @@ var EntityMutationError = class extends Error {
120
121
  this.name = "EntityMutationError";
121
122
  }
122
123
  };
124
+ var InvalidExpirationError = class extends Error {
125
+ constructor(expiresIn) {
126
+ super(`Invalid expiresIn: ${String(expiresIn)}. expiresIn must be a positive integer and a multiple of the Arkiv block time (${BLOCK_TIME} seconds), because expiration is measured in whole blocks (1 block = ${BLOCK_TIME} seconds).`);
127
+ this.name = "InvalidExpirationError";
128
+ }
129
+ };
130
+ var InvalidAttributeError = class extends Error {
131
+ constructor(key, value) {
132
+ super(`Invalid numeric value for attribute "${key}": ${String(value)}. Numeric attribute values must be integers. To keep numeric ordering/range queries, scale it to an integer (e.g. Math.round(${String(value)} * 1000), dividing by 1000 on read); otherwise store it as a string (e.g. "${String(value)}").`);
133
+ this.name = "InvalidAttributeError";
134
+ }
135
+ };
123
136
  var NoMoreResultsError = class extends Error {
124
137
  constructor() {
125
138
  super("No more results");
@@ -235,7 +248,7 @@ function processPredicates(predicates) {
235
248
  }).join(" && ");
236
249
  }
237
250
  async function processQuery(client, queryParams) {
238
- const { predicates, limit, cursor, ownedBy, createdBy, orderBy, validAtBlock, withAttributes, withMetadata, withPayload } = queryParams;
251
+ const { predicates, limit, cursor, ownedBy, createdBy, orderBy, validAtBlock, withAttributes, withMetadata, withPayload, includeData } = queryParams;
239
252
  logger$1("Processing query with params %o", {
240
253
  predicates,
241
254
  cursor,
@@ -246,14 +259,15 @@ async function processQuery(client, queryParams) {
246
259
  validAtBlock,
247
260
  withAttributes,
248
261
  withMetadata,
249
- withPayload
262
+ withPayload,
263
+ includeData
250
264
  });
251
265
  let query = processPredicates(predicates);
252
266
  if (ownedBy) query += ` && $owner=${ownedBy}`;
253
267
  if (createdBy) query += ` && $creator=${createdBy}`;
254
268
  query = query.trim();
255
269
  if (query.startsWith("&& ")) query = query.slice(3);
256
- const queryOptions = { includeData: {
270
+ const queryOptions = { includeData: includeData ?? {
257
271
  key: true,
258
272
  attributes: withAttributes ?? false,
259
273
  payload: withPayload ?? false,
@@ -288,6 +302,12 @@ async function processQuery(client, queryParams) {
288
302
  //#endregion
289
303
  //#region src/query/queryResult.ts
290
304
  const logger = getLogger("query:result");
305
+ /**
306
+ * The result of a query. Holds the fetched entities and supports cursor-based pagination.
307
+ *
308
+ * @typeParam TEntity - The shape of each entity, inferred from the query builder
309
+ * (a full {@link Entity}, or a projected object inferred from a `select()` selection).
310
+ */
291
311
  var QueryResult = class {
292
312
  entities;
293
313
  _endOfIteration;
@@ -325,6 +345,53 @@ var QueryResult = class {
325
345
  }
326
346
  };
327
347
 
348
+ //#endregion
349
+ //#region src/query/selection.ts
350
+ /**
351
+ * Converts a {@link SelectArg} into the {@link RpcIncludeData} understood by the query engine.
352
+ * Every field is opt-in — anything not explicitly selected defaults to `false`, including the key.
353
+ * `undefined` or `"*"` selects everything.
354
+ *
355
+ * @param selection - The selection to convert
356
+ * @returns The fully-resolved include-data object for the RPC query
357
+ * @throws If an empty selection object is provided
358
+ *
359
+ * @example
360
+ * selectionToIncludeData() // everything
361
+ * selectionToIncludeData("*") // everything
362
+ * selectionToIncludeData({ key: true }) // only the key
363
+ * selectionToIncludeData({ owner: true }) // only the owner
364
+ */
365
+ function selectionToIncludeData(selection) {
366
+ if (selection === void 0 || selection === "*") return {
367
+ key: true,
368
+ attributes: true,
369
+ payload: true,
370
+ contentType: true,
371
+ expiration: true,
372
+ owner: true,
373
+ creator: true,
374
+ createdAtBlock: true,
375
+ lastModifiedAtBlock: true,
376
+ transactionIndexInBlock: true,
377
+ operationIndexInTransaction: true
378
+ };
379
+ if (!Object.values(selection).some((selected) => selected === true)) throw new Error("select() requires at least one field to be selected. Pass select() or select(\"*\") to select everything.");
380
+ return {
381
+ key: selection.key ?? false,
382
+ attributes: selection.attributes ?? false,
383
+ payload: selection.payload ?? false,
384
+ contentType: selection.contentType ?? false,
385
+ expiration: selection.expiresAtBlock ?? false,
386
+ owner: selection.owner ?? false,
387
+ creator: selection.creator ?? false,
388
+ createdAtBlock: selection.createdAtBlock ?? false,
389
+ lastModifiedAtBlock: selection.lastModifiedAtBlock ?? false,
390
+ transactionIndexInBlock: selection.transactionIndexInBlock ?? false,
391
+ operationIndexInTransaction: selection.operationIndexInTransaction ?? false
392
+ };
393
+ }
394
+
328
395
  //#endregion
329
396
  //#region src/query/queryBuilder.ts
330
397
  /**
@@ -360,20 +427,21 @@ function desc(attributeName, attributeType) {
360
427
  };
361
428
  }
362
429
  /**
363
- * QueryBuilder is a helper class to build queries to the Arkiv DBChains.
364
- * It can be used to fetch entities from the Arkiv DBChains. It follows the Builder pattern allowing chaining of methods.
365
- * @param client - The Arkiv client
366
- * @returns The QueryBuilder instance {@link QueryBuilder}
430
+ * BaseQueryBuilder holds the query-building logic shared by every query builder
431
+ * (filtering, ordering, pagination, execution). It follows the Builder pattern,
432
+ * allowing methods to be chained. Subclasses decide how data selection is expressed
433
+ * by implementing the protected `selectionParams` method.
434
+ *
435
+ * Use {@link SelectQueryBuilder} via `client.select()` to build and execute queries.
436
+ *
437
+ * @typeParam TEntity - The shape of each entity produced by {@link BaseQueryBuilder.fetch}.
367
438
  */
368
- var QueryBuilder = class {
439
+ var BaseQueryBuilder = class {
369
440
  _client;
370
441
  _ownedBy;
371
442
  _createdBy;
372
443
  _orderBy;
373
444
  _validAtBlock;
374
- _withAttributes;
375
- _withMetadata;
376
- _withPayload;
377
445
  _limit;
378
446
  _cursor;
379
447
  _predicates;
@@ -384,10 +452,10 @@ var QueryBuilder = class {
384
452
  /**
385
453
  * Sets the ownedBy filter
386
454
  * @param ownedBy - The address of the owner
387
- * @returns The QueryBuilder instance
455
+ * @returns The query builder instance
388
456
  *
389
457
  * @example
390
- * const builder = new QueryBuilder(client)
458
+ * const builder = client.select()
391
459
  * builder.ownedBy("0x1234567890123456789012345678901234567890")
392
460
  */
393
461
  ownedBy(ownedBy) {
@@ -397,10 +465,10 @@ var QueryBuilder = class {
397
465
  /**
398
466
  * Sets the createdBy filter
399
467
  * @param createdBy - The address of the creator
400
- * @returns The QueryBuilder instance
468
+ * @returns The query builder instance
401
469
  *
402
470
  * @example
403
- * const builder = new QueryBuilder(client)
471
+ * const builder = client.select()
404
472
  * builder.createdBy("0x1234567890123456789012345678901234567890")
405
473
  */
406
474
  createdBy(createdBy) {
@@ -427,51 +495,12 @@ var QueryBuilder = class {
427
495
  return this;
428
496
  }
429
497
  /**
430
- * Sets the withAttributes flag which will return the attributes for the entities if true
431
- * @param withAttributes - The boolean value to set
432
- * @returns The QueryBuilder instance
433
- *
434
- * @example
435
- * const builder = new QueryBuilder(client)
436
- * builder.withAttributes(true)
437
- */
438
- withAttributes(withAttributes = true) {
439
- this._withAttributes = withAttributes;
440
- return this;
441
- }
442
- /**
443
- * Sets the withMetadata flag which will return the metadata (like owner, expiredAt, etc.) for the entities if true
444
- * @param withMetadata - The boolean value to set
445
- * @returns The QueryBuilder instance
446
- *
447
- * @example
448
- * const builder = new QueryBuilder(client)
449
- * builder.withMetadata(true)
450
- */
451
- withMetadata(withMetadata = true) {
452
- this._withMetadata = withMetadata;
453
- return this;
454
- }
455
- /**
456
- * Sets the withPayload flag which will return the payload for the entities if true
457
- * @param withPayload - The boolean value to set
458
- * @returns The QueryBuilder instance
459
- *
460
- * @example
461
- * const builder = new QueryBuilder(client)
462
- * builder.withPayload(true)
463
- */
464
- withPayload(withPayload = true) {
465
- this._withPayload = withPayload;
466
- return this;
467
- }
468
- /**
469
498
  * Sets the limit for the query
470
499
  * @param limit - The number of entities to return
471
- * @returns The QueryBuilder instance
500
+ * @returns The query builder instance
472
501
  *
473
502
  * @example
474
- * const builder = new QueryBuilder(client)
503
+ * const builder = client.select()
475
504
  * builder.limit(10)
476
505
  */
477
506
  limit(limit) {
@@ -481,11 +510,11 @@ var QueryBuilder = class {
481
510
  /**
482
511
  * Sets the cursor for the query - it is advances setting which rather shouldn't be used manually but it is provided from query result if limit is used (pagination).
483
512
  * @param cursor - The cursor to set which tells to RPC Query server where to start or continue the query.
484
- * @returns The QueryBuilder instance
513
+ * @returns The query builder instance
485
514
  *
486
515
  * @example
487
- * const builder = new QueryBuilder(client)
488
- * builder.offset(10)
516
+ * const builder = client.select()
517
+ * builder.cursor("0xABC123")
489
518
  */
490
519
  cursor(cursor) {
491
520
  this._cursor = cursor;
@@ -495,10 +524,10 @@ var QueryBuilder = class {
495
524
  * Sets the validAtBlock for the query which tells at which block height the state we are intested.
496
525
  * If not set, the latest block is used.
497
526
  * @param validAtBlock - The block number to set
498
- * @returns The QueryBuilder instance
527
+ * @returns The query builder instance
499
528
  *
500
529
  * @example
501
- * const builder = new QueryBuilder(client)
530
+ * const builder = client.select()
502
531
  * builder.validAtBlock(10000)
503
532
  */
504
533
  validAtBlock(validAtBlock) {
@@ -509,10 +538,10 @@ var QueryBuilder = class {
509
538
  * Sets the predicates for the query limiting the results. It can be a single predicate or an array of predicates combined with 'and'.
510
539
  * Predicates can be nested using 'or' and 'and' predicates.
511
540
  * @param predicates - The predicates to set
512
- * @returns The QueryBuilder instance
541
+ * @returns The query builder instance
513
542
  *
514
543
  * @example
515
- * const builder = new QueryBuilder(client)
544
+ * const builder = client.select()
516
545
  * builder.where(eq("name", "John"))
517
546
  * builder.where([eq("name", "John"), eq("age", 30)])
518
547
  * builder.where([eq("name", "John"), or([eq("age", 30), eq("age", 31)])])
@@ -527,12 +556,12 @@ var QueryBuilder = class {
527
556
  return this;
528
557
  }
529
558
  /**
530
- * Fetches the entities from the query. Re
559
+ * Fetches the entities from the query.
531
560
  * It will return a QueryResult instance which can be used to fetch the next and previous pages.
532
561
  * @returns The QueryResult instance {@link QueryResult}
533
562
  *
534
563
  * @example
535
- * const builder = new QueryBuilder(client)
564
+ * const builder = client.select()
536
565
  * const result = await builder.where(eq("name", "John")).fetch()
537
566
  * // result = { entities: [Entity, Entity, Entity], next: async () => QueryResult, previous: async () => QueryResult }
538
567
  */
@@ -545,11 +574,9 @@ var QueryBuilder = class {
545
574
  createdBy: this._createdBy,
546
575
  orderBy: this._orderBy,
547
576
  validAtBlock: this._validAtBlock,
548
- withAttributes: this._withAttributes,
549
- withMetadata: this._withMetadata,
550
- withPayload: this._withPayload
577
+ ...this.selectionParams()
551
578
  });
552
- const entities = await Promise.all(queryResult.data.map((entity) => entityFromRpcResult(entity)));
579
+ const entities = await Promise.all(queryResult.data.map((entity) => this.projectEntity(entity)));
553
580
  this.cursor(queryResult.cursor);
554
581
  this.validAtBlock(BigInt(queryResult.blockNumber ?? 0));
555
582
  return new QueryResult(entities, this, this._cursor, this._limit, this._validAtBlock);
@@ -559,7 +586,7 @@ var QueryBuilder = class {
559
586
  * @returns The number of entities
560
587
  *
561
588
  * @example
562
- * const builder = new QueryBuilder(client)
589
+ * const builder = client.select()
563
590
  * const result = await builder.where(eq("name", "John")).count()
564
591
  * // result = 10
565
592
  */
@@ -578,7 +605,109 @@ var QueryBuilder = class {
578
605
  })).data.length ?? 0;
579
606
  }
580
607
  };
608
+ /**
609
+ * QueryBuilder is a helper class to build queries to the Arkiv DBChains.
610
+ * It can be used to fetch entities from the Arkiv DBChains. It follows the Builder pattern allowing chaining of methods.
611
+ *
612
+ * By default the result includes only the entity `key`. Additional data is opt-in through
613
+ * `withAttributes()`, `withMetadata()` and `withPayload()`.
614
+ *
615
+ * @deprecated Use {@link SelectQueryBuilder} via `client.select()` instead. Declaring the
616
+ * selection up front avoids the common mistake of forgetting to opt in to data and getting back
617
+ * entities with only their `key` populated. This class remains for backwards compatibility and
618
+ * will be removed in a future release.
619
+ *
620
+ * @param client - The Arkiv client
621
+ * @returns The QueryBuilder instance {@link QueryBuilder}
622
+ */
623
+ var QueryBuilder = class extends BaseQueryBuilder {
624
+ _withAttributes;
625
+ _withMetadata;
626
+ _withPayload;
627
+ /**
628
+ * Sets the withAttributes flag which will return the attributes for the entities if true
629
+ * @param withAttributes - The boolean value to set
630
+ * @returns The QueryBuilder instance
631
+ *
632
+ * @example
633
+ * const builder = client.buildQuery()
634
+ * builder.withAttributes(true)
635
+ */
636
+ withAttributes(withAttributes = true) {
637
+ this._withAttributes = withAttributes;
638
+ return this;
639
+ }
640
+ /**
641
+ * Sets the withMetadata flag which will return the metadata (like owner, expiredAt, etc.) for the entities if true
642
+ * @param withMetadata - The boolean value to set
643
+ * @returns The QueryBuilder instance
644
+ *
645
+ * @example
646
+ * const builder = client.buildQuery()
647
+ * builder.withMetadata(true)
648
+ */
649
+ withMetadata(withMetadata = true) {
650
+ this._withMetadata = withMetadata;
651
+ return this;
652
+ }
653
+ /**
654
+ * Sets the withPayload flag which will return the payload for the entities if true
655
+ * @param withPayload - The boolean value to set
656
+ * @returns The QueryBuilder instance
657
+ *
658
+ * @example
659
+ * const builder = client.buildQuery()
660
+ * builder.withPayload(true)
661
+ */
662
+ withPayload(withPayload = true) {
663
+ this._withPayload = withPayload;
664
+ return this;
665
+ }
666
+ selectionParams() {
667
+ return {
668
+ withAttributes: this._withAttributes,
669
+ withMetadata: this._withMetadata,
670
+ withPayload: this._withPayload
671
+ };
672
+ }
673
+ projectEntity(rpcEntity) {
674
+ return entityFromRpcResult(rpcEntity);
675
+ }
676
+ };
677
+ /**
678
+ * SelectQueryBuilder is the recommended query builder. It requires the selection to be declared
679
+ * up front, so results always contain exactly the data you asked for — and the type of each
680
+ * returned entity is narrowed to exactly the selected fields.
681
+ *
682
+ * The selection is fixed at construction time and is flat — each field maps to an entity field.
683
+ * Create one via `client.select(...)` rather than constructing it directly, so the result type is
684
+ * inferred from the selection.
685
+ *
686
+ * @typeParam TEntity - The projected entity shape, inferred from the selection by `client.select()`.
687
+ *
688
+ * @example
689
+ * // everything
690
+ * await client.select().where(eq("name", "John")).fetch()
691
+ * await client.select("*").where(eq("name", "John")).fetch()
692
+ * // specific fields
693
+ * await client.select({ owner: true, attributes: true }).fetch()
694
+ * // a single field — result is typed (flat) { owner: Hex }
695
+ * await client.select({ owner: true }).fetch()
696
+ */
697
+ var SelectQueryBuilder = class extends BaseQueryBuilder {
698
+ _includeData;
699
+ constructor(client, selection) {
700
+ super(client);
701
+ this._includeData = selectionToIncludeData(selection);
702
+ }
703
+ selectionParams() {
704
+ return { includeData: this._includeData };
705
+ }
706
+ async projectEntity(rpcEntity) {
707
+ return await entityFromRpcResult(rpcEntity);
708
+ }
709
+ };
581
710
 
582
711
  //#endregion
583
- export { entityFromRpcResult as a, NoEntityFoundError as c, QueryResult as i, NoMoreResultsError as l, asc as n, EntityMutationError as o, desc as r, NoCursorOrLimitError as s, QueryBuilder as t, getLogger as u };
584
- //# sourceMappingURL=queryBuilder-DonAg1aq.js.map
712
+ export { desc as a, entityFromRpcResult as c, InvalidExpirationError as d, NoCursorOrLimitError as f, getLogger as h, asc as i, EntityMutationError as l, NoMoreResultsError as m, QueryBuilder as n, selectionToIncludeData as o, NoEntityFoundError as p, SelectQueryBuilder as r, QueryResult as s, BaseQueryBuilder as t, InvalidAttributeError as u };
713
+ //# sourceMappingURL=queryBuilder-D-ACo-g_.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"queryBuilder-D-ACo-g_.js","names":["enabledNamespaces: Set<string>","disabledNamespaces: Set<string>","logger","logger","predicate","queryOptions: RpcQueryOptions","order"],"sources":["../src/utils/logger.ts","../src/errors.ts","../src/types/entity.ts","../src/utils/entities.ts","../src/query/engine.ts","../src/query/queryResult.ts","../src/query/selection.ts","../src/query/queryBuilder.ts"],"sourcesContent":["const ROOT_NAMESPACE = \"arkiv\"\n\n// Debug logger type - returns a function that can be called to log messages\ntype DebugLogger = (...args: unknown[]) => void\n\n// Get DEBUG environment variable (works in both Node.js and browser)\nfunction getDebugEnv(): string {\n if (typeof process !== \"undefined\") {\n const debugEnv = process?.env?.DEBUG\n if (debugEnv) {\n return debugEnv\n }\n }\n // Browser: check localStorage\n if (typeof globalThis !== \"undefined\" && \"localStorage\" in globalThis) {\n try {\n const storage = (globalThis as { localStorage?: Storage }).localStorage\n return storage?.getItem(\"DEBUG\") || \"\"\n } catch {\n // localStorage might not be available\n }\n }\n return \"\"\n}\n\n// Parse debug patterns and check if a namespace matches\nfunction matchesPattern(namespace: string, pattern: string): boolean {\n // Exact match\n if (pattern === namespace) return true\n\n // Wildcard match: \"arkiv:*\" matches \"arkiv:query\", \"arkiv:rpc\", etc.\n if (pattern.endsWith(\"*\")) {\n const prefix = pattern.slice(0, -1)\n return namespace.startsWith(prefix)\n }\n\n // Negative match: \"-arkiv:query\" excludes \"arkiv:query\"\n if (pattern.startsWith(\"-\")) {\n const excludePattern = pattern.slice(1)\n return !matchesPattern(namespace, excludePattern)\n }\n\n return false\n}\n\n// Check if a namespace is enabled for debugging\nfunction isEnabled(namespace: string): boolean {\n const debugEnv = getDebugEnv()\n if (!debugEnv) return false\n\n // Split by comma/space and check each pattern\n const patterns = debugEnv.split(/[\\s,]+/).filter((p) => p.length > 0)\n\n // If no patterns, nothing is enabled\n if (patterns.length === 0) return false\n\n // Check if any pattern matches (or if explicitly excluded)\n let enabled = false\n for (const pattern of patterns) {\n if (pattern.startsWith(\"-\")) {\n // Exclude pattern - if it matches, disable\n if (matchesPattern(namespace, pattern)) {\n return false\n }\n } else if (matchesPattern(namespace, pattern)) {\n enabled = true\n }\n }\n\n return enabled\n}\n\n// Store enabled namespaces (for programmatic enable/disable)\nconst enabledNamespaces: Set<string> = new Set()\nconst disabledNamespaces: Set<string> = new Set()\n\n// Color palette for namespace coloring (distinct, readable colors)\nconst COLOR_PALETTE = [\n \"#0000FF\", // blue\n \"#008000\", // green\n \"#FF0000\", // red\n \"#FF00FF\", // magenta\n \"#FFA500\", // orange\n \"#800080\", // purple\n \"#00CED1\", // dark turquoise\n \"#FF1493\", // deep pink\n \"#32CD32\", // lime green\n \"#1E90FF\", // dodger blue\n \"#FF4500\", // orange red\n \"#9370DB\", // medium purple\n \"#00FA9A\", // medium spring green\n \"#FFD700\", // gold\n \"#DC143C\", // crimson\n \"#00BFFF\", // deep sky blue\n \"#FF69B4\", // hot pink\n \"#20B2AA\", // light sea green\n \"#DA70D6\", // orchid\n \"#4682B4\", // steel blue\n]\n\n// Detect if we're in Node.js (for ANSI colors) or browser (for CSS colors)\nconst isNode = typeof process !== \"undefined\" && process.versions?.node != null\n\n// ANSI color codes for Node.js (bright, distinct colors)\nconst ANSI_COLORS = [\n \"\\x1b[94m\", // bright blue\n \"\\x1b[92m\", // bright green\n \"\\x1b[91m\", // bright red\n \"\\x1b[95m\", // bright magenta\n \"\\x1b[93m\", // bright yellow\n \"\\x1b[96m\", // bright cyan\n \"\\x1b[35m\", // magenta\n \"\\x1b[36m\", // cyan\n \"\\x1b[32m\", // green\n \"\\x1b[34m\", // blue\n \"\\x1b[33m\", // yellow\n \"\\x1b[31m\", // red\n \"\\x1b[90m\", // bright black (gray)\n \"\\x1b[37m\", // white\n \"\\x1b[1m\", // bold (as a color option)\n]\n\nconst ANSI_RESET = \"\\x1b[0m\"\nconst ANSI_BOLD = \"\\x1b[1m\"\n\n// Cache colors for namespaces (same namespace = same color)\nconst namespaceColors = new Map<string, { css: string; ansi: string }>()\n\n// Generate a consistent color for a namespace based on its hash\nfunction getColorForNamespace(namespace: string): { css: string; ansi: string } {\n // Check cache first\n const cachedColor = namespaceColors.get(namespace)\n if (cachedColor) {\n return cachedColor\n }\n\n // Simple hash function to convert string to number\n let hash = 0\n for (let i = 0; i < namespace.length; i++) {\n const char = namespace.charCodeAt(i)\n hash = (hash << 5) - hash + char\n hash = hash & hash // Convert to 32-bit integer\n }\n\n // Use absolute value and modulo to get index\n const colorIndex = Math.abs(hash) % COLOR_PALETTE.length\n const cssColor = COLOR_PALETTE[colorIndex]\n const ansiColor = ANSI_COLORS[colorIndex % ANSI_COLORS.length]\n\n const color = { css: cssColor, ansi: ansiColor }\n\n // Cache the color\n namespaceColors.set(namespace, color)\n\n return color\n}\n\n// Create a debug logger function\nfunction createDebugLogger(namespace: string): DebugLogger {\n // Get the color for this namespace (consistent across calls)\n const colors = getColorForNamespace(namespace)\n\n return (...args: unknown[]) => {\n // Check if enabled via environment variable or programmatically\n const envEnabled = isEnabled(namespace)\n const progEnabled = enabledNamespaces.has(namespace) && !disabledNamespaces.has(namespace)\n\n if (envEnabled || progEnabled) {\n if (isNode) {\n // Node.js: use ANSI color codes\n const coloredNamespace = `${ANSI_BOLD}${colors.ansi}${namespace}${ANSI_RESET}`\n console.log(coloredNamespace, ...args)\n } else {\n // Browser: use CSS styling with %c\n // The format is: console.log(\"%cstyled%cnormal\", style1, style2, ...args)\n // This colors the namespace, then resets for the rest\n const style1 = `color: ${colors.css}; font-weight: bold`\n const style2 = \"color: inherit; font-weight: normal\"\n // Combine namespace with a space, then log with styles\n console.log(`%c${namespace}%c`, style1, style2, ...args)\n }\n }\n }\n}\n\nexport const getLogger = (scope: string): DebugLogger => {\n const namespace = `${ROOT_NAMESPACE}:${scope}`\n return createDebugLogger(namespace)\n}\n\nexport const enableDebug = (namespaces: string): void => {\n // Parse and add namespaces to enabled set\n const patterns = namespaces.split(/[\\s,]+/).filter((p) => p.length > 0)\n for (const pattern of patterns) {\n if (pattern.startsWith(\"-\")) {\n // Remove from enabled, add to disabled\n const namespace = pattern.slice(1)\n enabledNamespaces.delete(namespace)\n disabledNamespaces.add(namespace)\n } else {\n enabledNamespaces.add(pattern)\n disabledNamespaces.delete(pattern)\n }\n }\n}\n\nexport const disableDebug = (): void => {\n enabledNamespaces.clear()\n disabledNamespaces.clear()\n}\n","import { BLOCK_TIME } from \"./consts\"\n\nexport class EntityMutationError extends Error {\n constructor(message: string) {\n super(message)\n this.name = \"EntityMutationError\"\n }\n}\nexport class InvalidExpirationError extends Error {\n constructor(expiresIn: unknown) {\n super(\n `Invalid expiresIn: ${String(expiresIn)}. expiresIn must be a positive integer and a multiple of the Arkiv block time (${BLOCK_TIME} seconds), because expiration is measured in whole blocks (1 block = ${BLOCK_TIME} seconds).`,\n )\n this.name = \"InvalidExpirationError\"\n }\n}\nexport class InvalidAttributeError extends Error {\n constructor(key: string, value: number) {\n super(\n `Invalid numeric value for attribute \"${key}\": ${String(value)}. Numeric attribute values must be integers. To keep numeric ordering/range queries, scale it to an integer (e.g. Math.round(${String(value)} * 1000), dividing by 1000 on read); otherwise store it as a string (e.g. \"${String(value)}\").`,\n )\n this.name = \"InvalidAttributeError\"\n }\n}\n\nexport class NoMoreResultsError extends Error {\n constructor() {\n super(\"No more results\")\n this.name = \"NoMoreResultsError\"\n }\n}\n\nexport class NoCursorOrLimitError extends Error {\n constructor() {\n super(\"Cursor and limit must be defined to fetch next\")\n this.name = \"NoCursorOrLimitError\"\n }\n}\n\nexport class NoEntityFoundError extends Error {\n constructor() {\n super(\"No entity found\")\n this.name = \"NoEntityFoundError\"\n }\n}\n","import { bytesToString, type Hex } from \"viem\"\nimport type { MimeType } from \"../types\"\nimport type { Attribute } from \"./attributes\"\n\nexport class Entity {\n key: Hex\n contentType: MimeType | undefined\n owner: Hex | undefined\n creator: Hex | undefined\n expiresAtBlock: bigint | undefined\n createdAtBlock: bigint | undefined\n lastModifiedAtBlock: bigint | undefined\n transactionIndexInBlock: bigint | undefined\n operationIndexInTransaction: bigint | undefined\n payload: Uint8Array | undefined\n attributes: Attribute[]\n\n constructor(\n key: Hex,\n contentType: MimeType | undefined = undefined,\n owner: Hex | undefined = undefined,\n creator: Hex | undefined = undefined,\n expiresAtBlock: bigint | undefined = undefined,\n createdAtBlock: bigint | undefined = undefined,\n lastModifiedAtBlock: bigint | undefined = undefined,\n transactionIndexInBlock: bigint | undefined = undefined,\n operationIndexInTransaction: bigint | undefined = undefined,\n payload: Uint8Array | undefined = undefined,\n attributes: Attribute[],\n ) {\n this.key = key\n this.owner = owner\n this.creator = creator\n this.expiresAtBlock = expiresAtBlock\n this.createdAtBlock = createdAtBlock\n this.lastModifiedAtBlock = lastModifiedAtBlock\n this.transactionIndexInBlock = transactionIndexInBlock\n this.operationIndexInTransaction = operationIndexInTransaction\n this.payload = payload\n this.attributes = attributes\n this.contentType = contentType\n }\n\n /**\n * Converts the entity payload from bytes to a string and returns it.\n * Throws an error if the payload is undefined, which may occur if the entity was not queried with the withPayload option.\n * Throws an error if the conversion from bytes to string fails.\n * @returns The entity payload as a string.\n */\n toText(): string {\n if (this.payload === undefined) {\n throw new Error(\n \"Entity has no payload – it was probably queried without withPayload(true) via QueryBuilder\",\n )\n }\n try {\n return bytesToString(this.payload)\n } catch (e) {\n throw new Error(\n `Failed to convert entity payload to text: ${e instanceof Error ? e.message : String(e)}`,\n { cause: e },\n )\n }\n }\n\n /**\n * Parses the entity payload as JSON and returns the resulting object.\n * Throws an error if the payload is undefined, which may occur if the entity was not queried with the withPayload option.\n * Throws an error if the payload is empty or cannot be parsed as JSON.\n * @returns The parsed JSON object from the entity payload.\n */\n toJson(): any {\n const text = this.toText()\n if (!text) {\n throw new Error(\"Entity has empty payload, cannot parse as JSON\")\n }\n try {\n return JSON.parse(text)\n } catch (e) {\n throw new Error(\n `Failed to parse entity payload as JSON: ${e instanceof Error ? e.message : String(e)}`,\n { cause: e },\n )\n }\n }\n}\n","import { toBytes } from \"viem\"\nimport { Entity } from \"../types/entity\"\nimport type { RpcEntity } from \"../types/rpcSchema\"\nimport { getLogger } from \"./logger\"\n\nconst logger = getLogger(\"utils:entities\")\n\nexport async function entityFromRpcResult(rpcEntity: RpcEntity) {\n logger(\"entityFromRpcResult %o\", rpcEntity)\n\n return new Entity(\n rpcEntity.key,\n rpcEntity.contentType,\n rpcEntity.owner,\n rpcEntity.creator,\n rpcEntity.expiresAt !== undefined ? BigInt(rpcEntity.expiresAt) : undefined,\n rpcEntity.createdAtBlock !== undefined ? BigInt(rpcEntity.createdAtBlock) : undefined,\n rpcEntity.lastModifiedAtBlock !== undefined ? BigInt(rpcEntity.lastModifiedAtBlock) : undefined,\n rpcEntity.transactionIndexInBlock !== undefined\n ? BigInt(rpcEntity.transactionIndexInBlock)\n : undefined,\n rpcEntity.operationIndexInTransaction !== undefined\n ? BigInt(rpcEntity.operationIndexInTransaction)\n : undefined,\n rpcEntity.value !== undefined ? toBytes(rpcEntity.value) : undefined,\n [\n ...(rpcEntity.stringAttributes ?? []).map(({ key, value }) => ({\n key,\n value,\n })),\n ...(rpcEntity.numericAttributes ?? []).map(({ key, value }) => ({\n key,\n value: Number(value),\n })),\n ],\n )\n}\n","import type { Hex } from \"viem\"\nimport { hexToNumber, numberToHex } from \"viem\"\nimport type { ArkivClient } from \"../clients/baseClient\"\nimport type { RpcIncludeData, RpcOrderByAttribute, RpcQueryOptions } from \"../types/rpcSchema\"\nimport { getLogger } from \"../utils/logger\"\nimport type { Predicate } from \"./predicate\"\n\nconst logger = getLogger(\"query:engine\")\n\nfunction processPredicates(predicates: Predicate[]): string {\n const processValue = (value: string | number) => {\n if (typeof value === \"string\") {\n return `\"${value}\"`\n }\n return value\n }\n return predicates\n .map((predicate) => {\n switch (predicate.type) {\n case \"eq\":\n return `${predicate.key} = ${processValue(predicate.value)}`\n case \"neq\":\n return `${predicate.key} != ${processValue(predicate.value)}`\n case \"gt\":\n return `${predicate.key} > ${processValue(predicate.value)}`\n case \"gte\":\n return `${predicate.key} >= ${processValue(predicate.value)}`\n case \"lt\":\n return `${predicate.key} < ${processValue(predicate.value)}`\n case \"lte\":\n return `${predicate.key} <= ${processValue(predicate.value)}`\n case \"not\":\n return `!${predicate.key}`\n case \"or\":\n return `(${predicate.predicates.map((predicate) => processPredicates([predicate])).join(\" || \")})`\n case \"and\":\n return `(${predicate.predicates.map((predicate) => processPredicates([predicate])).join(\" && \")})`\n default:\n return \"\"\n }\n })\n .join(\" && \")\n}\n\nexport async function processQuery(\n client: ArkivClient,\n queryParams: {\n predicates: Predicate[]\n limit: number | undefined\n cursor: string | undefined\n ownedBy: Hex | undefined\n createdBy: Hex | undefined\n orderBy: RpcOrderByAttribute[] | undefined\n validAtBlock?: bigint | undefined\n withAttributes?: boolean | undefined\n withMetadata?: boolean | undefined\n withPayload?: boolean | undefined\n /**\n * Fully-resolved include-data for fine-grained selection. When provided it takes\n * precedence over the `withAttributes`/`withMetadata`/`withPayload` booleans.\n */\n includeData?: RpcIncludeData | undefined\n },\n) {\n const {\n predicates,\n limit,\n cursor,\n ownedBy,\n createdBy,\n orderBy,\n validAtBlock,\n withAttributes,\n withMetadata,\n withPayload,\n includeData,\n } = queryParams\n\n logger(\"Processing query with params %o\", {\n predicates,\n cursor,\n limit,\n ownedBy,\n createdBy,\n orderBy,\n validAtBlock,\n withAttributes,\n withMetadata,\n withPayload,\n includeData,\n })\n\n let query = processPredicates(predicates)\n if (ownedBy) {\n query += ` && $owner=${ownedBy}`\n }\n if (createdBy) {\n query += ` && $creator=${createdBy}`\n }\n\n // remove leading and trailing spaces and leading &&\n query = query.trim()\n if (query.startsWith(\"&& \")) {\n query = query.slice(3)\n }\n\n const queryOptions: RpcQueryOptions = {\n includeData:\n includeData ??\n ({\n key: true,\n attributes: withAttributes ?? false,\n payload: withPayload ?? false,\n contentType: withMetadata ?? false,\n expiration: withMetadata ?? false,\n owner: withMetadata ?? false,\n creator: withMetadata ?? false,\n createdAtBlock: withMetadata ?? false,\n lastModifiedAtBlock: withMetadata ?? false,\n transactionIndexInBlock: withMetadata ?? false,\n operationIndexInTransaction: withMetadata ?? false,\n } as RpcIncludeData),\n }\n\n if (validAtBlock !== undefined) {\n queryOptions.atBlock = numberToHex(validAtBlock)\n }\n if (limit !== undefined) {\n queryOptions.resultsPerPage = numberToHex(limit)\n }\n if (cursor !== undefined) {\n queryOptions.cursor = cursor\n }\n if (orderBy !== undefined) {\n queryOptions.orderBy = orderBy\n }\n\n logger(\"Built query to send %s %o\", query, {\n includeData: queryOptions.includeData,\n atBlock: queryOptions.atBlock ? hexToNumber(queryOptions.atBlock) : undefined,\n orderBy: queryOptions.orderBy,\n resultsPerPage: queryOptions.resultsPerPage,\n cursor: queryOptions.cursor,\n })\n\n const result = await client.request({\n method: \"arkiv_query\",\n params: [query, queryOptions],\n })\n logger(\"Raw result from query %o\", result)\n\n return result\n}\n","import { NoCursorOrLimitError, NoMoreResultsError } from \"../errors\"\nimport type { Entity } from \"../types/entity\"\nimport { getLogger } from \"../utils/logger\"\nimport type { BaseQueryBuilder } from \"./queryBuilder\"\n\nconst logger = getLogger(\"query:result\")\n\n/**\n * The result of a query. Holds the fetched entities and supports cursor-based pagination.\n *\n * @typeParam TEntity - The shape of each entity, inferred from the query builder\n * (a full {@link Entity}, or a projected object inferred from a `select()` selection).\n */\nexport class QueryResult<TEntity = Entity> {\n entities: TEntity[]\n private _endOfIteration: boolean\n private _cursor: string | undefined\n private _limit: number | undefined\n private _validAtBlock: bigint | undefined\n private _queryBuilder: BaseQueryBuilder<TEntity>\n\n // Public getters for internal state\n get queryBuilder(): BaseQueryBuilder<TEntity> {\n return this._queryBuilder\n }\n\n get cursor(): string | undefined {\n return this._cursor\n }\n\n constructor(\n entities: TEntity[],\n queryBuilder: BaseQueryBuilder<TEntity>,\n cursor: string | undefined,\n limit: number | undefined,\n validAtBlock: bigint | undefined,\n ) {\n this.entities = entities\n this._queryBuilder = queryBuilder\n this._endOfIteration = !limit || entities.length < limit\n this._cursor = cursor\n this._limit = limit\n this._validAtBlock = validAtBlock\n }\n\n async next() {\n if (this._cursor === undefined || this._limit === undefined) {\n throw new NoCursorOrLimitError()\n }\n if (this._endOfIteration) {\n throw new NoMoreResultsError()\n }\n this._queryBuilder.cursor(this._cursor)\n const result = await this._queryBuilder.fetch()\n this.entities = result.entities\n // Update the query builder reference\n this._queryBuilder = result.queryBuilder\n // Check if we've reached the end (no more cursor or we got fewer entities than limit)\n this._endOfIteration = !result.cursor || result.entities.length < this._limit\n // Update the cursor\n this._cursor = result.cursor\n\n // TODO check current block height and if it is not too old\n logger(\"Current block height for next page %s\", this._validAtBlock?.toString() ?? \"unknown\")\n }\n\n hasNextPage() {\n return !this._endOfIteration\n }\n}\n","import type { Entity } from \"../types/entity\"\nimport type { RpcIncludeData } from \"../types/rpcSchema\"\n\n/** The entity fields that can be selected. These match the fields of {@link Entity} one-to-one. */\ntype DataKey =\n | \"key\"\n | \"contentType\"\n | \"owner\"\n | \"creator\"\n | \"expiresAtBlock\"\n | \"createdAtBlock\"\n | \"lastModifiedAtBlock\"\n | \"transactionIndexInBlock\"\n | \"operationIndexInTransaction\"\n | \"attributes\"\n | \"payload\"\n\n/**\n * The parts of an entity that can be selected. Every field is opt-in (including the `key`) and maps\n * directly to a field of the returned {@link Entity} — the selection is flat.\n */\nexport type SelectionFields = { [K in DataKey]?: boolean }\n\n/**\n * Requires at least one property of `T` to be present.\n * `{}` is not assignable, which is how `select({})` is rejected at compile time.\n */\ntype AtLeastOne<T, K extends keyof T = keyof T> = {\n [P in K]: Required<Pick<T, P>> & Partial<Omit<T, P>>\n}[K]\n\n/**\n * A non-empty entity selection — the object form accepted by `select()`. At least one field must be\n * selected.\n */\nexport type EntitySelection = AtLeastOne<SelectionFields>\n\n/** Argument accepted by `select()` — a non-empty {@link EntitySelection}, or `\"*\"` for everything. */\nexport type SelectArg = EntitySelection | \"*\"\n\n/**\n * The result of a selection `S`: an {@link Entity} narrowed to exactly the selected fields (each\n * non-`undefined`). The shape is flat and backwards compatible — e.g. `select({ owner: true })`\n * yields `{ owner: Hex }` accessed as `entity.owner`. Accessing an unselected field is a compile\n * error.\n *\n * The `toText()` / `toJson()` helpers operate on the payload, so they are only present when\n * `payload` was selected — calling them otherwise would always throw.\n */\nexport type ProjectedEntity<S> = {\n readonly [K in keyof S as S[K] extends true ? K : never]: K extends keyof Entity\n ? NonNullable<Entity[K]>\n : never\n} & (S extends { payload: true } ? Pick<Entity, \"toText\" | \"toJson\"> : unknown)\n\n/** A selection of every field, used to type the result of `select()` / `select(\"*\")`. */\ntype AllSelected = { [K in DataKey]: true }\n\n/** The projected entity type when everything is selected — every field, plus the methods. */\nexport type FullEntity = ProjectedEntity<AllSelected>\n\n/**\n * Converts a {@link SelectArg} into the {@link RpcIncludeData} understood by the query engine.\n * Every field is opt-in — anything not explicitly selected defaults to `false`, including the key.\n * `undefined` or `\"*\"` selects everything.\n *\n * @param selection - The selection to convert\n * @returns The fully-resolved include-data object for the RPC query\n * @throws If an empty selection object is provided\n *\n * @example\n * selectionToIncludeData() // everything\n * selectionToIncludeData(\"*\") // everything\n * selectionToIncludeData({ key: true }) // only the key\n * selectionToIncludeData({ owner: true }) // only the owner\n */\nexport function selectionToIncludeData(selection?: SelectArg): RpcIncludeData {\n if (selection === undefined || selection === \"*\") {\n return {\n key: true,\n attributes: true,\n payload: true,\n contentType: true,\n expiration: true,\n owner: true,\n creator: true,\n createdAtBlock: true,\n lastModifiedAtBlock: true,\n transactionIndexInBlock: true,\n operationIndexInTransaction: true,\n }\n }\n\n // At least one field must be opted in. This rejects both `{}` and selections whose fields are\n // all explicitly `false` (e.g. `select({ key: false })`), which the type system permits.\n if (!Object.values(selection).some((selected) => selected === true)) {\n throw new Error(\n 'select() requires at least one field to be selected. Pass select() or select(\"*\") to select everything.',\n )\n }\n\n return {\n key: selection.key ?? false,\n attributes: selection.attributes ?? false,\n payload: selection.payload ?? false,\n contentType: selection.contentType ?? false,\n // The selection uses the entity field name `expiresAtBlock`; the RPC calls it `expiration`.\n expiration: selection.expiresAtBlock ?? false,\n owner: selection.owner ?? false,\n creator: selection.creator ?? false,\n createdAtBlock: selection.createdAtBlock ?? false,\n lastModifiedAtBlock: selection.lastModifiedAtBlock ?? false,\n transactionIndexInBlock: selection.transactionIndexInBlock ?? false,\n operationIndexInTransaction: selection.operationIndexInTransaction ?? false,\n }\n}\n","import type { Hex } from \"viem\"\nimport type { ArkivClient } from \"../clients/baseClient\"\nimport type { Entity } from \"../types/entity\"\nimport type { RpcEntity, RpcIncludeData, RpcOrderByAttribute } from \"../types/rpcSchema\"\nimport { entityFromRpcResult } from \"../utils/entities\"\nimport { processQuery } from \"./engine\"\nimport type { Predicate } from \"./predicate\"\nimport { QueryResult } from \"./queryResult\"\nimport { type SelectArg, selectionToIncludeData } from \"./selection\"\n\nexport type OrderByAttribute = {\n name: string\n type: \"string\" | \"number\"\n order: \"asc\" | \"desc\"\n}\n\n/**\n * Helper function to create an ascending order by attribute\n * @param attributeName - The name of the attribute to order by\n * @param attributeType - The type of the attribute to order by (string or number)\n * @returns Input for orderBy method\n *\n * @example\n * const ascAttribute = asc(\"name\", \"string\")\n */\nexport function asc(attributeName: string, attributeType: \"string\" | \"number\"): OrderByAttribute {\n return {\n name: attributeName,\n type: attributeType,\n order: \"asc\",\n }\n}\n\n/**\n * Helper function to create a descending order by attribute\n * @param attributeName - The name of the attribute to order by\n * @param attributeType - The type of the attribute to order by (string or number)\n * @returns Input for orderBy method\n *\n * @example\n * const descAttribute = desc(\"name\", \"string\")\n */\nexport function desc(attributeName: string, attributeType: \"string\" | \"number\"): OrderByAttribute {\n return {\n name: attributeName,\n type: attributeType,\n order: \"desc\",\n }\n}\n\n/**\n * Data-selection parameters forwarded to the query engine on each fetch.\n * Subclasses of {@link BaseQueryBuilder} decide which parts of an entity are fetched.\n */\ntype SelectionParams = {\n withAttributes?: boolean | undefined\n withMetadata?: boolean | undefined\n withPayload?: boolean | undefined\n includeData?: RpcIncludeData | undefined\n}\n\n/**\n * BaseQueryBuilder holds the query-building logic shared by every query builder\n * (filtering, ordering, pagination, execution). It follows the Builder pattern,\n * allowing methods to be chained. Subclasses decide how data selection is expressed\n * by implementing the protected `selectionParams` method.\n *\n * Use {@link SelectQueryBuilder} via `client.select()` to build and execute queries.\n *\n * @typeParam TEntity - The shape of each entity produced by {@link BaseQueryBuilder.fetch}.\n */\nexport abstract class BaseQueryBuilder<TEntity> {\n protected _client: ArkivClient\n protected _ownedBy: Hex | undefined\n protected _createdBy: Hex | undefined\n protected _orderBy: RpcOrderByAttribute[] | undefined\n protected _validAtBlock: bigint | undefined\n protected _limit: number | undefined\n protected _cursor: string | undefined\n protected _predicates: Predicate[]\n\n constructor(client: ArkivClient) {\n this._client = client\n this._predicates = []\n }\n\n /**\n * Sets the ownedBy filter\n * @param ownedBy - The address of the owner\n * @returns The query builder instance\n *\n * @example\n * const builder = client.select()\n * builder.ownedBy(\"0x1234567890123456789012345678901234567890\")\n */\n ownedBy(ownedBy: Hex): this {\n this._ownedBy = ownedBy\n return this\n }\n\n /**\n * Sets the createdBy filter\n * @param createdBy - The address of the creator\n * @returns The query builder instance\n *\n * @example\n * const builder = client.select()\n * builder.createdBy(\"0x1234567890123456789012345678901234567890\")\n */\n createdBy(createdBy: Hex): this {\n this._createdBy = createdBy\n return this\n }\n\n /**\n * Sets the orderBy for the query.\n * It can be called multiple times to order by multiple attributes.\n * The order of the attributes is important. The first attribute is the primary order by attribute.\n * You can use the helper functions asc() and desc() as input for this method.\n * @param attributeName - The name of the attribute to order by\n * @param attributeType - The type of the attribute to order by (string or number)\n * @param order - The order to set the order by (asc or desc)\n * @returns The query builder instance\n *\n * @example\n * const builder = client.select()\n * builder.orderBy(\"name\", \"string\", \"desc\")\n * builder.orderBy(asc(\"name\", \"string\"))\n * builder.orderBy(desc(\"name\", \"string\"))\n */\n orderBy(attributeName: string, attributeType: \"string\" | \"number\", order?: \"asc\" | \"desc\"): this\n /**\n * Sets the orderBy for the query.\n * This method takes the OrderByAttribute object as an argument and is mainly\n * used to use the helper functions asc() and desc() to create the OrderByAttribute instances.\n * @param orderByAttribute - The OrderByAttribute instance to set\n * @returns The query builder instance\n *\n * @example\n * const builder = client.select()\n * builder.orderBy(asc(\"name\", \"string\"))\n * builder.orderBy(desc(\"name\", \"string\"))\n */\n orderBy(orderByAttribute: OrderByAttribute): this\n orderBy(\n attributeNameOrOrderByAttribute: string | OrderByAttribute,\n attributeType?: \"string\" | \"number\",\n order: \"asc\" | \"desc\" = \"asc\",\n ): this {\n if (!this._orderBy) {\n this._orderBy = []\n }\n\n const pushOrderByAttribute = ({ name, type, order }: OrderByAttribute) => {\n this._orderBy?.push({\n name,\n type: type === \"number\" ? \"numeric\" : type,\n desc: order === \"desc\",\n })\n }\n\n if (typeof attributeNameOrOrderByAttribute === \"string\") {\n if (!attributeType) {\n throw new Error(\"attributeType is required when using positional orderBy arguments\")\n }\n pushOrderByAttribute({\n name: attributeNameOrOrderByAttribute,\n type: attributeType,\n order,\n })\n } else {\n pushOrderByAttribute(attributeNameOrOrderByAttribute)\n }\n\n return this\n }\n\n /**\n * Sets the limit for the query\n * @param limit - The number of entities to return\n * @returns The query builder instance\n *\n * @example\n * const builder = client.select()\n * builder.limit(10)\n */\n limit(limit: number): this {\n this._limit = limit\n return this\n }\n\n /**\n * Sets the cursor for the query - it is advances setting which rather shouldn't be used manually but it is provided from query result if limit is used (pagination).\n * @param cursor - The cursor to set which tells to RPC Query server where to start or continue the query.\n * @returns The query builder instance\n *\n * @example\n * const builder = client.select()\n * builder.cursor(\"0xABC123\")\n */\n cursor(cursor: string): this {\n this._cursor = cursor\n return this\n }\n\n /**\n * Sets the validAtBlock for the query which tells at which block height the state we are intested.\n * If not set, the latest block is used.\n * @param validAtBlock - The block number to set\n * @returns The query builder instance\n *\n * @example\n * const builder = client.select()\n * builder.validAtBlock(10000)\n */\n validAtBlock(validAtBlock: bigint): this {\n this._validAtBlock = validAtBlock\n return this\n }\n\n /**\n * Sets the predicates for the query limiting the results. It can be a single predicate or an array of predicates combined with 'and'.\n * Predicates can be nested using 'or' and 'and' predicates.\n * @param predicates - The predicates to set\n * @returns The query builder instance\n *\n * @example\n * const builder = client.select()\n * builder.where(eq(\"name\", \"John\"))\n * builder.where([eq(\"name\", \"John\"), eq(\"age\", 30)])\n * builder.where([eq(\"name\", \"John\"), or([eq(\"age\", 30), eq(\"age\", 31)])])\n * builder.where([eq(\"name\", \"John\"), and([eq(\"age\", 30), eq(\"age\", 31)])])\n * builder.where([eq(\"name\", \"John\"), or([eq(\"age\", 30), and([eq(\"age\", 31), eq(\"age\", 32)])])])\n * builder.where([eq(\"name\", \"John\"), and([eq(\"age\", 30), or([eq(\"age\", 31), eq(\"age\", 32)])])])\n * builder.where([eq(\"name\", \"John\"), and([eq(\"age\", 30), or([eq(\"age\", 31), and([eq(\"age\", 32), eq(\"age\", 33)])])])])\n */\n where(predicates: Predicate[] | Predicate): this {\n if (Array.isArray(predicates)) {\n this._predicates.push(...predicates)\n } else {\n this._predicates.push(predicates)\n }\n return this\n }\n\n /**\n * Returns the data-selection parameters forwarded to the query engine.\n * Subclasses decide which parts of an entity are fetched.\n */\n protected abstract selectionParams(): SelectionParams\n\n /**\n * Builds a single result entity from a raw RPC entity. Subclasses decide the produced shape\n * (a full {@link Entity}, or a projected object inferred from the selection).\n */\n protected abstract projectEntity(rpcEntity: RpcEntity): TEntity | Promise<TEntity>\n\n /**\n * Fetches the entities from the query.\n * It will return a QueryResult instance which can be used to fetch the next and previous pages.\n * @returns The QueryResult instance {@link QueryResult}\n *\n * @example\n * const builder = client.select()\n * const result = await builder.where(eq(\"name\", \"John\")).fetch()\n * // result = { entities: [Entity, Entity, Entity], next: async () => QueryResult, previous: async () => QueryResult }\n */\n async fetch(): Promise<QueryResult<TEntity>> {\n const queryResult = await processQuery(this._client, {\n predicates: this._predicates,\n limit: this._limit,\n cursor: this._cursor,\n ownedBy: this._ownedBy,\n createdBy: this._createdBy,\n orderBy: this._orderBy,\n validAtBlock: this._validAtBlock,\n ...this.selectionParams(),\n })\n\n const entities = await Promise.all(queryResult.data.map((entity) => this.projectEntity(entity)))\n\n this.cursor(queryResult.cursor)\n this.validAtBlock(BigInt(queryResult.blockNumber ?? 0))\n\n return new QueryResult<TEntity>(entities, this, this._cursor, this._limit, this._validAtBlock)\n }\n\n /**\n * Counts the entities from the query.\n * @returns The number of entities\n *\n * @example\n * const builder = client.select()\n * const result = await builder.where(eq(\"name\", \"John\")).count()\n * // result = 10\n */\n async count() {\n const queryResult = await processQuery(this._client, {\n predicates: this._predicates,\n limit: this._limit,\n cursor: this._cursor,\n ownedBy: this._ownedBy,\n createdBy: this._createdBy,\n orderBy: undefined,\n validAtBlock: this._validAtBlock,\n withAttributes: false,\n withMetadata: false,\n withPayload: false,\n })\n\n return queryResult.data.length ?? 0\n }\n}\n\n/**\n * QueryBuilder is a helper class to build queries to the Arkiv DBChains.\n * It can be used to fetch entities from the Arkiv DBChains. It follows the Builder pattern allowing chaining of methods.\n *\n * By default the result includes only the entity `key`. Additional data is opt-in through\n * `withAttributes()`, `withMetadata()` and `withPayload()`.\n *\n * @deprecated Use {@link SelectQueryBuilder} via `client.select()` instead. Declaring the\n * selection up front avoids the common mistake of forgetting to opt in to data and getting back\n * entities with only their `key` populated. This class remains for backwards compatibility and\n * will be removed in a future release.\n *\n * @param client - The Arkiv client\n * @returns The QueryBuilder instance {@link QueryBuilder}\n */\nexport class QueryBuilder extends BaseQueryBuilder<Entity> {\n private _withAttributes: boolean | undefined\n private _withMetadata: boolean | undefined\n private _withPayload: boolean | undefined\n\n /**\n * Sets the withAttributes flag which will return the attributes for the entities if true\n * @param withAttributes - The boolean value to set\n * @returns The QueryBuilder instance\n *\n * @example\n * const builder = client.buildQuery()\n * builder.withAttributes(true)\n */\n withAttributes(withAttributes: boolean = true): this {\n this._withAttributes = withAttributes\n return this\n }\n\n /**\n * Sets the withMetadata flag which will return the metadata (like owner, expiredAt, etc.) for the entities if true\n * @param withMetadata - The boolean value to set\n * @returns The QueryBuilder instance\n *\n * @example\n * const builder = client.buildQuery()\n * builder.withMetadata(true)\n */\n withMetadata(withMetadata: boolean = true): this {\n this._withMetadata = withMetadata\n return this\n }\n\n /**\n * Sets the withPayload flag which will return the payload for the entities if true\n * @param withPayload - The boolean value to set\n * @returns The QueryBuilder instance\n *\n * @example\n * const builder = client.buildQuery()\n * builder.withPayload(true)\n */\n withPayload(withPayload: boolean = true): this {\n this._withPayload = withPayload\n return this\n }\n\n protected selectionParams(): SelectionParams {\n return {\n withAttributes: this._withAttributes,\n withMetadata: this._withMetadata,\n withPayload: this._withPayload,\n }\n }\n\n protected projectEntity(rpcEntity: RpcEntity): Promise<Entity> {\n return entityFromRpcResult(rpcEntity)\n }\n}\n\n/**\n * SelectQueryBuilder is the recommended query builder. It requires the selection to be declared\n * up front, so results always contain exactly the data you asked for — and the type of each\n * returned entity is narrowed to exactly the selected fields.\n *\n * The selection is fixed at construction time and is flat — each field maps to an entity field.\n * Create one via `client.select(...)` rather than constructing it directly, so the result type is\n * inferred from the selection.\n *\n * @typeParam TEntity - The projected entity shape, inferred from the selection by `client.select()`.\n *\n * @example\n * // everything\n * await client.select().where(eq(\"name\", \"John\")).fetch()\n * await client.select(\"*\").where(eq(\"name\", \"John\")).fetch()\n * // specific fields\n * await client.select({ owner: true, attributes: true }).fetch()\n * // a single field — result is typed (flat) { owner: Hex }\n * await client.select({ owner: true }).fetch()\n */\nexport class SelectQueryBuilder<TEntity> extends BaseQueryBuilder<TEntity> {\n private _includeData: RpcIncludeData\n\n constructor(client: ArkivClient, selection?: SelectArg) {\n super(client)\n this._includeData = selectionToIncludeData(selection)\n }\n\n protected selectionParams(): SelectionParams {\n return { includeData: this._includeData }\n }\n\n protected async projectEntity(rpcEntity: RpcEntity): Promise<TEntity> {\n // The runtime value is a full Entity (with methods); the static type is narrowed to the\n // selected fields via `client.select()`'s inference.\n return (await entityFromRpcResult(rpcEntity)) as unknown as TEntity\n }\n}\n"],"mappings":";;;;AAAA,MAAM,iBAAiB;AAMvB,SAAS,cAAsB;AAC7B,KAAI,OAAO,YAAY,aAAa;EAClC,MAAM,WAAW,SAAS,KAAK;AAC/B,MAAI,SACF,QAAO;;AAIX,KAAI,OAAO,eAAe,eAAe,kBAAkB,WACzD,KAAI;AAEF,SADiB,WAA0C,cAC3C,QAAQ,QAAQ,IAAI;SAC9B;AAIV,QAAO;;AAIT,SAAS,eAAe,WAAmB,SAA0B;AAEnE,KAAI,YAAY,UAAW,QAAO;AAGlC,KAAI,QAAQ,SAAS,IAAI,EAAE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Aa,eAAwB,MAAY;AAC/C,OAAK,gBAAgB;AACrB,SAAO;;;;;;;;;;;CAYT,YAAY,cAAuB,MAAY;AAC7C,OAAK,eAAe;AACpB,SAAO;;CAGT,AAAU,kBAAmC;AAC3C,SAAO;GACL,gBAAgB,KAAK;GACrB,cAAc,KAAK;GACnB,aAAa,KAAK;GACnB;;CAGH,AAAU,cAAc,WAAuC;AAC7D,SAAO,oBAAoB,UAAU;;;;;;;;;;;;;;;;;;;;;;;AAwBzC,IAAa,qBAAb,cAAiD,iBAA0B;CACzE,AAAQ;CAER,YAAY,QAAqB,WAAuB;AACtD,QAAM,OAAO;AACb,OAAK,eAAe,uBAAuB,UAAU;;CAGvD,AAAU,kBAAmC;AAC3C,SAAO,EAAE,aAAa,KAAK,cAAc;;CAG3C,MAAgB,cAAc,WAAwC;AAGpE,SAAQ,MAAM,oBAAoB,UAAU"}
@@ -1,2 +1,2 @@
1
- import { A as RpcIncludeData, C as CreateEntityReturnType, E as GetBlockTimingReturnType, M as RpcQueryOptions, N as MimeType, O as ArkivRpcSchema, S as CreateEntityParameters, T as ChangeOwnershipReturnType, _ as UpdateEntityReturnType, a as Entity, b as DeleteEntityParameters, c as OnEntityDeletedEvent, d as OnEntityOwnerChangedEvent, f as OnEntityUpdatedEvent, g as UpdateEntityParameters, h as MutateEntitiesReturnType, i as QueryReturnType, j as RpcOrderByAttribute, k as RpcEntity, l as OnEntityExpiredEvent, m as MutateEntitiesParameters, n as QueryOptionsIncludeData, o as TxParams, p as Attribute, r as QueryOptionsOrderBy, s as OnEntityCreatedEvent, t as QueryOptions, u as OnEntityExpiresInExtendedEvent, v as ExtendEntityParameters, w as ChangeOwnershipParameters, x as DeleteEntityReturnType, y as ExtendEntityReturnType } from "../query-CO6f35AE.cjs";
1
+ import { A as RpcIncludeData, C as QueryOptionsIncludeData, E as GetBlockTimingReturnType, M as RpcQueryOptions, N as MimeType, O as ArkivRpcSchema, S as QueryOptions, T as QueryReturnType, _ as DeleteEntityReturnType, a as OnEntityExpiredEvent, b as ChangeOwnershipParameters, c as OnEntityUpdatedEvent, d as MutateEntitiesReturnType, f as UpdateEntityParameters, g as DeleteEntityParameters, h as ExtendEntityReturnType, i as OnEntityDeletedEvent, j as RpcOrderByAttribute, k as RpcEntity, l as Attribute, m as ExtendEntityParameters, n as TxParams, o as OnEntityExpiresInExtendedEvent, p as UpdateEntityReturnType, r as OnEntityCreatedEvent, s as OnEntityOwnerChangedEvent, t as Entity, u as MutateEntitiesParameters, v as CreateEntityParameters, w as QueryOptionsOrderBy, x as ChangeOwnershipReturnType, y as CreateEntityReturnType } from "../entity-BSU5-vyY.cjs";
2
2
  export { ArkivRpcSchema, Attribute, ChangeOwnershipParameters, ChangeOwnershipReturnType, CreateEntityParameters, CreateEntityReturnType, DeleteEntityParameters, DeleteEntityReturnType, Entity, ExtendEntityParameters, ExtendEntityReturnType, GetBlockTimingReturnType, MimeType, MutateEntitiesParameters, MutateEntitiesReturnType, OnEntityCreatedEvent, OnEntityDeletedEvent, OnEntityExpiredEvent, OnEntityExpiresInExtendedEvent, OnEntityOwnerChangedEvent, OnEntityUpdatedEvent, QueryOptions, QueryOptionsIncludeData, QueryOptionsOrderBy, QueryReturnType, RpcEntity, RpcIncludeData, RpcOrderByAttribute, RpcQueryOptions, TxParams, UpdateEntityParameters, UpdateEntityReturnType };
@@ -1,2 +1,2 @@
1
- import { A as RpcIncludeData, C as CreateEntityReturnType, E as GetBlockTimingReturnType, M as RpcQueryOptions, N as MimeType, O as ArkivRpcSchema, S as CreateEntityParameters, T as ChangeOwnershipReturnType, _ as UpdateEntityReturnType, a as Entity, b as DeleteEntityParameters, c as OnEntityDeletedEvent, d as OnEntityOwnerChangedEvent, f as OnEntityUpdatedEvent, g as UpdateEntityParameters, h as MutateEntitiesReturnType, i as QueryReturnType, j as RpcOrderByAttribute, k as RpcEntity, l as OnEntityExpiredEvent, m as MutateEntitiesParameters, n as QueryOptionsIncludeData, o as TxParams, p as Attribute, r as QueryOptionsOrderBy, s as OnEntityCreatedEvent, t as QueryOptions, u as OnEntityExpiresInExtendedEvent, v as ExtendEntityParameters, w as ChangeOwnershipParameters, x as DeleteEntityReturnType, y as ExtendEntityReturnType } from "../query-BhdmAzYg.js";
1
+ import { A as RpcIncludeData, C as QueryOptionsIncludeData, E as GetBlockTimingReturnType, M as RpcQueryOptions, N as MimeType, O as ArkivRpcSchema, S as QueryOptions, T as QueryReturnType, _ as DeleteEntityReturnType, a as OnEntityExpiredEvent, b as ChangeOwnershipParameters, c as OnEntityUpdatedEvent, d as MutateEntitiesReturnType, f as UpdateEntityParameters, g as DeleteEntityParameters, h as ExtendEntityReturnType, i as OnEntityDeletedEvent, j as RpcOrderByAttribute, k as RpcEntity, l as Attribute, m as ExtendEntityParameters, n as TxParams, o as OnEntityExpiresInExtendedEvent, p as UpdateEntityReturnType, r as OnEntityCreatedEvent, s as OnEntityOwnerChangedEvent, t as Entity, u as MutateEntitiesParameters, v as CreateEntityParameters, w as QueryOptionsOrderBy, x as ChangeOwnershipReturnType, y as CreateEntityReturnType } from "../entity-CHiZ2Qu1.js";
2
2
  export { ArkivRpcSchema, Attribute, ChangeOwnershipParameters, ChangeOwnershipReturnType, CreateEntityParameters, CreateEntityReturnType, DeleteEntityParameters, DeleteEntityReturnType, Entity, ExtendEntityParameters, ExtendEntityReturnType, GetBlockTimingReturnType, MimeType, MutateEntitiesParameters, MutateEntitiesReturnType, OnEntityCreatedEvent, OnEntityDeletedEvent, OnEntityExpiredEvent, OnEntityExpiresInExtendedEvent, OnEntityOwnerChangedEvent, OnEntityUpdatedEvent, QueryOptions, QueryOptionsIncludeData, QueryOptionsOrderBy, QueryReturnType, RpcEntity, RpcIncludeData, RpcOrderByAttribute, RpcQueryOptions, TxParams, UpdateEntityParameters, UpdateEntityReturnType };
@@ -1,4 +1,5 @@
1
- const require_payload = require('../payload-vwU3Rc6P.cjs');
1
+ const require_consts = require('../consts-AUoL-v42.cjs');
2
+ const require_payload = require('../payload-DpA5PA-w.cjs');
2
3
 
3
4
  //#region src/utils/expirationTime.ts
4
5
  const ExpirationTime = {
@@ -9,18 +10,11 @@ const ExpirationTime = {
9
10
  fromWeeks: (weeks) => weeks * 7 * 24 * 60 * 60,
10
11
  fromMonths: (months) => months * 30 * 24 * 60 * 60,
11
12
  fromYears: (years) => years * 365 * 24 * 60 * 60,
12
- fromBlocks: (blocks) => blocks * require_payload.BLOCK_TIME,
13
+ fromBlocks: (blocks) => blocks * require_consts.BLOCK_TIME,
13
14
  fromDate: (date) => Math.floor(date.getTime() / 1e3) - Math.floor(Date.now() / 1e3)
14
15
  };
15
16
 
16
17
  //#endregion
17
18
  exports.ExpirationTime = ExpirationTime;
18
19
  exports.jsonToPayload = require_payload.jsonToPayload;
19
- exports.stringToPayload = require_payload.stringToPayload;
20
- var viem_utils = require("viem/utils");
21
- Object.keys(viem_utils).forEach(function (k) {
22
- if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
23
- enumerable: true,
24
- get: function () { return viem_utils[k]; }
25
- });
26
- });
20
+ exports.stringToPayload = require_payload.stringToPayload;
@@ -1,5 +1,4 @@
1
1
  import { n as stringToPayload, t as jsonToPayload } from "../payload-CJN8fTvX.cjs";
2
- export * from "viem/utils";
3
2
 
4
3
  //#region src/utils/expirationTime.d.ts
5
4
  declare const ExpirationTime: {
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":[],"sources":["../../src/utils/expirationTime.ts"],"sourcesContent":[],"mappings":";;;;cAEa;;;;;EAAA,SAAA,EAAA,CAAA,KAUZ,EAAA,MAAA,EAAA,GADkB,MAAI;;;;mBAAJ"}
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../../src/utils/expirationTime.ts"],"sourcesContent":[],"mappings":";;;cAEa;;;EAAA,SAAA,EAAA,CAAA,KAUZ,EAAA,MAAA,EAAA,GADkB,MAAI;;;;;;mBAAJ"}
@@ -1,5 +1,4 @@
1
- import { n as stringToPayload, t as jsonToPayload } from "../payload-Da9gJMG5.js";
2
- export * from "viem/utils";
1
+ import { n as stringToPayload, t as jsonToPayload } from "../payload-B2kFJyah.js";
3
2
 
4
3
  //#region src/utils/expirationTime.d.ts
5
4
  declare const ExpirationTime: {
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/utils/expirationTime.ts"],"sourcesContent":[],"mappings":";;;;cAEa;;;;;EAAA,SAAA,EAAA,CAAA,KAUZ,EAAA,MAAA,EAAA,GADkB,MAAI;;;;mBAAJ"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/utils/expirationTime.ts"],"sourcesContent":[],"mappings":";;;cAEa;;;EAAA,SAAA,EAAA,CAAA,KAUZ,EAAA,MAAA,EAAA,GADkB,MAAI;;;;;;mBAAJ"}
@@ -1,6 +1,5 @@
1
- import { i as BLOCK_TIME, n as stringToPayload, t as jsonToPayload } from "../payload-DKBYYjeA.js";
2
-
3
- export * from "viem/utils"
1
+ import { n as BLOCK_TIME } from "../consts-BV4PR-de.js";
2
+ import { n as stringToPayload, t as jsonToPayload } from "../payload-Claf2jUO.js";
4
3
 
5
4
  //#region src/utils/expirationTime.ts
6
5
  const ExpirationTime = {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/utils/expirationTime.ts"],"sourcesContent":["import { BLOCK_TIME } from \"../consts\"\n\nexport const ExpirationTime = {\n fromSeconds: (seconds: number) => seconds,\n fromMinutes: (minutes: number) => minutes * 60,\n fromHours: (hours: number) => hours * 60 * 60,\n fromDays: (days: number) => days * 24 * 60 * 60,\n fromWeeks: (weeks: number) => weeks * 7 * 24 * 60 * 60,\n fromMonths: (months: number) => months * 30 * 24 * 60 * 60,\n fromYears: (years: number) => years * 365 * 24 * 60 * 60,\n fromBlocks: (blocks: number) => blocks * BLOCK_TIME,\n fromDate: (date: Date) => Math.floor(date.getTime() / 1000) - Math.floor(Date.now() / 1000),\n}\n"],"mappings":";;;;;AAEA,MAAa,iBAAiB;CAC5B,cAAc,YAAoB;CAClC,cAAc,YAAoB,UAAU;CAC5C,YAAY,UAAkB,QAAQ,KAAK;CAC3C,WAAW,SAAiB,OAAO,KAAK,KAAK;CAC7C,YAAY,UAAkB,QAAQ,IAAI,KAAK,KAAK;CACpD,aAAa,WAAmB,SAAS,KAAK,KAAK,KAAK;CACxD,YAAY,UAAkB,QAAQ,MAAM,KAAK,KAAK;CACtD,aAAa,WAAmB,SAAS;CACzC,WAAW,SAAe,KAAK,MAAM,KAAK,SAAS,GAAG,IAAK,GAAG,KAAK,MAAM,KAAK,KAAK,GAAG,IAAK;CAC5F"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/utils/expirationTime.ts"],"sourcesContent":["import { BLOCK_TIME } from \"../consts\"\n\nexport const ExpirationTime = {\n fromSeconds: (seconds: number) => seconds,\n fromMinutes: (minutes: number) => minutes * 60,\n fromHours: (hours: number) => hours * 60 * 60,\n fromDays: (days: number) => days * 24 * 60 * 60,\n fromWeeks: (weeks: number) => weeks * 7 * 24 * 60 * 60,\n fromMonths: (months: number) => months * 30 * 24 * 60 * 60,\n fromYears: (years: number) => years * 365 * 24 * 60 * 60,\n fromBlocks: (blocks: number) => blocks * BLOCK_TIME,\n fromDate: (date: Date) => Math.floor(date.getTime() / 1000) - Math.floor(Date.now() / 1000),\n}\n"],"mappings":";;;;AAEA,MAAa,iBAAiB;CAC5B,cAAc,YAAoB;CAClC,cAAc,YAAoB,UAAU;CAC5C,YAAY,UAAkB,QAAQ,KAAK;CAC3C,WAAW,SAAiB,OAAO,KAAK,KAAK;CAC7C,YAAY,UAAkB,QAAQ,IAAI,KAAK,KAAK;CACpD,aAAa,WAAmB,SAAS,KAAK,KAAK,KAAK;CACxD,YAAY,UAAkB,QAAQ,MAAM,KAAK,KAAK;CACtD,aAAa,WAAmB,SAAS;CACzC,WAAW,SAAe,KAAK,MAAM,KAAK,SAAS,GAAG,IAAK,GAAG,KAAK,MAAM,KAAK,KAAK,GAAG,IAAK;CAC5F"}