@odatano/core 2.0.0-rc.5 → 2.0.0-rc.51

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 (239) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +99 -51
  2. package/@cds-models/CardanoAgentService/index.js +15 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +358 -0
  4. package/@cds-models/CardanoBackendService/index.js +41 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +594 -11
  6. package/@cds-models/CardanoIndexerService/index.js +74 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +417 -57
  8. package/@cds-models/CardanoODataService/index.js +42 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +45 -19
  10. package/@cds-models/CardanoSignService/index.js +4 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +70 -44
  12. package/@cds-models/CardanoTransactionService/index.js +5 -0
  13. package/@cds-models/CardanoWorkerService/index.d.ts +35 -22
  14. package/@cds-models/CardanoWorkerService/index.js +2 -0
  15. package/@cds-models/index.d.ts +114 -4
  16. package/@cds-models/index.js +20 -4
  17. package/@cds-models/odatano/cardano/index.d.ts +451 -32
  18. package/@cds-models/odatano/cardano/index.js +48 -0
  19. package/README.md +103 -167
  20. package/db/schema.cds +2455 -1705
  21. package/db/types.cds +456 -295
  22. package/package.json +41 -53
  23. package/scripts/deploy-schema.mjs +113 -0
  24. package/scripts/migrate-schema.mjs +528 -0
  25. package/scripts/migrate-slot-leader.mjs +96 -0
  26. package/src/index.d.ts +20 -21
  27. package/src/index.js +45 -31
  28. package/src/plugin.js +17 -35
  29. package/srv/blockchain/asset-decimals.d.ts +7 -0
  30. package/srv/blockchain/asset-decimals.js +91 -0
  31. package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -137
  32. package/srv/blockchain/backends/blockfrost-backend.js +125 -215
  33. package/srv/blockchain/backends/call-signal.d.ts +7 -0
  34. package/srv/blockchain/backends/call-signal.js +22 -0
  35. package/srv/blockchain/backends/cardano-backend.d.ts +100 -189
  36. package/srv/blockchain/backends/cardano-backend.js +29 -5
  37. package/srv/blockchain/backends/koios-backend.d.ts +108 -170
  38. package/srv/blockchain/backends/koios-backend.js +488 -482
  39. package/srv/blockchain/backends/odatano-backend.d.ts +55 -0
  40. package/srv/blockchain/backends/odatano-backend.js +211 -0
  41. package/srv/blockchain/backends/ogmios-backend.d.ts +122 -190
  42. package/srv/blockchain/backends/ogmios-backend.js +683 -327
  43. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
  44. package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
  45. package/srv/blockchain/cardano-client.d.ts +71 -241
  46. package/srv/blockchain/cardano-client.js +354 -322
  47. package/srv/blockchain/cardano-indexer.d.ts +295 -283
  48. package/srv/blockchain/cardano-indexer.js +1690 -502
  49. package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
  50. package/srv/blockchain/cardano-tx-builder.js +164 -140
  51. package/srv/blockchain/circuit-breaker.d.ts +2 -13
  52. package/srv/blockchain/circuit-breaker.js +11 -15
  53. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  54. package/srv/blockchain/crawler/account-snapshots.js +173 -0
  55. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +17 -0
  56. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  57. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +46 -0
  58. package/srv/blockchain/crawler/asset-registry-backfill.js +157 -0
  59. package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
  60. package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
  61. package/srv/blockchain/crawler/certificate-backfill.d.ts +56 -0
  62. package/srv/blockchain/crawler/certificate-backfill.js +174 -0
  63. package/srv/blockchain/crawler/crawler.d.ts +125 -81
  64. package/srv/blockchain/crawler/crawler.js +738 -167
  65. package/srv/blockchain/crawler/credential-backfill.d.ts +30 -0
  66. package/srv/blockchain/crawler/credential-backfill.js +101 -0
  67. package/srv/blockchain/crawler/hooks.d.ts +2 -17
  68. package/srv/blockchain/crawler/index.d.ts +1 -8
  69. package/srv/blockchain/crawler/index.js +31 -17
  70. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  71. package/srv/blockchain/crawler/input-asset-copies.js +161 -0
  72. package/srv/blockchain/crawler/key-pages.d.ts +12 -0
  73. package/srv/blockchain/crawler/key-pages.js +48 -0
  74. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +22 -0
  75. package/srv/blockchain/crawler/metadata-position-backfill.js +59 -0
  76. package/srv/blockchain/crawler/output-datum-backfill.d.ts +41 -0
  77. package/srv/blockchain/crawler/output-datum-backfill.js +100 -0
  78. package/srv/blockchain/crawler/sync-state.d.ts +31 -47
  79. package/srv/blockchain/crawler/sync-state.js +135 -128
  80. package/srv/blockchain/crawler/transaction-backfill.d.ts +46 -0
  81. package/srv/blockchain/crawler/transaction-backfill.js +271 -0
  82. package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
  83. package/srv/blockchain/crawler/utxo-set-import.js +399 -0
  84. package/srv/blockchain/crawler/window-plan.d.ts +31 -0
  85. package/srv/blockchain/crawler/window-plan.js +59 -0
  86. package/srv/blockchain/ledger-state.d.ts +62 -0
  87. package/srv/blockchain/ledger-state.js +521 -0
  88. package/srv/blockchain/pending-spends.d.ts +16 -0
  89. package/srv/blockchain/pending-spends.js +81 -0
  90. package/srv/blockchain/pool-metadata.d.ts +15 -0
  91. package/srv/blockchain/pool-metadata.js +132 -0
  92. package/srv/blockchain/request-coalescer.d.ts +2 -16
  93. package/srv/blockchain/request-coalescer.js +2 -16
  94. package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
  95. package/srv/blockchain/signing/cose-verifier.js +146 -70
  96. package/srv/blockchain/signing/external-signer.d.ts +15 -115
  97. package/srv/blockchain/signing/external-signer.js +22 -131
  98. package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
  99. package/srv/blockchain/signing/failed-recheck.js +135 -0
  100. package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
  101. package/srv/blockchain/signing/hsm-signer.js +28 -79
  102. package/srv/blockchain/signing/landing-proof.d.ts +60 -0
  103. package/srv/blockchain/signing/landing-proof.js +224 -0
  104. package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
  105. package/srv/blockchain/signing/signature-verifier.js +71 -87
  106. package/srv/blockchain/signing/submission-finalizer.d.ts +37 -45
  107. package/srv/blockchain/signing/submission-finalizer.js +280 -86
  108. package/srv/blockchain/stored-chain.d.ts +19 -0
  109. package/srv/blockchain/stored-chain.js +258 -0
  110. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
  111. package/srv/blockchain/transaction-building/buildooor-tx.js +663 -421
  112. package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
  113. package/srv/blockchain/transaction-presence.d.ts +12 -0
  114. package/srv/blockchain/transaction-presence.js +29 -0
  115. package/srv/blockchain/transaction-rows.d.ts +12 -0
  116. package/srv/blockchain/transaction-rows.js +44 -0
  117. package/srv/blockchain/wallet-worker/build-request.d.ts +8 -23
  118. package/srv/blockchain/wallet-worker/build-request.js +40 -353
  119. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +27 -47
  120. package/srv/blockchain/wallet-worker/confirmation-tracker.js +158 -61
  121. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  122. package/srv/blockchain/wallet-worker/index.js +3 -11
  123. package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
  124. package/srv/blockchain/wallet-worker/invalidation.js +128 -0
  125. package/srv/blockchain/wallet-worker/job-store.d.ts +58 -150
  126. package/srv/blockchain/wallet-worker/job-store.js +200 -273
  127. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
  128. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
  129. package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
  130. package/srv/blockchain/wallet-worker/signers.js +4 -12
  131. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +29 -82
  132. package/srv/blockchain/wallet-worker/wallet-worker.js +334 -198
  133. package/srv/cardano-agent-service.cds +122 -84
  134. package/srv/cardano-agent-service.js +12 -9
  135. package/srv/cardano-backend-service.cds +81 -0
  136. package/srv/cardano-backend-service.d.ts +2 -0
  137. package/srv/cardano-backend-service.js +259 -0
  138. package/srv/cardano-indexer-service.cds +393 -18
  139. package/srv/cardano-indexer-service.d.ts +5 -1
  140. package/srv/cardano-indexer-service.js +477 -16
  141. package/srv/cardano-service.cds +426 -269
  142. package/srv/cardano-service.js +640 -217
  143. package/srv/cardano-sign-service.cds +211 -180
  144. package/srv/cardano-sign-service.js +210 -287
  145. package/srv/cardano-tx-service.cds +462 -370
  146. package/srv/cardano-tx-service.js +283 -800
  147. package/srv/cardano-ui.cds +16 -16
  148. package/srv/cardano-worker-service.cds +141 -125
  149. package/srv/cardano-worker-service.js +104 -61
  150. package/srv/cbor/cip68.d.ts +13 -0
  151. package/srv/cbor/cip68.js +56 -0
  152. package/srv/cbor/index.d.ts +3 -1
  153. package/srv/cbor/index.js +9 -1
  154. package/srv/cbor/parse.d.ts +30 -18
  155. package/srv/cbor/parse.js +44 -9
  156. package/srv/cbor/plutus-data-json.d.ts +20 -0
  157. package/srv/cbor/plutus-data-json.js +32 -0
  158. package/srv/config.d.ts +117 -0
  159. package/srv/config.js +419 -0
  160. package/srv/server.d.ts +15 -110
  161. package/srv/server.js +83 -405
  162. package/srv/utils/agent-access.d.ts +11 -0
  163. package/srv/utils/agent-access.js +86 -0
  164. package/srv/utils/agent-grants-config.d.ts +0 -46
  165. package/srv/utils/agent-grants-config.js +17 -85
  166. package/srv/utils/agent-grants.d.ts +106 -122
  167. package/srv/utils/agent-grants.js +538 -237
  168. package/srv/utils/agent-token-auth.d.ts +4 -99
  169. package/srv/utils/agent-token-auth.js +62 -186
  170. package/srv/utils/backend-request-handler.d.ts +3 -17
  171. package/srv/utils/backend-request-handler.js +3 -18
  172. package/srv/utils/build-request.d.ts +52 -0
  173. package/srv/utils/build-request.js +487 -0
  174. package/srv/utils/collections.d.ts +4 -10
  175. package/srv/utils/collections.js +14 -10
  176. package/srv/utils/const.d.ts +32 -75
  177. package/srv/utils/const.js +40 -80
  178. package/srv/utils/crypto.d.ts +3 -12
  179. package/srv/utils/crypto.js +11 -25
  180. package/srv/utils/db-indexes.d.ts +31 -0
  181. package/srv/utils/db-indexes.js +185 -0
  182. package/srv/utils/db-kind.d.ts +23 -0
  183. package/srv/utils/db-kind.js +42 -0
  184. package/srv/utils/db-sanitize.d.ts +20 -0
  185. package/srv/utils/db-sanitize.js +80 -0
  186. package/srv/utils/deep-json.d.ts +6 -0
  187. package/srv/utils/deep-json.js +240 -0
  188. package/srv/utils/detached-run.d.ts +41 -0
  189. package/srv/utils/detached-run.js +101 -0
  190. package/srv/utils/epoch-slots.d.ts +14 -0
  191. package/srv/utils/epoch-slots.js +45 -0
  192. package/srv/utils/error-codes.d.ts +26 -75
  193. package/srv/utils/error-codes.js +27 -72
  194. package/srv/utils/errors.d.ts +55 -187
  195. package/srv/utils/errors.js +161 -235
  196. package/srv/utils/lease.d.ts +20 -0
  197. package/srv/utils/lease.js +62 -0
  198. package/srv/utils/liveness.d.ts +12 -0
  199. package/srv/utils/liveness.js +35 -0
  200. package/srv/utils/mappers.d.ts +111 -223
  201. package/srv/utils/mappers.js +432 -371
  202. package/srv/utils/navigation.d.ts +17 -0
  203. package/srv/utils/navigation.js +52 -0
  204. package/srv/utils/network-context.d.ts +0 -1
  205. package/srv/utils/network-context.js +9 -15
  206. package/srv/utils/paging.d.ts +31 -0
  207. package/srv/utils/paging.js +43 -0
  208. package/srv/utils/pg-inline-json.d.ts +8 -0
  209. package/srv/utils/pg-inline-json.js +58 -0
  210. package/srv/utils/pg-order-nulls.d.ts +14 -0
  211. package/srv/utils/pg-order-nulls.js +54 -0
  212. package/srv/utils/plutus-placeholders.d.ts +16 -22
  213. package/srv/utils/plutus-placeholders.js +62 -33
  214. package/srv/utils/rate-limiter.d.ts +2 -21
  215. package/srv/utils/rate-limiter.js +5 -17
  216. package/srv/utils/readiness.d.ts +12 -0
  217. package/srv/utils/readiness.js +29 -0
  218. package/srv/utils/reference-script.d.ts +19 -0
  219. package/srv/utils/reference-script.js +84 -0
  220. package/srv/utils/resolution.d.ts +13 -0
  221. package/srv/utils/resolution.js +47 -0
  222. package/srv/utils/result-numbers.d.ts +15 -0
  223. package/srv/utils/result-numbers.js +61 -0
  224. package/srv/utils/row-values.d.ts +7 -0
  225. package/srv/utils/row-values.js +27 -0
  226. package/srv/utils/service-events.d.ts +0 -24
  227. package/srv/utils/service-events.js +3 -25
  228. package/srv/utils/signing-helper.d.ts +3 -20
  229. package/srv/utils/signing-helper.js +35 -64
  230. package/srv/utils/tx-build-helper.d.ts +25 -105
  231. package/srv/utils/tx-build-helper.js +108 -156
  232. package/srv/utils/tx-request-parsers.d.ts +82 -33
  233. package/srv/utils/tx-request-parsers.js +401 -49
  234. package/srv/utils/tx-utils.d.ts +3 -27
  235. package/srv/utils/tx-utils.js +32 -50
  236. package/srv/utils/types.d.ts +294 -232
  237. package/srv/utils/types.js +2 -22
  238. package/srv/utils/validators.d.ts +22 -92
  239. package/srv/utils/validators.js +60 -170
@@ -0,0 +1,17 @@
1
+ import type { Request } from '@sap/cds';
2
+ /** The parent of a navigation read such as `Transactions('h')/inputs`: its entity, its keys, the navigation. */
3
+ export interface NavigationRead {
4
+ parent: string;
5
+ keys: Record<string, unknown>;
6
+ nav: string;
7
+ /** Keys of the navigation step, as in `Accounts('s')/Address('a')`; null for a plain collection. */
8
+ navKeys: Record<string, unknown> | null;
9
+ /** Segments of the path: 2 for `Parent(k)/nav`, more when it goes further. */
10
+ depth: number;
11
+ /** Name of every segment after the parent; `steps[0]` is `nav`. */
12
+ steps: string[];
13
+ }
14
+ /** The parent of `req` when it reads through a navigation, else null. */
15
+ export declare function navigationOf(req: Pick<Request, 'query'>): NavigationRead | null;
16
+ export declare function readKey(req: Pick<Request, 'query' | 'data'>, field: string): unknown;
17
+ //# sourceMappingURL=navigation.d.ts.map
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.navigationOf = navigationOf;
4
+ exports.readKey = readKey;
5
+ const nameOf = (segment) => typeof segment === 'string' ? segment : typeof segment?.id === 'string' ? segment.id : null;
6
+ const refOf = (req) => {
7
+ const ref = req.query?.SELECT?.from?.ref;
8
+ return Array.isArray(ref) ? ref : undefined;
9
+ };
10
+ /** The keys of a key segment, `ref = val` joined by `and`; null for any other predicate. */
11
+ function segmentKeys(segment) {
12
+ if (typeof segment !== 'object' || !Array.isArray(segment.where))
13
+ return null;
14
+ const keys = {};
15
+ const where = segment.where;
16
+ for (let i = 0; i < where.length; i += 4) {
17
+ const left = where[i];
18
+ const right = where[i + 2];
19
+ if (where[i + 1] !== '=' || !left?.ref || left.ref.length !== 1 || !right || !('val' in right))
20
+ return null;
21
+ if (i + 3 < where.length && where[i + 3] !== 'and')
22
+ return null;
23
+ keys[String(left.ref[0])] = right.val;
24
+ }
25
+ return keys;
26
+ }
27
+ /** The parent of `req` when it reads through a navigation, else null. */
28
+ function navigationOf(req) {
29
+ const ref = refOf(req);
30
+ if (!ref || ref.length < 2)
31
+ return null;
32
+ const head = ref[0];
33
+ const step = ref[1];
34
+ if (typeof head !== 'object' || typeof head.id !== 'string')
35
+ return null;
36
+ const nav = nameOf(step);
37
+ const keys = segmentKeys(head);
38
+ if (!nav || !keys)
39
+ return null;
40
+ const steps = ref.slice(1).map((s) => nameOf(s) ?? '');
41
+ return { parent: head.id.slice(head.id.lastIndexOf('.') + 1), keys, nav, navKeys: typeof step === 'string' ? null : segmentKeys(step), depth: ref.length, steps };
42
+ }
43
+ // The key `field` of a keyed read. The OData adapter puts it into req.data; a query built with
44
+ // cds.ql in the same process carries it only in its key segment.
45
+ function readKey(req, field) {
46
+ const fromData = req.data?.[field];
47
+ if (fromData !== undefined)
48
+ return fromData;
49
+ const ref = refOf(req);
50
+ return ref?.length === 1 ? segmentKeys(ref[0])?.[field] : undefined;
51
+ }
52
+ //# sourceMappingURL=navigation.js.map
@@ -1,6 +1,5 @@
1
1
  import type { Network } from '../blockchain/cardano-client';
2
2
  /** Record the active network. Pass `null` to clear (shutdown/reset). */
3
3
  export declare function setActiveNetwork(n: Network | null): void;
4
- /** The active network, or `null` if the app context has not been initialized. */
5
4
  export declare function getActiveNetwork(): Network | null;
6
5
  //# sourceMappingURL=network-context.d.ts.map
@@ -2,26 +2,20 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.setActiveNetwork = setActiveNetwork;
4
4
  exports.getActiveNetwork = getActiveNetwork;
5
- /**
6
- * Module-scoped holder for the active Cardano network.
7
- *
8
- * This is a deliberately tiny *leaf* module: it has no runtime dependencies (the
9
- * `Network` import is type-only and erased at compile), so leaf utilities such as
10
- * `validators.ts` can read the configured network WITHOUT importing `server.ts`
11
- * — which would otherwise drag the whole server → indexer graph (and its
12
- * module-load `cds.ql` access) into every consumer.
13
- *
14
- * Set during bootstrap by `initializeAppContext` and cleared on shutdown. Reads
15
- * before bootstrap return `null`; callers treat that as "not ready" rather than
16
- * throwing (e.g. network-aware validators return `false`).
17
- */
5
+ const config_1 = require("../config");
6
+ // Holds the active network so validators can read it without importing server.ts.
18
7
  let active = null;
8
+ const NETWORKS = ['mainnet', 'preview', 'preprod'];
19
9
  /** Record the active network. Pass `null` to clear (shutdown/reset). */
20
10
  function setActiveNetwork(n) {
21
11
  active = n;
22
12
  }
23
- /** The active network, or `null` if the app context has not been initialized. */
13
+ // The network of the running app context, else the configured one. Before the context exists a
14
+ // request is still checked against its network; the missing context then answers 503 by itself.
24
15
  function getActiveNetwork() {
25
- return active;
16
+ if (active)
17
+ return active;
18
+ const configured = (0, config_1.configuredNetworkName)();
19
+ return NETWORKS.includes(configured) ? configured : null;
26
20
  }
27
21
  //# sourceMappingURL=network-context.js.map
@@ -0,0 +1,31 @@
1
+ import type { Request } from '@sap/cds';
2
+ /** A page of a list operation. The CDS model range-checks `limit` and `skip` before the handler runs. */
3
+ export interface Page {
4
+ limit: number;
5
+ skip: number;
6
+ }
7
+ /** The page a request asks for, with the operation's default limit when none is given. */
8
+ export declare function pageOf(data: {
9
+ limit?: number | null;
10
+ skip?: number | null;
11
+ }, defaultLimit: number): Page;
12
+ /** The rows of one page out of a list that is already in its final order. */
13
+ export declare function pageRows<T>(rows: T[], page: Page): T[];
14
+ /** Rows sorted by a string key; a fixed order keeps pages stable across calls. */
15
+ export declare function byKey<T>(rows: T[], keyOf: (row: T) => string): T[];
16
+ /** UTxOs in output-reference order: tx hash, then output index. */
17
+ export declare function byOutRef<T extends {
18
+ hash?: string | null;
19
+ index?: number | null;
20
+ }>(rows: T[]): T[];
21
+ /** Newest first. Koios rows carry only a time, Blockfrost rows only a height; the tx hash breaks ties. */
22
+ export declare function sortAssetHistory<T extends {
23
+ blockHeight?: number | null;
24
+ blockTime?: number | null;
25
+ txHash?: string | null;
26
+ }>(rows: T[]): T[];
27
+ /** Operations over a provider's newest rows reach at most this far. */
28
+ export declare const LATEST_WINDOW = 100;
29
+ /** Page over the newest LATEST_WINDOW rows; a page reaching past them is a 400. */
30
+ export declare function latestWindowPage(req: Request, ctx: string, defaultLimit: number): Page;
31
+ //# sourceMappingURL=paging.d.ts.map
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LATEST_WINDOW = void 0;
4
+ exports.pageOf = pageOf;
5
+ exports.pageRows = pageRows;
6
+ exports.byKey = byKey;
7
+ exports.byOutRef = byOutRef;
8
+ exports.sortAssetHistory = sortAssetHistory;
9
+ exports.latestWindowPage = latestWindowPage;
10
+ const errors_1 = require("./errors");
11
+ /** The page a request asks for, with the operation's default limit when none is given. */
12
+ function pageOf(data, defaultLimit) {
13
+ return { limit: data.limit ?? defaultLimit, skip: data.skip ?? 0 };
14
+ }
15
+ /** The rows of one page out of a list that is already in its final order. */
16
+ function pageRows(rows, page) {
17
+ return rows.slice(page.skip, page.skip + page.limit);
18
+ }
19
+ /** Rows sorted by a string key; a fixed order keeps pages stable across calls. */
20
+ function byKey(rows, keyOf) {
21
+ return [...rows].sort((a, b) => keyOf(a).localeCompare(keyOf(b)));
22
+ }
23
+ /** UTxOs in output-reference order: tx hash, then output index. */
24
+ function byOutRef(rows) {
25
+ return [...rows].sort((a, b) => String(a.hash ?? '').localeCompare(String(b.hash ?? '')) || Number(a.index ?? 0) - Number(b.index ?? 0));
26
+ }
27
+ /** Newest first. Koios rows carry only a time, Blockfrost rows only a height; the tx hash breaks ties. */
28
+ function sortAssetHistory(rows) {
29
+ return [...rows].sort((a, b) => Number(b.blockHeight ?? -1) - Number(a.blockHeight ?? -1)
30
+ || Number(b.blockTime ?? -1) - Number(a.blockTime ?? -1)
31
+ || String(b.txHash ?? '').localeCompare(String(a.txHash ?? '')));
32
+ }
33
+ /** Operations over a provider's newest rows reach at most this far. */
34
+ exports.LATEST_WINDOW = 100;
35
+ /** Page over the newest LATEST_WINDOW rows; a page reaching past them is a 400. */
36
+ function latestWindowPage(req, ctx, defaultLimit) {
37
+ const page = pageOf(req.data, defaultLimit);
38
+ if (page.skip + page.limit > exports.LATEST_WINDOW) {
39
+ (0, errors_1.rejectInvalid)(req, ctx, `skip + limit must not exceed ${exports.LATEST_WINDOW}`, 'skip');
40
+ }
41
+ return page;
42
+ }
43
+ //# sourceMappingURL=paging.js.map
@@ -0,0 +1,8 @@
1
+ import { Readable } from 'stream';
2
+ /** A JSON row stream the CAP renderer built from an array (it keeps the array as `_raw`). */
3
+ export declare function isInlineRowStream(v: unknown): v is Readable & {
4
+ _raw: unknown[];
5
+ };
6
+ /** Wraps the driver's `_prepareStreams` once; returns false when the driver or the hook is missing. */
7
+ export declare function installPostgresInlineJson(): boolean;
8
+ //# sourceMappingURL=pg-inline-json.d.ts.map
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.isInlineRowStream = isInlineRowStream;
7
+ exports.installPostgresInlineJson = installPostgresInlineJson;
8
+ // Sends bulk INSERT and UPSERT rows on PostgreSQL as one text parameter. The driver default
9
+ // streams them through a temp table, which costs three round trips per write.
10
+ // Streams a caller passes in keep the driver's path.
11
+ const cds_1 = __importDefault(require("@sap/cds"));
12
+ const db_kind_1 = require("./db-kind");
13
+ const stream_1 = require("stream");
14
+ const logger = cds_1.default.log('PgInlineJson');
15
+ const INSTALLED = Symbol.for('odatano.pgInlineJson');
16
+ /** A JSON row stream the CAP renderer built from an array (it keeps the array as `_raw`). */
17
+ function isInlineRowStream(v) {
18
+ return v instanceof stream_1.Readable && Array.isArray(v._raw);
19
+ }
20
+ async function drain(stream) {
21
+ const parts = [];
22
+ for await (const part of stream)
23
+ parts.push(Buffer.isBuffer(part) ? part : Buffer.from(String(part)));
24
+ return Buffer.concat(parts).toString('utf8');
25
+ }
26
+ /** Wraps the driver's `_prepareStreams` once; returns false when the driver or the hook is missing. */
27
+ function installPostgresInlineJson() {
28
+ let PostgresService;
29
+ try {
30
+ PostgresService = require('@cap-js/postgres/lib/PostgresService');
31
+ }
32
+ catch (err) {
33
+ if ((0, db_kind_1.configuredDbKind)() === 'postgres')
34
+ logger.warn(`@cap-js/postgres/lib/PostgresService not loadable, bulk writes keep the COPY buffer: ${String(err?.message ?? err)}`);
35
+ return false;
36
+ }
37
+ const proto = PostgresService?.prototype;
38
+ const orig = proto?._prepareStreams;
39
+ if (!proto || typeof orig !== 'function') {
40
+ logger.warn('@cap-js/postgres has no _prepareStreams hook; bulk writes keep the COPY buffer');
41
+ return false;
42
+ }
43
+ if (proto[INSTALLED])
44
+ return true;
45
+ proto._prepareStreams = function (query, values) {
46
+ if (!Array.isArray(values) || !values.some(isInlineRowStream))
47
+ return orig.call(this, query, values);
48
+ return (async () => {
49
+ const inlined = await Promise.all(values.map(v => (isInlineRowStream(v) ? drain(v) : v)));
50
+ return orig.call(this, query, inlined);
51
+ })();
52
+ };
53
+ proto[INSTALLED] = true;
54
+ if ((0, db_kind_1.configuredDbKind)() === 'postgres')
55
+ logger.info('Bulk writes on Postgres: row lists sent inline, no COPY buffer');
56
+ return true;
57
+ }
58
+ //# sourceMappingURL=pg-inline-json.js.map
@@ -0,0 +1,14 @@
1
+ interface OrderTerm {
2
+ nulls?: string;
3
+ element?: {
4
+ key?: boolean;
5
+ notNull?: boolean;
6
+ '@cds.valid.from'?: boolean;
7
+ };
8
+ }
9
+ /** Strips the null placement from the rendered terms whose column cannot be NULL. */
10
+ export declare function stripNullsForNotNull(orderBy: OrderTerm[], rendered: string[]): string[];
11
+ /** Wraps the driver's `_orderBy` once; returns false when the driver or the hook is missing. */
12
+ export declare function installPostgresOrderNulls(): boolean;
13
+ export {};
14
+ //# sourceMappingURL=pg-order-nulls.d.ts.map
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.stripNullsForNotNull = stripNullsForNotNull;
7
+ exports.installPostgresOrderNulls = installPostgresOrderNulls;
8
+ // Drops the NULLS clause from ORDER BY on PostgreSQL for columns that cannot be NULL.
9
+ // The driver's NULLS placement is the opposite of the btree index, so `$top` would sort the whole table.
10
+ const cds_1 = __importDefault(require("@sap/cds"));
11
+ const db_kind_1 = require("./db-kind");
12
+ const logger = cds_1.default.log('PgOrderNulls');
13
+ const INSTALLED = Symbol.for('odatano.pgOrderNulls');
14
+ /** Strips the null placement from the rendered terms whose column cannot be NULL. */
15
+ function stripNullsForNotNull(orderBy, rendered) {
16
+ return rendered.map((sql, i) => {
17
+ const c = orderBy[i];
18
+ if (!c || c.nulls)
19
+ return sql;
20
+ const el = c.element;
21
+ if (el && (el.key === true || el.notNull === true || el['@cds.valid.from'] === true))
22
+ return sql.replace(/ NULLS (FIRST|LAST)$/, '');
23
+ return sql;
24
+ });
25
+ }
26
+ /** Wraps the driver's `_orderBy` once; returns false when the driver or the hook is missing. */
27
+ function installPostgresOrderNulls() {
28
+ let PostgresService;
29
+ try {
30
+ PostgresService = require('@cap-js/postgres/lib/PostgresService');
31
+ }
32
+ catch (err) {
33
+ // No loadable Postgres driver: silent unless the database is Postgres.
34
+ if ((0, db_kind_1.configuredDbKind)() === 'postgres')
35
+ logger.warn(`@cap-js/postgres/lib/PostgresService not loadable, ORDER BY keeps the NULLS clause: ${String(err?.message ?? err)}`);
36
+ return false;
37
+ }
38
+ const proto = PostgresService.CQN2SQL?.prototype;
39
+ const orig = proto?._orderBy;
40
+ if (!proto || typeof orig !== 'function') {
41
+ logger.warn('@cap-js/postgres has no _orderBy hook; ORDER BY keeps the NULLS clause (indexes will not serve ordered reads)');
42
+ return false;
43
+ }
44
+ if (proto[INSTALLED])
45
+ return true;
46
+ proto._orderBy = function (orderBy, ...rest) {
47
+ return stripNullsForNotNull(orderBy, orig.call(this, orderBy, ...rest));
48
+ };
49
+ proto[INSTALLED] = true;
50
+ if ((0, db_kind_1.configuredDbKind)() === 'postgres')
51
+ logger.info('ORDER BY on Postgres: NULLS clause dropped for key and NOT NULL columns');
52
+ return true;
53
+ }
54
+ //# sourceMappingURL=pg-order-nulls.js.map
@@ -1,35 +1,29 @@
1
1
  import type { JSONValue } from './types';
2
- /**
3
- * PlutusData-JSON input-index placeholder.
4
- * Matches the full string form `__INPUT_IDX:<64-hex txHash>#<outputIndex>__`.
5
- * The placeholder must be the entire `int` field value — partial matches are ignored.
6
- */
7
2
  export declare const INPUT_IDX_REGEX: RegExp;
3
+ /** Reference-input index placeholder `__REF_IDX:<64-hex txHash>#<outputIndex>__`, same rules as INPUT_IDX_REGEX. */
4
+ export declare const REF_IDX_REGEX: RegExp;
5
+ /** Withdrawal index placeholder `__WDRL_IDX:<56-hex credential hash>__`, same rules as INPUT_IDX_REGEX. */
6
+ export declare const WDRL_IDX_REGEX: RegExp;
8
7
  /** Minimal UTxO reference shape used by the placeholder resolver. */
9
8
  export interface InputRef {
10
9
  txHash: string;
11
10
  outputIndex: number;
12
11
  }
12
+ /** Credential of a reward account, as the ledger orders withdrawals. */
13
+ export interface WithdrawalCredential {
14
+ credentialHash: string;
15
+ isScript: boolean;
16
+ }
13
17
  export interface ResolveContext {
14
- /** Inputs in their final, post-sort order — index of `ref` in this array == resolved placeholder value. */
18
+ /** Inputs in their final, post-sort order; the array index is the resolved placeholder value. */
15
19
  sortedInputs: InputRef[];
20
+ /** All reference inputs in ledger order; absent where the build does not support `__REF_IDX__`. */
21
+ sortedReferenceInputs?: InputRef[];
22
+ /** Withdrawal credential hashes in ledger order; absent where the build does not support `__WDRL_IDX__`. */
23
+ sortedWithdrawals?: string[];
16
24
  }
17
- /**
18
- * Replicates Buildooor's input sort: lexicographic on the txHash bytes, tie-break by outputIndex asc.
19
- * This mirrors the Cardano ledger CBOR-set ordering used by Buildooor.
20
- * Verified against node_modules/@harmoniclabs/buildooor/dist/TxBuilder/TxBuilder.js:772.
21
- */
22
25
  export declare function sortInputsLikeBuildooor<T extends InputRef>(refs: T[]): T[];
23
- /**
24
- * Walk a PlutusData JSON tree and replace any `{int: "__INPUT_IDX:<hash>#<idx>__"}` leaves
25
- * with `{int: <resolvedIndex>}` according to the sorted input order in `ctx`.
26
- *
27
- * Placeholders are only recognised inside an `int` field. Strings elsewhere (e.g. `bytes`)
28
- * are left untouched — hex payloads may legitimately contain `__` sequences.
29
- *
30
- * Throws TransactionValidationError if a placeholder references a UTxO ref that is not present
31
- * in `ctx.sortedInputs`. The exact placeholder string is included in the message so consumers
32
- * can diagnose missing forceInputs / script UTxOs.
33
- */
26
+ /** Ledger order of withdrawals: script credentials before key credentials, then hash bytes. */
27
+ export declare function sortWithdrawalsLikeLedger<T extends WithdrawalCredential>(entries: T[]): T[];
34
28
  export declare function resolveIndexPlaceholders(node: JSONValue, ctx: ResolveContext): JSONValue;
35
29
  //# sourceMappingURL=plutus-placeholders.d.ts.map
@@ -1,23 +1,20 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.INPUT_IDX_REGEX = void 0;
3
+ exports.WDRL_IDX_REGEX = exports.REF_IDX_REGEX = exports.INPUT_IDX_REGEX = void 0;
4
4
  exports.sortInputsLikeBuildooor = sortInputsLikeBuildooor;
5
+ exports.sortWithdrawalsLikeLedger = sortWithdrawalsLikeLedger;
5
6
  exports.resolveIndexPlaceholders = resolveIndexPlaceholders;
6
7
  const errors_1 = require("./errors");
7
- /**
8
- * PlutusData-JSON input-index placeholder.
9
- * Matches the full string form `__INPUT_IDX:<64-hex txHash>#<outputIndex>__`.
10
- * The placeholder must be the entire `int` field value — partial matches are ignored.
11
- */
12
- // case-insensitive: tx hashes are conventionally lowercase, but accept either
13
- // case and normalize the captured hash to lowercase at the use site
8
+ // Input-index placeholder; must be the entire `int` field value.
9
+ // The hash is case-insensitive and lowercased at the use site.
14
10
  exports.INPUT_IDX_REGEX = /^__INPUT_IDX:([0-9a-fA-F]{64})#(\d+)__$/;
11
+ /** Reference-input index placeholder `__REF_IDX:<64-hex txHash>#<outputIndex>__`, same rules as INPUT_IDX_REGEX. */
12
+ exports.REF_IDX_REGEX = /^__REF_IDX:([0-9a-fA-F]{64})#(\d+)__$/;
13
+ /** Withdrawal index placeholder `__WDRL_IDX:<56-hex credential hash>__`, same rules as INPUT_IDX_REGEX. */
14
+ exports.WDRL_IDX_REGEX = /^__WDRL_IDX:([0-9a-fA-F]{56})__$/;
15
15
  const MAX_WALK_DEPTH = 64;
16
- /**
17
- * Replicates Buildooor's input sort: lexicographic on the txHash bytes, tie-break by outputIndex asc.
18
- * This mirrors the Cardano ledger CBOR-set ordering used by Buildooor.
19
- * Verified against node_modules/@harmoniclabs/buildooor/dist/TxBuilder/TxBuilder.js:772.
20
- */
16
+ // Ledger set order as Buildooor sorts it: txHash bytes, then outputIndex.
17
+ // The ledger orders reference inputs the same way.
21
18
  function sortInputsLikeBuildooor(refs) {
22
19
  const copy = refs.slice();
23
20
  copy.sort((a, b) => {
@@ -30,20 +27,59 @@ function sortInputsLikeBuildooor(refs) {
30
27
  });
31
28
  return copy;
32
29
  }
33
- /**
34
- * Walk a PlutusData JSON tree and replace any `{int: "__INPUT_IDX:<hash>#<idx>__"}` leaves
35
- * with `{int: <resolvedIndex>}` according to the sorted input order in `ctx`.
36
- *
37
- * Placeholders are only recognised inside an `int` field. Strings elsewhere (e.g. `bytes`)
38
- * are left untouched — hex payloads may legitimately contain `__` sequences.
39
- *
40
- * Throws TransactionValidationError if a placeholder references a UTxO ref that is not present
41
- * in `ctx.sortedInputs`. The exact placeholder string is included in the message so consumers
42
- * can diagnose missing forceInputs / script UTxOs.
43
- */
30
+ /** Ledger order of withdrawals: script credentials before key credentials, then hash bytes. */
31
+ function sortWithdrawalsLikeLedger(entries) {
32
+ const copy = entries.slice();
33
+ copy.sort((a, b) => {
34
+ if (a.isScript !== b.isScript)
35
+ return a.isScript ? -1 : 1;
36
+ return Buffer.compare(Buffer.from(a.credentialHash, 'hex'), Buffer.from(b.credentialHash, 'hex'));
37
+ });
38
+ return copy;
39
+ }
40
+ // Replaces INPUT_IDX, REF_IDX and WDRL_IDX placeholders with the position in the matching list.
41
+ // Only `int` fields are inspected, since `bytes` may contain `__`. An unknown ref throws.
44
42
  function resolveIndexPlaceholders(node, ctx) {
45
43
  return walk(node, ctx, 0);
46
44
  }
45
+ function positionOf(value, ctx) {
46
+ const input = exports.INPUT_IDX_REGEX.exec(value);
47
+ if (input) {
48
+ const txHash = input[1].toLowerCase(); // input refs are validated lowercase
49
+ const outputIndex = Number(input[2]);
50
+ const pos = ctx.sortedInputs.findIndex(ref => ref.txHash === txHash && ref.outputIndex === outputIndex);
51
+ if (pos === -1) {
52
+ throw new errors_1.TransactionValidationError(`Placeholder "${value}" references input ${txHash}#${outputIndex} that is not in the final transaction input set`);
53
+ }
54
+ return pos;
55
+ }
56
+ const ref = exports.REF_IDX_REGEX.exec(value);
57
+ if (ref) {
58
+ if (!ctx.sortedReferenceInputs) {
59
+ throw new errors_1.TransactionValidationError(`Placeholder "${value}" is supported by BuildPlutusTransaction only`);
60
+ }
61
+ const txHash = ref[1].toLowerCase();
62
+ const outputIndex = Number(ref[2]);
63
+ const pos = ctx.sortedReferenceInputs.findIndex(r => r.txHash === txHash && r.outputIndex === outputIndex);
64
+ if (pos === -1) {
65
+ throw new errors_1.TransactionValidationError(`Placeholder "${value}" references ${txHash}#${outputIndex}, which is not a reference input of the transaction`);
66
+ }
67
+ return pos;
68
+ }
69
+ const wdrl = exports.WDRL_IDX_REGEX.exec(value);
70
+ if (wdrl) {
71
+ if (!ctx.sortedWithdrawals) {
72
+ throw new errors_1.TransactionValidationError(`Placeholder "${value}" is supported by BuildPlutusTransaction only`);
73
+ }
74
+ const credentialHash = wdrl[1].toLowerCase();
75
+ const pos = ctx.sortedWithdrawals.indexOf(credentialHash);
76
+ if (pos === -1) {
77
+ throw new errors_1.TransactionValidationError(`Placeholder "${value}" references credential ${credentialHash}, which has no withdrawal in the transaction`);
78
+ }
79
+ return pos;
80
+ }
81
+ return undefined;
82
+ }
47
83
  function walk(node, ctx, depth) {
48
84
  if (depth > MAX_WALK_DEPTH) {
49
85
  throw new errors_1.TransactionValidationError(`PlutusData placeholder walker exceeded max depth ${MAX_WALK_DEPTH}`);
@@ -56,15 +92,8 @@ function walk(node, ctx, depth) {
56
92
  const out = {};
57
93
  for (const [key, value] of Object.entries(node)) {
58
94
  if (key === 'int' && typeof value === 'string') {
59
- const match = exports.INPUT_IDX_REGEX.exec(value);
60
- if (match) {
61
- const [, rawTxHash, idxStr] = match;
62
- const txHash = rawTxHash.toLowerCase(); // normalize to match validated lowercase input refs
63
- const outputIndex = Number(idxStr);
64
- const pos = ctx.sortedInputs.findIndex(ref => ref.txHash === txHash && ref.outputIndex === outputIndex);
65
- if (pos === -1) {
66
- throw new errors_1.TransactionValidationError(`Placeholder "${value}" references input ${txHash}#${outputIndex} that is not in the final transaction input set`);
67
- }
95
+ const pos = positionOf(value, ctx);
96
+ if (pos !== undefined) {
68
97
  out[key] = pos;
69
98
  continue;
70
99
  }
@@ -1,8 +1,4 @@
1
- /**
2
- * In-memory sliding-window rate limiter, ported from NIGHTGATE
3
- * (srv/utils/rate-limiter.ts). Used for grant administration and for failed
4
- * agent-token attempts; nothing here touches the database.
5
- */
1
+ /** In-memory sliding-window rate limiter (grant administration, failed agent-token attempts). No DB. */
6
2
  export interface RateLimiterOptions {
7
3
  windowMs: number;
8
4
  maxRequests: number;
@@ -10,24 +6,12 @@ export interface RateLimiterOptions {
10
6
  maxKeys?: number;
11
7
  /** Stale-key sweep interval (default 60 000 ms). */
12
8
  sweepIntervalMs?: number;
13
- /**
14
- * Max distinct keys ONE group may hold (default 64). The group is the key up
15
- * to its first ':' (the principal in `principal:scope` keys). Bounds what a
16
- * single caller can do to the shared table: without it, made-up scopes under
17
- * one principal evicted every other caller's window.
18
- */
19
9
  maxKeysPerGroup?: number;
20
10
  }
21
11
  export interface RateCheckResult {
22
12
  allowed: boolean;
23
13
  retryAfterMs: number;
24
14
  }
25
- /**
26
- * Rate-limit key for a CAP request: the principal (user, else client address)
27
- * plus the scope. Batch parts carry no address and a proxy hides the real one,
28
- * so the address is the last resort only. The principal is the limiter's GROUP
29
- * (see maxKeysPerGroup), hence no ':' in it.
30
- */
31
15
  export declare function principalRateKey(req: unknown, scope: string): string;
32
16
  export declare class RateLimiter {
33
17
  private readonly windowMs;
@@ -43,10 +27,7 @@ export declare class RateLimiter {
43
27
  peek(key: string): RateCheckResult;
44
28
  /** Forget every key (tests). */
45
29
  reset(): void;
46
- /**
47
- * Consume `count` slots atomically: either ALL fit into the window and are
48
- * recorded, or NONE are (a rejected caller has consumed nothing).
49
- */
30
+ /** Consume `count` slots atomically: all fit and are recorded, or none are. */
50
31
  checkMany(key: string, count: number): RateCheckResult;
51
32
  private dropKey;
52
33
  /** Remove keys with no hits within the current window. */
@@ -1,9 +1,5 @@
1
1
  "use strict";
2
- /**
3
- * In-memory sliding-window rate limiter, ported from NIGHTGATE
4
- * (srv/utils/rate-limiter.ts). Used for grant administration and for failed
5
- * agent-token attempts; nothing here touches the database.
6
- */
2
+ /** In-memory sliding-window rate limiter (grant administration, failed agent-token attempts). No DB. */
7
3
  Object.defineProperty(exports, "__esModule", { value: true });
8
4
  exports.RateLimiter = void 0;
9
5
  exports.principalRateKey = principalRateKey;
@@ -12,12 +8,8 @@ function groupOf(key) {
12
8
  const i = key.indexOf(':');
13
9
  return i < 0 ? key : key.slice(0, i);
14
10
  }
15
- /**
16
- * Rate-limit key for a CAP request: the principal (user, else client address)
17
- * plus the scope. Batch parts carry no address and a proxy hides the real one,
18
- * so the address is the last resort only. The principal is the limiter's GROUP
19
- * (see maxKeysPerGroup), hence no ':' in it.
20
- */
11
+ // Key `principal:scope` for a CAP request. The principal is the user, else the client address.
12
+ // Colons in an IPv6 address are replaced, because the text before the first ':' is the group.
21
13
  function principalRateKey(req, scope) {
22
14
  const r = req;
23
15
  const user = r?.user?.id;
@@ -61,10 +53,7 @@ class RateLimiter {
61
53
  this.hits.clear();
62
54
  this.groupCounts.clear();
63
55
  }
64
- /**
65
- * Consume `count` slots atomically: either ALL fit into the window and are
66
- * recorded, or NONE are (a rejected caller has consumed nothing).
67
- */
56
+ /** Consume `count` slots atomically: all fit and are recorded, or none are. */
68
57
  checkMany(key, count) {
69
58
  if (count <= 0)
70
59
  return { allowed: true, retryAfterMs: 0 };
@@ -75,8 +64,7 @@ class RateLimiter {
75
64
  if ((this.groupCounts.get(group) ?? 0) >= this.maxKeysPerGroup) {
76
65
  return { allowed: false, retryAfterMs: this.windowMs };
77
66
  }
78
- // At capacity a NEW key evicts the least recently used one (the map is
79
- // insertion ordered and `set` below re-inserts on every hit).
67
+ // At capacity a new key evicts the least recently used one (insertion-ordered map, re-inserted per hit).
80
68
  if (this.hits.size >= this.maxKeys) {
81
69
  const oldest = this.hits.keys().next().value;
82
70
  if (oldest !== undefined)
@@ -0,0 +1,12 @@
1
+ export interface Readiness {
2
+ status: 'ready' | 'not_ready';
3
+ timestamp: string;
4
+ /** The client, the indexer and the transaction builder exist. */
5
+ context: boolean;
6
+ /** The database answers and holds the schema. */
7
+ database: boolean;
8
+ /** The HSM session is connected; null when no HSM is configured. */
9
+ hsm: boolean | null;
10
+ }
11
+ export declare function buildReadiness(parts: Pick<Readiness, 'context' | 'hsm'>, now?: Date): Promise<Readiness>;
12
+ //# sourceMappingURL=readiness.d.ts.map
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ // Readiness body for getReadiness(): whether this instance can serve requests. It names the
3
+ // missing part and nothing else, so an anonymous probe learns no configuration detail.
4
+ var __importDefault = (this && this.__importDefault) || function (mod) {
5
+ return (mod && mod.__esModule) ? mod : { "default": mod };
6
+ };
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.buildReadiness = buildReadiness;
9
+ const cds_1 = __importDefault(require("@sap/cds"));
10
+ const tx_utils_1 = require("./tx-utils");
11
+ const { SELECT } = cds_1.default.ql;
12
+ const PROBE_TIMEOUT_MS = 3000;
13
+ async function databaseAnswers() {
14
+ if (!cds_1.default.db)
15
+ return false;
16
+ try {
17
+ await (0, tx_utils_1.detachedTx)('readiness probe', (db) => db.run(SELECT.one.from('odatano.cardano.CardanoSyncState').columns('ID')), PROBE_TIMEOUT_MS);
18
+ return true;
19
+ }
20
+ catch {
21
+ return false;
22
+ }
23
+ }
24
+ async function buildReadiness(parts, now = new Date()) {
25
+ const database = await databaseAnswers();
26
+ const ready = parts.context && database && parts.hsm !== false;
27
+ return { status: ready ? 'ready' : 'not_ready', timestamp: now.toISOString(), context: parts.context, database, hsm: parts.hsm };
28
+ }
29
+ //# sourceMappingURL=readiness.js.map