@adcp/sdk 16.0.0-beta.2 → 16.0.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (248) hide show
  1. package/README.md +54 -0
  2. package/dist/lib/auth/oauth/diagnose.js +3 -11
  3. package/dist/lib/auth/oauth/diagnose.mjs +4 -12
  4. package/dist/lib/auth/oauth/diagnostics.d.mts +2 -1
  5. package/dist/lib/auth/oauth/diagnostics.d.ts +2 -1
  6. package/dist/lib/auth/oauth/diagnostics.js +8 -10
  7. package/dist/lib/auth/oauth/diagnostics.mjs +7 -10
  8. package/dist/lib/core/ConversationTypes.d.mts +8 -3
  9. package/dist/lib/core/ConversationTypes.d.ts +8 -3
  10. package/dist/lib/core/SingleAgentClient.d.mts +5 -3
  11. package/dist/lib/core/SingleAgentClient.d.ts +5 -3
  12. package/dist/lib/core/TaskExecutor.js +5 -1
  13. package/dist/lib/core/TaskExecutor.mjs +5 -1
  14. package/dist/lib/errors/index.d.mts +9 -4
  15. package/dist/lib/errors/index.d.ts +9 -4
  16. package/dist/lib/index.d.mts +3 -3
  17. package/dist/lib/index.d.ts +3 -3
  18. package/dist/lib/index.js +8 -0
  19. package/dist/lib/index.mjs +14 -2
  20. package/dist/lib/negotiation/types.d.mts +20 -39
  21. package/dist/lib/negotiation/types.d.ts +20 -39
  22. package/dist/lib/protocols/index.d.mts +60 -24
  23. package/dist/lib/protocols/index.d.ts +60 -24
  24. package/dist/lib/protocols/index.js +9 -4
  25. package/dist/lib/protocols/index.mjs +3 -0
  26. package/dist/lib/protocols/mcp-modern.js +1 -0
  27. package/dist/lib/protocols/mcp-modern.mjs +2 -1
  28. package/dist/lib/protocols/mcp.js +1 -0
  29. package/dist/lib/protocols/mcp.mjs +2 -1
  30. package/dist/lib/protocols/responseSizeLimit.d.mts +91 -5
  31. package/dist/lib/protocols/responseSizeLimit.d.ts +91 -5
  32. package/dist/lib/protocols/responseSizeLimit.js +195 -31
  33. package/dist/lib/protocols/responseSizeLimit.mjs +192 -31
  34. package/dist/lib/reporting/consumer-runtime.js +2 -1
  35. package/dist/lib/reporting/consumer-runtime.mjs +2 -1
  36. package/dist/lib/reporting/ledger/handler.js +50 -11
  37. package/dist/lib/reporting/ledger/handler.mjs +50 -12
  38. package/dist/lib/reporting/ledger/index.d.mts +17 -14
  39. package/dist/lib/reporting/ledger/index.d.ts +17 -14
  40. package/dist/lib/reporting/ledger/index.js +32 -20
  41. package/dist/lib/reporting/ledger/index.mjs +21 -10
  42. package/dist/lib/reporting/ledger/offering-validation.d.mts +9 -0
  43. package/dist/lib/reporting/ledger/offering-validation.d.ts +9 -0
  44. package/dist/lib/reporting/{gcs/bucket-policy.js → ledger/offering-validation.js} +9 -8
  45. package/dist/lib/reporting/ledger/offering-validation.mjs +8 -0
  46. package/dist/lib/reporting/ledger/receipts.d.mts +48 -0
  47. package/dist/lib/reporting/ledger/receipts.d.ts +48 -0
  48. package/dist/lib/reporting/ledger/receipts.js +186 -0
  49. package/dist/lib/reporting/ledger/receipts.mjs +161 -0
  50. package/dist/lib/reporting/ledger/status-ingest.js +3 -3
  51. package/dist/lib/reporting/ledger/status-ingest.mjs +4 -5
  52. package/dist/lib/reporting/ledger/types.d.mts +43 -0
  53. package/dist/lib/reporting/ledger/types.d.ts +43 -0
  54. package/dist/lib/reporting/ledger/types.js +31 -2
  55. package/dist/lib/reporting/ledger/types.mjs +26 -1
  56. package/dist/lib/reporting/pagination.d.mts +6 -0
  57. package/dist/lib/reporting/pagination.d.ts +6 -0
  58. package/dist/lib/reporting/{gcs/errors.js → pagination.js} +12 -17
  59. package/dist/lib/reporting/pagination.mjs +12 -0
  60. package/dist/lib/reporting/reconciliation.d.mts +1 -0
  61. package/dist/lib/reporting/reconciliation.d.ts +1 -0
  62. package/dist/lib/reporting/reconciliation.js +3 -2
  63. package/dist/lib/reporting/reconciliation.mjs +3 -2
  64. package/dist/lib/reporting/service/index.d.mts +79 -153
  65. package/dist/lib/reporting/service/index.d.ts +79 -153
  66. package/dist/lib/reporting/service/index.js +34 -491
  67. package/dist/lib/reporting/service/index.mjs +36 -510
  68. package/dist/lib/reporting/service/scheduler-support.d.mts +43 -0
  69. package/dist/lib/reporting/service/scheduler-support.d.ts +43 -0
  70. package/dist/lib/reporting/service/scheduler-support.js +125 -0
  71. package/dist/lib/reporting/service/scheduler-support.mjs +96 -0
  72. package/dist/lib/schemas-data/v2.5/_provenance.json +1 -1
  73. package/dist/lib/signing/canonicalize.d.mts +4 -0
  74. package/dist/lib/signing/canonicalize.d.ts +4 -0
  75. package/dist/lib/signing/canonicalize.js +14 -8
  76. package/dist/lib/signing/canonicalize.mjs +14 -8
  77. package/dist/lib/signing/content-digest.d.mts +8 -0
  78. package/dist/lib/signing/content-digest.d.ts +8 -0
  79. package/dist/lib/signing/content-digest.js +11 -5
  80. package/dist/lib/signing/content-digest.mjs +10 -5
  81. package/dist/lib/signing/crypto.d.mts +15 -0
  82. package/dist/lib/signing/crypto.d.ts +15 -0
  83. package/dist/lib/signing/crypto.js +75 -3
  84. package/dist/lib/signing/crypto.mjs +78 -3
  85. package/dist/lib/signing/server.d.mts +1 -1
  86. package/dist/lib/signing/server.d.ts +1 -1
  87. package/dist/lib/signing/server.js +2 -0
  88. package/dist/lib/signing/server.mjs +2 -1
  89. package/dist/lib/signing/signer.js +11 -14
  90. package/dist/lib/signing/signer.mjs +13 -16
  91. package/dist/lib/signing/testing.js +2 -6
  92. package/dist/lib/signing/testing.mjs +3 -7
  93. package/dist/lib/signing/verifier.js +2 -2
  94. package/dist/lib/signing/verifier.mjs +3 -3
  95. package/dist/lib/signing/web-bot-auth.js +122 -43
  96. package/dist/lib/signing/web-bot-auth.mjs +128 -44
  97. package/dist/lib/signing/webhook-verifier.js +2 -2
  98. package/dist/lib/signing/webhook-verifier.mjs +3 -3
  99. package/dist/lib/substitution/compile.js +2 -1
  100. package/dist/lib/substitution/compile.mjs +2 -1
  101. package/dist/lib/substitution/consent-macros.d.mts +4 -0
  102. package/dist/lib/substitution/consent-macros.d.ts +4 -0
  103. package/dist/lib/substitution/consent-macros.js +45 -0
  104. package/dist/lib/substitution/consent-macros.mjs +20 -0
  105. package/dist/lib/substitution/index.d.mts +1 -1
  106. package/dist/lib/substitution/index.d.ts +1 -1
  107. package/dist/lib/substitution/index.js +2 -0
  108. package/dist/lib/substitution/index.mjs +2 -1
  109. package/dist/lib/substitution/translate.d.mts +15 -2
  110. package/dist/lib/substitution/translate.d.ts +15 -2
  111. package/dist/lib/substitution/translate.js +148 -26
  112. package/dist/lib/substitution/translate.mjs +147 -26
  113. package/dist/lib/testing/client.js +2 -1
  114. package/dist/lib/testing/client.mjs +2 -1
  115. package/dist/lib/testing/scenarios/capabilities.js +1 -1
  116. package/dist/lib/testing/scenarios/capabilities.mjs +1 -1
  117. package/dist/lib/testing/storyboard/junit.js +16 -3
  118. package/dist/lib/testing/storyboard/junit.mjs +16 -3
  119. package/dist/lib/testing/storyboard/request-signing/builder.js +12 -14
  120. package/dist/lib/testing/storyboard/request-signing/builder.mjs +13 -15
  121. package/dist/lib/testing/storyboard/runner.js +94 -25
  122. package/dist/lib/testing/storyboard/runner.mjs +94 -25
  123. package/dist/lib/testing/storyboard/signer-grader/grader.js +2 -7
  124. package/dist/lib/testing/storyboard/signer-grader/grader.mjs +2 -7
  125. package/dist/lib/testing/storyboard/types.d.mts +6 -0
  126. package/dist/lib/testing/storyboard/types.d.ts +6 -0
  127. package/dist/lib/testing/storyboard/validations.d.mts +1 -1
  128. package/dist/lib/testing/storyboard/validations.d.ts +1 -1
  129. package/dist/lib/types/enums.generated.d.mts +3 -0
  130. package/dist/lib/types/enums.generated.d.ts +3 -0
  131. package/dist/lib/types/enums.generated.js +9 -0
  132. package/dist/lib/types/enums.generated.mjs +6 -0
  133. package/dist/lib/validation/schema-loader.js +25 -0
  134. package/dist/lib/validation/schema-loader.mjs +24 -0
  135. package/dist/lib/version.d.mts +3 -3
  136. package/dist/lib/version.d.ts +3 -3
  137. package/dist/lib/version.js +3 -3
  138. package/dist/lib/version.mjs +3 -3
  139. package/docs/TYPE-SUMMARY.md +28 -5
  140. package/docs/guides/DISCOVERY-CACHE-AND-SESSION-REUSE.md +3 -2
  141. package/docs/guides/REPORTING-GCS-FENCE.md +3 -3
  142. package/docs/guides/REPORTING-GCS-MANAGED.md +4 -4
  143. package/docs/guides/REPORTING-LEDGER-CUTOVER.md +7 -7
  144. package/docs/guides/REPORTING-LEDGER.md +107 -51
  145. package/docs/guides/REPORTING-OPERATIONS.md +66 -5
  146. package/docs/guides/REPORTING-STABILITY.md +36 -32
  147. package/docs/guides/UNIVERSAL-MACRO-COMPILATION.md +38 -0
  148. package/docs/guides/VALIDATE-YOUR-AGENT.md +12 -0
  149. package/docs/llms.txt +4 -3
  150. package/docs/migration-14.x-rc-worksheet.md +4 -7
  151. package/docs/migration-reporting-storage-package.md +186 -0
  152. package/examples/README.md +1 -1
  153. package/package.json +14 -78
  154. package/dist/lib/reporting/azure/index.d.mts +0 -31
  155. package/dist/lib/reporting/azure/index.d.ts +0 -31
  156. package/dist/lib/reporting/azure/index.js +0 -266
  157. package/dist/lib/reporting/azure/index.mjs +0 -249
  158. package/dist/lib/reporting/bigquery/index.d.mts +0 -246
  159. package/dist/lib/reporting/bigquery/index.d.ts +0 -246
  160. package/dist/lib/reporting/bigquery/index.js +0 -633
  161. package/dist/lib/reporting/bigquery/index.mjs +0 -594
  162. package/dist/lib/reporting/gcs/adapter.d.mts +0 -38
  163. package/dist/lib/reporting/gcs/adapter.d.ts +0 -38
  164. package/dist/lib/reporting/gcs/adapter.js +0 -342
  165. package/dist/lib/reporting/gcs/adapter.mjs +0 -325
  166. package/dist/lib/reporting/gcs/bucket-policy.d.mts +0 -3
  167. package/dist/lib/reporting/gcs/bucket-policy.d.ts +0 -3
  168. package/dist/lib/reporting/gcs/bucket-policy.mjs +0 -7
  169. package/dist/lib/reporting/gcs/errors.d.mts +0 -11
  170. package/dist/lib/reporting/gcs/errors.d.ts +0 -11
  171. package/dist/lib/reporting/gcs/errors.mjs +0 -16
  172. package/dist/lib/reporting/gcs/fence.d.mts +0 -41
  173. package/dist/lib/reporting/gcs/fence.d.ts +0 -41
  174. package/dist/lib/reporting/gcs/fence.js +0 -250
  175. package/dist/lib/reporting/gcs/fence.mjs +0 -230
  176. package/dist/lib/reporting/gcs/index.d.mts +0 -18
  177. package/dist/lib/reporting/gcs/index.d.ts +0 -18
  178. package/dist/lib/reporting/gcs/index.js +0 -44
  179. package/dist/lib/reporting/gcs/index.mjs +0 -14
  180. package/dist/lib/reporting/gcs/io.d.mts +0 -7
  181. package/dist/lib/reporting/gcs/io.d.ts +0 -7
  182. package/dist/lib/reporting/gcs/io.js +0 -95
  183. package/dist/lib/reporting/gcs/io.mjs +0 -69
  184. package/dist/lib/reporting/gcs/reader.d.mts +0 -67
  185. package/dist/lib/reporting/gcs/reader.d.ts +0 -67
  186. package/dist/lib/reporting/gcs/reader.js +0 -193
  187. package/dist/lib/reporting/gcs/reader.mjs +0 -169
  188. package/dist/lib/reporting/gcs/row-provider.d.mts +0 -39
  189. package/dist/lib/reporting/gcs/row-provider.d.ts +0 -39
  190. package/dist/lib/reporting/gcs/row-provider.js +0 -225
  191. package/dist/lib/reporting/gcs/row-provider.mjs +0 -208
  192. package/dist/lib/reporting/gcs/validation.d.mts +0 -5
  193. package/dist/lib/reporting/gcs/validation.d.ts +0 -5
  194. package/dist/lib/reporting/gcs/validation.js +0 -49
  195. package/dist/lib/reporting/gcs/validation.mjs +0 -25
  196. package/dist/lib/reporting/ledger/change-feed.d.mts +0 -69
  197. package/dist/lib/reporting/ledger/change-feed.d.ts +0 -69
  198. package/dist/lib/reporting/ledger/change-feed.js +0 -107
  199. package/dist/lib/reporting/ledger/change-feed.mjs +0 -80
  200. package/dist/lib/reporting/ledger/managed-postgres.d.mts +0 -293
  201. package/dist/lib/reporting/ledger/managed-postgres.d.ts +0 -293
  202. package/dist/lib/reporting/ledger/managed-postgres.js +0 -2346
  203. package/dist/lib/reporting/ledger/managed-postgres.mjs +0 -2332
  204. package/dist/lib/reporting/ledger/managed-router.d.mts +0 -148
  205. package/dist/lib/reporting/ledger/managed-router.d.ts +0 -148
  206. package/dist/lib/reporting/ledger/managed-router.js +0 -280
  207. package/dist/lib/reporting/ledger/managed-router.mjs +0 -258
  208. package/dist/lib/reporting/ledger/managed.d.mts +0 -535
  209. package/dist/lib/reporting/ledger/managed.d.ts +0 -535
  210. package/dist/lib/reporting/ledger/managed.js +0 -761
  211. package/dist/lib/reporting/ledger/managed.mjs +0 -729
  212. package/dist/lib/reporting/ledger/notification-activity.d.mts +0 -332
  213. package/dist/lib/reporting/ledger/notification-activity.d.ts +0 -332
  214. package/dist/lib/reporting/ledger/notification-activity.js +0 -1366
  215. package/dist/lib/reporting/ledger/notification-activity.mjs +0 -1337
  216. package/dist/lib/reporting/ledger/object-writes.d.mts +0 -128
  217. package/dist/lib/reporting/ledger/object-writes.d.ts +0 -128
  218. package/dist/lib/reporting/ledger/object-writes.js +0 -147
  219. package/dist/lib/reporting/ledger/object-writes.mjs +0 -114
  220. package/dist/lib/reporting/ledger/postgres.d.mts +0 -689
  221. package/dist/lib/reporting/ledger/postgres.d.ts +0 -689
  222. package/dist/lib/reporting/ledger/postgres.js +0 -4462
  223. package/dist/lib/reporting/ledger/postgres.mjs +0 -4462
  224. package/dist/lib/reporting/ledger/row-storage-migration.d.mts +0 -59
  225. package/dist/lib/reporting/ledger/row-storage-migration.d.ts +0 -59
  226. package/dist/lib/reporting/ledger/row-storage-migration.js +0 -365
  227. package/dist/lib/reporting/ledger/row-storage-migration.mjs +0 -339
  228. package/dist/lib/reporting/ledger/row-storage-object.d.mts +0 -203
  229. package/dist/lib/reporting/ledger/row-storage-object.d.ts +0 -203
  230. package/dist/lib/reporting/ledger/row-storage-object.js +0 -379
  231. package/dist/lib/reporting/ledger/row-storage-object.mjs +0 -335
  232. package/dist/lib/reporting/ledger/row-storage-provider-io.d.mts +0 -44
  233. package/dist/lib/reporting/ledger/row-storage-provider-io.d.ts +0 -44
  234. package/dist/lib/reporting/ledger/row-storage-provider-io.js +0 -142
  235. package/dist/lib/reporting/ledger/row-storage-provider-io.mjs +0 -111
  236. package/dist/lib/reporting/ledger/row-storage.d.mts +0 -316
  237. package/dist/lib/reporting/ledger/row-storage.d.ts +0 -316
  238. package/dist/lib/reporting/ledger/row-storage.js +0 -812
  239. package/dist/lib/reporting/ledger/row-storage.mjs +0 -802
  240. package/dist/lib/reporting/s3/index.d.mts +0 -34
  241. package/dist/lib/reporting/s3/index.d.ts +0 -34
  242. package/dist/lib/reporting/s3/index.js +0 -347
  243. package/dist/lib/reporting/s3/index.mjs +0 -340
  244. package/dist/lib/reporting/service/maintenance.d.mts +0 -148
  245. package/dist/lib/reporting/service/maintenance.d.ts +0 -148
  246. package/dist/lib/reporting/service/maintenance.js +0 -185
  247. package/dist/lib/reporting/service/maintenance.mjs +0 -159
  248. package/examples/reliable-reporting-service/README.md +0 -169
@@ -1,761 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var managed_exports = {};
20
- __export(managed_exports, {
21
- REPORTING_ADAPTER_PROBE_DEADLINE_MILLISECONDS_V1: () => REPORTING_ADAPTER_PROBE_DEADLINE_MILLISECONDS_V1,
22
- REPORTING_DESTINATION_PATTERNS_V1: () => REPORTING_DESTINATION_PATTERNS_V1,
23
- REPORTING_DESTINATION_TRANSPORT_PATTERN_V1: () => REPORTING_DESTINATION_TRANSPORT_PATTERN_V1,
24
- UNROUTED_REPORTING_ROUTE_KEY_V1: () => UNROUTED_REPORTING_ROUTE_KEY_V1,
25
- adjustmentReceiptEvidenceMatches: () => adjustmentReceiptEvidenceMatches,
26
- assertCredentialFreeReportingResourceLocationV1: () => assertCredentialFreeReportingResourceLocationV1,
27
- assertMaterializationOutcome: () => assertMaterializationOutcome,
28
- createReportingManagedDeliveryRuntime: () => createReportingManagedDeliveryRuntime,
29
- createSyncReportingReceiptsHandler: () => createSyncReportingReceiptsHandler,
30
- readManagedReportingResource: () => readManagedReportingResource,
31
- receiptEvidenceMatches: () => receiptEvidenceMatches,
32
- reportingManagedDeliveryBindingV1: () => reportingManagedDeliveryBindingV1,
33
- runManagedDeliveryWorker: () => runManagedDeliveryWorker
34
- });
35
- module.exports = __toCommonJS(managed_exports);
36
- var import_node_crypto = require("node:crypto");
37
- var import_schemas = require('../../types/schemas.generated.js');
38
- var import_jcs = require('../../utils/jcs.js');
39
- var import_schema_loader = require('../../validation/schema-loader.js');
40
- var import_evidence = require('../evidence.js');
41
- var import_async_outcome = require('../../server/decisioning/async-outcome.js');
42
- var import_handler = require('./handler.js');
43
- const DEFAULT_LEASE_MILLISECONDS = 65e3;
44
- const DEFAULT_DELIVERY_DEADLINE_MILLISECONDS = 6e4;
45
- const MINIMUM_SETTLEMENT_GRACE_MILLISECONDS = 5e3;
46
- const DEFAULT_RESOURCE_MAX_BYTES = 64 * 1024 * 1024;
47
- const REPORTING_ADAPTER_PROBE_DEADLINE_MILLISECONDS_V1 = 3e4;
48
- const ADAPTER_PROBE_DEADLINE_MILLISECONDS = REPORTING_ADAPTER_PROBE_DEADLINE_MILLISECONDS_V1;
49
- const MAX_DESCRIPTOR_BYTES = 1024 * 1024;
50
- const MAX_NODE_TIMER_DELAY_MILLISECONDS = 2147483647;
51
- const NANOSECONDS_PER_MILLISECOND = 1000000n;
52
- const MAX_RECEIPTS_PER_ARRAY = 100;
53
- const MAX_RECEIPT_RESULTS = 100;
54
- const MAX_RECEIPT_EVIDENCE_BYTES = 64 * 1024;
55
- const REPORTING_DESTINATION_PATTERNS_V1 = Object.freeze([
56
- "file_transfer",
57
- "dataset_share",
58
- "warehouse_materialization"
59
- ]);
60
- const REPORTING_DESTINATION_TRANSPORT_PATTERN_V1 = /^[a-z][a-z0-9_.-]{0,63}$/;
61
- const UNROUTED_REPORTING_ROUTE_KEY_V1 = "~unrouted";
62
- async function createReportingManagedDeliveryRuntime(options) {
63
- if (!await options.store.probe(options.coreStore)) {
64
- throw new Error("Managed reporting store is not operational for the configured Core authority");
65
- }
66
- if (typeof options.store.adoptAdvertisedPolicies !== "function") {
67
- throw new Error(
68
- "Managed Delivery capability publication requires atomic durable adoption of every advertised policy"
69
- );
70
- }
71
- nonnegativeInteger(options.automatedRecoveryWindowSeconds, "automatedRecoveryWindowSeconds");
72
- positiveInteger(options.statusRetentionDays, "statusRetentionDays");
73
- positiveInteger(options.resourceRetentionDays, "resourceRetentionDays");
74
- nonnegativeInteger(options.authorizationRevocationSeconds, "authorizationRevocationSeconds");
75
- if (typeof options.adapter.deliver !== "function" || typeof options.adapter.read !== "function" || typeof options.adapter.revoke !== "function" || options.adapter.revocationFencesDeliveryGenerations !== true) {
76
- throw new Error(
77
- "Managed Delivery requires delivery, resource-reader, and provider generation-fencing revocation components"
78
- );
79
- }
80
- assertManagedOfferings(options.offerings);
81
- if (!options.offerings.length || !options.offerings.some((offering) => offering.method !== void 0)) {
82
- throw new Error("Managed Delivery requires at least one atomic managed offering");
83
- }
84
- const reconciledOfferings = options.offerings.filter((offering) => offering.reconciliation_mode === "consumer_receipt");
85
- if (!options.adapter.verificationProfiles.length) {
86
- throw new Error("Managed Delivery requires an installed verification profile");
87
- }
88
- if (reconciledOfferings.length > 0 && (options.resolveConsumerId === void 0 || !options.adapter.verificationProfiles.includes("canonical_digest"))) {
89
- throw new Error(
90
- "Consumer-receipt offerings require an authenticated receipt handler and canonical-digest verifier"
91
- );
92
- }
93
- if (typeof options.adapter.admitOffering === "function") {
94
- for (const offering of options.offerings) {
95
- const method = offering.method;
96
- if (method === void 0) continue;
97
- options.adapter.admitOffering({ method, reconciliation_mode: offering.reconciliation_mode });
98
- }
99
- }
100
- if (typeof options.adapter.admitBinding === "function" && typeof options.store.setBindingAdmission !== "function") {
101
- throw new Error(
102
- "This Managed Delivery adapter admits bindings at install, but the store cannot enforce an install-time admission"
103
- );
104
- }
105
- const reconciledBilling = reconciledOfferings.length > 0;
106
- for (const offering of reconciledOfferings) {
107
- const profile = offering.reporting_profile;
108
- if (!profile.canonicalization_id || !profile.canonicalization_uri || !profile.canonicalization_sha256) {
109
- throw new Error("Reconciled Billing offerings require the pinned canonicalization contract");
110
- }
111
- }
112
- const statusOptions = options.resolveConsumerId ? {
113
- resolveConsumerId: options.resolveConsumerId,
114
- ...options.consumerMismatchEscalation ? { consumerMismatchEscalation: options.consumerMismatchEscalation } : {}
115
- } : void 0;
116
- const getReportingStatus = (0, import_handler.createReportingStatusHandler)(options.coreStore, statusOptions);
117
- const getMediaBuyDelivery = (0, import_handler.createReportingDeliveryHandler)(
118
- options.coreStore,
119
- options.legacyRevisionReader ? { legacyRevisionReader: options.legacyRevisionReader } : {}
120
- );
121
- const syncReportingReceipts = reconciledBilling ? createSyncReportingReceiptsHandler(options.store, options.resolveConsumerId) : void 0;
122
- const reportingDeliveryCapabilities = {
123
- supported: true,
124
- reliable_reporting_version: "1.0",
125
- managed_delivery: true,
126
- ...reconciledBilling ? { reconciled_billing: true, receipt_task: "sync_reporting_receipts" } : {},
127
- configuration_task: "sync_accounts",
128
- status_task: "get_reporting_status",
129
- revision_content_task: "get_media_buy_delivery",
130
- offerings: [...options.offerings],
131
- automated_recovery_window_seconds: options.automatedRecoveryWindowSeconds,
132
- status_retention_days: options.statusRetentionDays,
133
- resource_retention_days: options.resourceRetentionDays,
134
- authorization_revocation_seconds: options.authorizationRevocationSeconds
135
- };
136
- const parsedCapabilities = import_schemas.ReportingDeliveryCapabilitiesSchema.safeParse(reportingDeliveryCapabilities);
137
- if (!parsedCapabilities.success) {
138
- throw new Error(
139
- `Managed Delivery capability wiring is invalid: ${parsedCapabilities.error.issues[0]?.message ?? "invalid"}`
140
- );
141
- }
142
- if (typeof options.adapter.probe === "function") await probeAdapter(options.adapter);
143
- const adoptedPolicy = await options.store.adoptAdvertisedPolicies({
144
- automatedRecoveryWindowSeconds: options.automatedRecoveryWindowSeconds,
145
- statusRetentionDays: options.statusRetentionDays,
146
- resourceRetentionDays: options.resourceRetentionDays,
147
- authorizationRevocationSeconds: options.authorizationRevocationSeconds
148
- });
149
- nonnegativeInteger(adoptedPolicy.automatedRecoveryWindowSeconds, "adopted automatedRecoveryWindowSeconds");
150
- positiveInteger(adoptedPolicy.statusRetentionDays, "adopted statusRetentionDays");
151
- positiveInteger(adoptedPolicy.resourceRetentionDays, "adopted resourceRetentionDays");
152
- nonnegativeInteger(adoptedPolicy.authorizationRevocationSeconds, "adopted authorizationRevocationSeconds");
153
- if (adoptedPolicy.automatedRecoveryWindowSeconds > options.automatedRecoveryWindowSeconds || adoptedPolicy.statusRetentionDays < options.statusRetentionDays || adoptedPolicy.resourceRetentionDays < options.resourceRetentionDays || adoptedPolicy.authorizationRevocationSeconds > options.authorizationRevocationSeconds) {
154
- throw new Error("Managed Delivery policy adoption returned values weaker than the capability being published");
155
- }
156
- if (typeof options.adapter.admitBinding === "function") {
157
- const adapter = options.adapter;
158
- options.store.setBindingAdmission?.((binding) => adapter.admitBinding(binding));
159
- }
160
- return {
161
- reportingDeliveryCapabilities,
162
- getReportingStatus,
163
- getMediaBuyDelivery,
164
- ...syncReportingReceipts ? { syncReportingReceipts } : {},
165
- runWorker: (workerOptions) => runManagedDeliveryWorker(options.store, options.adapter, {
166
- ...typeof options.coreStore.getRevision === "function" ? {
167
- hydrateRevision: async (revision, accountId) => {
168
- const hydrated = await options.coreStore.getRevision(revision.reporting_revision_id, accountId);
169
- if (!hydrated) throw new Error("Reporting revision is unavailable for delivery");
170
- return hydrated;
171
- }
172
- } : {},
173
- ...workerOptions,
174
- minimumResourceRetentionDays: Math.max(
175
- options.resourceRetentionDays,
176
- adoptedPolicy.resourceRetentionDays,
177
- workerOptions?.minimumResourceRetentionDays ?? 0
178
- ),
179
- // The capability block is the promise; the worker is what keeps it.
180
- // A caller may only tighten the advertised window, never widen it.
181
- authorizationRevocationSeconds: Math.min(
182
- options.authorizationRevocationSeconds,
183
- adoptedPolicy.authorizationRevocationSeconds,
184
- workerOptions?.authorizationRevocationSeconds ?? options.authorizationRevocationSeconds
185
- )
186
- }),
187
- readResource: (input) => readManagedReportingResource(options.store, options.adapter, input)
188
- };
189
- }
190
- function createSyncReportingReceiptsHandler(store, resolveConsumerId, now = () => /* @__PURE__ */ new Date()) {
191
- return async (request, context) => {
192
- const account_id = resolvedAccountId(context.account);
193
- const consumer_id = await resolveConsumerId(context);
194
- if (!consumer_id || consumer_id.length > 255) {
195
- throw new TypeError("resolveConsumerId must return a durable authenticated principal of at most 255 characters");
196
- }
197
- if (request.receipts !== void 0 && !Array.isArray(request.receipts)) {
198
- throw new import_async_outcome.AdcpError("VALIDATION_ERROR", { message: "sync_reporting_receipts receipts must be an array" });
199
- }
200
- if (request.adjustment_receipts !== void 0 && !Array.isArray(request.adjustment_receipts)) {
201
- throw new import_async_outcome.AdcpError("VALIDATION_ERROR", {
202
- message: "sync_reporting_receipts adjustment_receipts must be an array"
203
- });
204
- }
205
- const revisionReceipts = request.receipts ?? [];
206
- const adjustmentReceipts = request.adjustment_receipts ?? [];
207
- if (!revisionReceipts.every(isRecord) || !adjustmentReceipts.every(isRecord)) {
208
- throw new import_async_outcome.AdcpError("VALIDATION_ERROR", {
209
- message: "sync_reporting_receipts entries must be objects"
210
- });
211
- }
212
- if (revisionReceipts.length > MAX_RECEIPTS_PER_ARRAY || adjustmentReceipts.length > MAX_RECEIPTS_PER_ARRAY) {
213
- throw new import_async_outcome.AdcpError("VALIDATION_ERROR", {
214
- message: `sync_reporting_receipts accepts at most ${MAX_RECEIPTS_PER_ARRAY} receipts and ${MAX_RECEIPTS_PER_ARRAY} adjustment receipts per request`
215
- });
216
- }
217
- if ([...revisionReceipts, ...adjustmentReceipts].some((receipt) => "received_at" in receipt)) {
218
- throw new import_async_outcome.AdcpError("VALIDATION_ERROR", {
219
- message: "sync_reporting_receipts receipts must not carry received_at; it is assigned by the server"
220
- });
221
- }
222
- const entries = [
223
- ...revisionReceipts.map((receipt) => ({ kind: "revision", receipt })),
224
- ...adjustmentReceipts.map((receipt) => ({
225
- kind: "adjustment",
226
- receipt
227
- }))
228
- ];
229
- if (entries.length > MAX_RECEIPT_RESULTS) {
230
- throw new import_async_outcome.AdcpError("VALIDATION_ERROR", {
231
- message: `sync_reporting_receipts can return at most ${MAX_RECEIPT_RESULTS} results, so a request may carry at most ${MAX_RECEIPT_RESULTS} receipts and adjustment receipts in total`
232
- });
233
- }
234
- if (!entries.length) {
235
- throw new import_async_outcome.AdcpError("VALIDATION_ERROR", {
236
- message: "sync_reporting_receipts requires at least one receipt or adjustment receipt"
237
- });
238
- }
239
- if (request.account && "account_id" in request.account && request.account.account_id !== account_id) {
240
- return receiptBatchFailure(entries, "PERMISSION_DENIED", "Reporting receipt account is unavailable");
241
- }
242
- if (!/^[A-Za-z0-9_.:-]{16,255}$/.test(request.idempotency_key)) {
243
- return receiptBatchFailure(entries, "VALIDATION_ERROR", "sync_reporting_receipts idempotency_key is invalid");
244
- }
245
- const submittedIds = entries.map(
246
- (entry) => isRecord(entry.receipt) && typeof entry.receipt.reporting_receipt_id === "string" ? entry.receipt.reporting_receipt_id : ""
247
- );
248
- const duplicateSubmittedIds = new Set(
249
- submittedIds.filter((value, index) => value !== "" && submittedIds.indexOf(value) !== index)
250
- );
251
- if (duplicateSubmittedIds.size) {
252
- return receiptBatchFailure(
253
- entries,
254
- "VALIDATION_ERROR",
255
- "sync_reporting_receipts receipt IDs must be unique across the batch"
256
- );
257
- }
258
- const evidenceValid = entries.map(
259
- (entry) => entry.kind === "revision" ? (0, import_evidence.isReportingReceiptEvidence)(entry.receipt) : (0, import_evidence.isReportingAdjustmentReceiptEvidence)(entry.receipt)
260
- );
261
- const oversized = entries.map(
262
- (entry) => Buffer.byteLength(JSON.stringify(entry.receipt), "utf8") > MAX_RECEIPT_EVIDENCE_BYTES
263
- );
264
- const valid = entries.map((_, index) => evidenceValid[index] && !oversized[index]);
265
- const validEntries = entries.filter((_, index) => valid[index]);
266
- const request_fingerprint = sha256({ entries });
267
- const stored = validEntries.length ? await store.syncReceiptBatch({
268
- account_id,
269
- consumer_id,
270
- idempotency_key: request.idempotency_key,
271
- request_fingerprint,
272
- entries: validEntries,
273
- received_at: now().toISOString()
274
- }) : [];
275
- let storedIndex = 0;
276
- return {
277
- status: "completed",
278
- results: entries.map((entry, index) => {
279
- if (valid[index]) return stored[storedIndex++];
280
- const field = entry.kind === "revision" ? `receipts[${index}]` : `adjustment_receipts[${index - revisionReceipts.length}]`;
281
- return oversized[index] ? receiptFailure(
282
- reflectableReceiptId(entry.receipt.reporting_receipt_id, index),
283
- "VALIDATION_ERROR",
284
- "Reporting receipt evidence exceeds the 64 KiB limit",
285
- {
286
- field,
287
- suggestion: `Reduce ${field} to 64 KiB or less and retry.`
288
- }
289
- ) : receiptFailure(
290
- reflectableReceiptId(entry.receipt.reporting_receipt_id, index),
291
- "VALIDATION_ERROR",
292
- "Reporting receipt evidence is malformed",
293
- {
294
- field,
295
- suggestion: `Correct ${field} to satisfy the reporting receipt evidence schema and retry.`
296
- }
297
- );
298
- })
299
- };
300
- };
301
- }
302
- function receiptBatchFailure(entries, code, message) {
303
- return {
304
- status: "completed",
305
- results: entries.map(
306
- (entry, index) => receiptFailure(reflectableReceiptId(entry.receipt.reporting_receipt_id, index), code, message)
307
- )
308
- };
309
- }
310
- const RECEIPT_ID_PATTERN = /^[A-Za-z0-9_.:-]{16,255}$/;
311
- function reflectableReceiptId(value, index) {
312
- return typeof value === "string" && RECEIPT_ID_PATTERN.test(value) ? value : `unidentified-reporting-receipt-${String(index).padStart(3, "0")}`;
313
- }
314
- function receiptFailure(reporting_receipt_id, code, message, metadata = {}) {
315
- return {
316
- result: "failed",
317
- reporting_receipt_id,
318
- errors: [{ code, message, recovery: "correctable", ...metadata }]
319
- };
320
- }
321
- async function runManagedDeliveryWorker(store, adapter, options = {}) {
322
- const now = options.now ?? (() => /* @__PURE__ */ new Date());
323
- const maxIterations = options.maxIterations ?? 25;
324
- const leaseMilliseconds = options.leaseMilliseconds ?? DEFAULT_LEASE_MILLISECONDS;
325
- const deadlineMilliseconds = options.deliveryDeadlineMilliseconds ?? DEFAULT_DELIVERY_DEADLINE_MILLISECONDS;
326
- const resourceMaxBytes = options.resourceMaxBytes ?? DEFAULT_RESOURCE_MAX_BYTES;
327
- const minimumResourceRetentionDays = options.minimumResourceRetentionDays ?? 1;
328
- positiveInteger(maxIterations, "maxIterations");
329
- positiveInteger(leaseMilliseconds, "leaseMilliseconds");
330
- positiveInteger(deadlineMilliseconds, "deliveryDeadlineMilliseconds");
331
- positiveInteger(resourceMaxBytes, "resourceMaxBytes");
332
- positiveInteger(minimumResourceRetentionDays, "minimumResourceRetentionDays");
333
- if (leaseMilliseconds < deadlineMilliseconds + MINIMUM_SETTLEMENT_GRACE_MILLISECONDS) {
334
- throw new RangeError("leaseMilliseconds must include at least 5 seconds of post-delivery settlement grace");
335
- }
336
- if (options.authorizationRevocationSeconds !== void 0) {
337
- nonnegativeInteger(options.authorizationRevocationSeconds, "authorizationRevocationSeconds");
338
- }
339
- const revocationWindow = options.authorizationRevocationSeconds === void 0 ? void 0 : options.authorizationRevocationSeconds * 1e3;
340
- const revocationLeaseMilliseconds = revocationWindow === void 0 ? leaseMilliseconds : Math.min(leaseMilliseconds, deadlineMilliseconds + MINIMUM_SETTLEMENT_GRACE_MILLISECONDS);
341
- const owner = `managed-reporting-${(0, import_node_crypto.randomUUID)()}`;
342
- const exhausted = await store.failExhaustedMaterializations?.({
343
- ...options.account_id ? { account_id: options.account_id } : {}
344
- }) ?? 0;
345
- const counts = {
346
- exhausted,
347
- planned: await store.planMaterializations({ ...options.account_id ? { account_id: options.account_id } : {} }),
348
- claimed: 0,
349
- delivered: 0,
350
- failed: 0,
351
- revocationsCompleted: 0,
352
- revocationsOverdue: 0
353
- };
354
- const routed = typeof adapter.routeIdFor === "function" ? {
355
- deliveriesByRoute: {},
356
- deliveryFailuresByRoute: {},
357
- revocationsByRoute: {},
358
- revocationFailuresByRoute: {},
359
- overdueByRoute: {}
360
- } : void 0;
361
- if (routed) Object.assign(counts, routed);
362
- const countRoute = (bucket, target) => {
363
- if (!routed) return;
364
- let id;
365
- try {
366
- id = adapter.routeIdFor(target);
367
- } catch {
368
- id = void 0;
369
- }
370
- const key = typeof id === "string" && id !== "" ? id : UNROUTED_REPORTING_ROUTE_KEY_V1;
371
- routed[bucket][key] = (routed[bucket][key] ?? 0) + 1;
372
- };
373
- for (let index = 0; index < maxIterations; index += 1) {
374
- options.signal?.throwIfAborted();
375
- const revocation = await store.claimRevocation({
376
- owner,
377
- now: now().toISOString(),
378
- lease_milliseconds: revocationLeaseMilliseconds,
379
- ...options.account_id ? { account_id: options.account_id } : {},
380
- ...options.authorizationRevocationSeconds !== void 0 ? {
381
- authorization_revocation_seconds: options.authorizationRevocationSeconds,
382
- // A holder is only displaced after it has had a full attempt's
383
- // worth of time, which recovers a crashed worker without letting
384
- // live workers steal from each other on an already-late grant.
385
- steal_after_milliseconds: deadlineMilliseconds + MINIMUM_SETTLEMENT_GRACE_MILLISECONDS
386
- } : {}
387
- });
388
- if (!revocation) break;
389
- const remaining = revocation.remaining_milliseconds ?? remainingRevocationMilliseconds(revocation, revocationWindow, now());
390
- const overdue = revocation.overdue ?? (remaining !== void 0 && remaining <= 0);
391
- if (overdue) {
392
- counts.revocationsOverdue += 1;
393
- countRoute("overdueByRoute", { authorization: revocation.authorization });
394
- }
395
- const attemptDeadline = remaining !== void 0 && remaining > 0 ? Math.min(deadlineMilliseconds, remaining) : deadlineMilliseconds;
396
- try {
397
- await withinDeadline(
398
- (signal) => adapter.revoke({ authorization: revocation.authorization }, { signal }),
399
- attemptDeadline,
400
- "Reporting revocation deadline elapsed",
401
- options.signal
402
- );
403
- if (await store.completeRevocation({ lease: revocation, completed_at: now().toISOString() })) {
404
- counts.revocationsCompleted += 1;
405
- countRoute("revocationsByRoute", { authorization: revocation.authorization });
406
- }
407
- } catch {
408
- countRoute("revocationFailuresByRoute", { authorization: revocation.authorization });
409
- await store.releaseRevocation({ lease: revocation });
410
- }
411
- }
412
- for (let index = 0; index < maxIterations; index += 1) {
413
- options.signal?.throwIfAborted();
414
- const lease = await store.claimMaterialization({
415
- owner,
416
- now: now().toISOString(),
417
- lease_milliseconds: leaseMilliseconds,
418
- ...options.account_id ? { account_id: options.account_id } : {}
419
- });
420
- if (!lease) break;
421
- counts.claimed += 1;
422
- try {
423
- if (!Array.isArray(lease.revision.rows) && options.hydrateRevision) {
424
- const hydrated = await options.hydrateRevision(
425
- lease.revision,
426
- lease.obligation.account.account_id,
427
- options.signal
428
- );
429
- if (hydrated.reporting_revision_id !== lease.revision.reporting_revision_id || hydrated.binding.sha256 !== lease.revision.binding.sha256 || !Array.isArray(hydrated.rows)) {
430
- throw new Error("Hydrated reporting revision does not match the claimed revision");
431
- }
432
- lease.revision = hydrated;
433
- }
434
- const outcome = await withinDeadline(
435
- (signal) => adapter.deliver(
436
- {
437
- materialization: lease.materialization,
438
- binding: lease.binding,
439
- obligation: lease.obligation,
440
- revision: lease.revision,
441
- maxBytes: resourceMaxBytes
442
- },
443
- { signal }
444
- ),
445
- deadlineMilliseconds,
446
- "Reporting delivery deadline elapsed",
447
- options.signal
448
- );
449
- assertMaterializationOutcome(lease, outcome, now().toISOString(), minimumResourceRetentionDays);
450
- if (await store.settleMaterialization({
451
- lease,
452
- now: now().toISOString(),
453
- outcome,
454
- minimum_resource_retention_days: Math.max(
455
- lease.binding.resource_retention_days,
456
- minimumResourceRetentionDays
457
- )
458
- })) {
459
- counts.delivered += 1;
460
- countRoute("deliveriesByRoute", { binding: lease.binding });
461
- } else {
462
- counts.failed += 1;
463
- countRoute("deliveryFailuresByRoute", { binding: lease.binding });
464
- }
465
- } catch {
466
- await store.settleMaterialization({
467
- lease,
468
- now: now().toISOString(),
469
- outcome: { status: "failed", failure_code: "DELIVERY_FAILED" }
470
- });
471
- counts.failed += 1;
472
- countRoute("deliveryFailuresByRoute", { binding: lease.binding });
473
- }
474
- }
475
- return counts;
476
- }
477
- async function probeAdapter(adapter) {
478
- try {
479
- await withinDeadline(
480
- (signal) => Promise.resolve().then(() => adapter.probe({ signal })),
481
- ADAPTER_PROBE_DEADLINE_MILLISECONDS,
482
- "Managed Delivery adapter probe deadline elapsed"
483
- );
484
- } catch (cause) {
485
- const failed = cause?.failedRouteIds;
486
- const routes = Array.isArray(failed) ? failed.filter((id) => typeof id === "string") : [];
487
- throw new Error(
488
- routes.length ? `Managed Delivery adapter probe failed for route ${routes.map((id) => JSON.stringify(id)).join(", ")}` : "Managed Delivery adapter probe failed",
489
- { cause }
490
- );
491
- }
492
- }
493
- function remainingRevocationMilliseconds(revocation, revocationWindow, now) {
494
- if (revocationWindow === void 0) return void 0;
495
- const revokedAt = revocation.authorization.revoked_at;
496
- if (!revokedAt) return void 0;
497
- const revoked = Date.parse(revokedAt);
498
- if (!Number.isFinite(revoked)) return void 0;
499
- return revoked + revocationWindow - now.getTime();
500
- }
501
- async function readManagedReportingResource(store, adapter, input) {
502
- const maxBytes = input.maxBytes ?? DEFAULT_RESOURCE_MAX_BYTES;
503
- const deadlineMilliseconds = input.deadlineMilliseconds ?? DEFAULT_DELIVERY_DEADLINE_MILLISECONDS;
504
- positiveInteger(maxBytes, "maxBytes");
505
- positiveInteger(deadlineMilliseconds, "deadlineMilliseconds");
506
- const selected = await store.getReadableResource(input);
507
- const resource = selected?.materialization.resource;
508
- if (!selected || !resource) return null;
509
- const { binding, materialization } = selected;
510
- const bytes = await withinDeadline(
511
- // Adapter failure messages are provider strings: they vary by SDK version
512
- // and can carry endpoint or credential detail. Callers get one stable
513
- // sentence; the provider error stays reachable as `cause` for seller logs.
514
- // `Promise.resolve().then` rather than calling and chaining `.catch`: an
515
- // adapter that throws synchronously — a bad credential resolved eagerly,
516
- // a client constructed inside `read` — never produced a promise to attach
517
- // the handler to, so its raw provider message escaped this boundary.
518
- (signal) => Promise.resolve().then(() => adapter.read({ materialization, binding, resource, maxBytes }, { signal })).catch((cause) => {
519
- throw new Error("Managed reporting resource read failed", { cause });
520
- }),
521
- deadlineMilliseconds,
522
- "Reporting resource read deadline elapsed",
523
- input.signal
524
- );
525
- if (bytes.byteLength > maxBytes) throw new RangeError("Managed reporting resource exceeds maxBytes");
526
- if (!await store.isAuthorizationCurrent({
527
- account_id: input.account_id,
528
- destination_ref: binding.destination_ref,
529
- generation: binding.authorization_generation
530
- })) {
531
- return null;
532
- }
533
- return bytes;
534
- }
535
- function assertMaterializationOutcome(lease, outcome, now, minimumResourceRetentionDays = lease.binding.resource_retention_days) {
536
- const parsed = import_schemas.ReportingMaterializationSchema.safeParse({
537
- ...lease.materialization,
538
- status: outcome.status,
539
- ready_at: now,
540
- resource: outcome.resource,
541
- verification: outcome.verification
542
- });
543
- if (!parsed.success) {
544
- throw new Error(`Managed materialization evidence is invalid: ${parsed.error.issues[0]?.message ?? "invalid"}`);
545
- }
546
- if (Buffer.byteLength(JSON.stringify(outcome), "utf8") > MAX_DESCRIPTOR_BYTES) {
547
- throw new RangeError("Managed materialization descriptor exceeds 1 MiB");
548
- }
549
- if (outcome.verification.verification_profile !== lease.binding.verification_profile) {
550
- throw new Error("Materialization verification profile differs from the installed binding");
551
- }
552
- if (outcome.verification.row_count !== lease.revision.binding.rowCount) {
553
- throw new Error("Materialization verification row count differs from the Core revision");
554
- }
555
- if (!(0, import_evidence.isReportingVerificationEvidence)(outcome.verification)) {
556
- throw new Error("Materialization is missing evidence required by its verification profile");
557
- }
558
- if (canonicalJson(outcome.verification.control_totals) !== canonicalJson(lease.revision.wireRevision.control_totals)) {
559
- throw new Error("Materialization verification control totals differ from the Core revision");
560
- }
561
- if (lease.binding.feed_purpose === "billing" && lease.binding.verification_profile !== "canonical_digest") {
562
- throw new Error("Billing materializations require canonical-digest verification");
563
- }
564
- if (lease.binding.method === "file_transfer" && outcome.resource.kind !== "manifest" || lease.binding.method === "dataset_share" && (outcome.resource.kind !== "dataset" || outcome.verification.verification_path !== "representative_consumer") || lease.binding.method === "warehouse_materialization" && (outcome.resource.kind !== "warehouse_relation" || outcome.verification.verification_path !== "destination")) {
565
- throw new Error("Materialization resource or verification path differs from its delivery method");
566
- }
567
- if (lease.binding.method === "file_transfer" && !outcome.verification.physical_checksums?.length) {
568
- throw new Error("File-transfer materializations require physical checksums");
569
- }
570
- if (outcome.resource.kind === "manifest" && (outcome.resource.manifest_version !== "1.0" || !outcome.resource.manifest_sha256)) {
571
- throw new Error("Manifest resources require immutable version and digest metadata");
572
- }
573
- const native = outcome.verification.native_commit_evidence;
574
- if (native !== void 0) {
575
- if (native.native_version_ref !== outcome.resource.native_version_ref || native.observed_through !== outcome.verification.verification_path) {
576
- throw new Error("Native commit evidence does not match the retained resource and verification path");
577
- }
578
- }
579
- void minimumResourceRetentionDays;
580
- if (outcome.verification.canonical_content_digest !== void 0) {
581
- const expected = lease.revision.wireRevision.canonical_content_digest;
582
- if (!expected || canonicalJson(outcome.verification.canonical_content_digest) !== canonicalJson(expected)) {
583
- throw new Error("Canonical materialization evidence does not match the official Core revision");
584
- }
585
- }
586
- if (outcome.resource.immutability === "native_version" && !outcome.resource.native_version_ref) {
587
- throw new Error("Native-version materializations require an exact native_version_ref");
588
- }
589
- assertCredentialFreeReportingResourceLocationV1(outcome.resource.location);
590
- }
591
- function receiptEvidenceMatches(receipt, materialization) {
592
- const verification = materialization.verification;
593
- const resource = materialization.resource;
594
- if (!verification || !resource || !(0, import_evidence.isReportingReceiptEvidence)(receipt)) return false;
595
- return receipt.verification_profile === verification.verification_profile && receipt.observed_row_count === verification.row_count && canonicalJson(receipt.observed_control_totals) === canonicalJson(verification.control_totals) && canonicalJson(receipt.observed_canonical_content_digest) === canonicalJson(verification.canonical_content_digest) && (verification.verification_profile !== "manifest_checksums" || receipt.observed_manifest_sha256 === resource.manifest_sha256) && (verification.verification_profile !== "native_commit" || receipt.observed_native_version_ref === resource.native_version_ref);
596
- }
597
- function adjustmentReceiptEvidenceMatches(receipt, adjustment) {
598
- return (0, import_evidence.isReportingAdjustmentReceiptEvidence)(receipt) && receipt.adjusts_reporting_revision_id === adjustment.adjusts_reporting_revision_id && receipt.observed_adjustment_sha256 === adjustment.wireAdjustment.canonical_adjustment_sha256;
599
- }
600
- function resolvedAccountId(account) {
601
- if (!account || typeof account !== "object") throw new Error("Reporting receipts require a resolved account");
602
- const value = account;
603
- const id = typeof value.id === "string" ? value.id : typeof value.account_id === "string" ? value.account_id : "";
604
- if (!id) throw new Error("Reporting receipts require a resolved account");
605
- return id;
606
- }
607
- function sha256(value) {
608
- return (0, import_node_crypto.createHash)("sha256").update(canonicalJson(value)).digest("hex");
609
- }
610
- function canonicalJson(value) {
611
- return (0, import_jcs.canonicalize)(value === void 0 ? null : value);
612
- }
613
- function positiveInteger(value, name) {
614
- if (!Number.isSafeInteger(value) || value <= 0) throw new RangeError(`${name} must be a positive safe integer`);
615
- }
616
- function nonnegativeInteger(value, name) {
617
- if (!Number.isSafeInteger(value) || value < 0) throw new RangeError(`${name} must be a non-negative safe integer`);
618
- }
619
- function assertManagedOfferings(offerings) {
620
- const validateOffering = (0, import_schema_loader.getSchemaValidatorByRef)("core/reporting-delivery-offering.json");
621
- if (!validateOffering) throw new Error("The installed AdCP bundle cannot validate reporting delivery offerings");
622
- const ids = /* @__PURE__ */ new Set();
623
- for (const offering of offerings) {
624
- if (!validateOffering(offering)) {
625
- throw new Error("Managed Delivery offering does not satisfy the complete installed RC3 schema");
626
- }
627
- if (ids.has(offering.offering_id)) throw new Error("Managed Delivery offering_id values must be unique");
628
- ids.add(offering.offering_id);
629
- const method = offering.method;
630
- if (method !== void 0) {
631
- if (!isRecord(method)) throw new Error("Managed Delivery offering method is invalid");
632
- const pattern = method.pattern;
633
- if (!["file_transfer", "dataset_share", "warehouse_materialization"].includes(String(pattern)) || typeof method.transport !== "string" || !["producer_managed", "consumer_managed"].includes(String(method.orchestration)) || !Array.isArray(method.destination_modes) || method.destination_modes.length === 0 || !isRecord(method.provider) || typeof method.provider.domain !== "string" || pattern === "file_transfer" && typeof method.format !== "string" || pattern === "dataset_share" && typeof method.access_mode !== "string") {
634
- throw new Error("Managed Delivery offering method omits RC3-required delivery fields");
635
- }
636
- }
637
- if (offering.feed_purpose === "billing" && offering.reconciliation_mode !== "consumer_receipt") {
638
- throw new Error("Billing offerings require consumer-receipt reconciliation");
639
- }
640
- const profile = offering.reporting_profile;
641
- if (offering.reconciliation_mode === "consumer_receipt") {
642
- if (method === void 0 || profile.canonicalization_contract_version !== "1.0" || profile.canonicalization_media_type !== "application/vnd.adcp.reporting-canonicalization+json" || !profile.canonicalization_id || !profile.canonicalization_uri || !profile.canonicalization_sha256) {
643
- throw new Error("Reconciled Billing offerings require the complete pinned RC3 canonicalization contract");
644
- }
645
- }
646
- }
647
- }
648
- function isRecord(value) {
649
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
650
- }
651
- function assertCredentialFreeReportingResourceLocationV1(location) {
652
- const refuse = () => {
653
- throw new Error("Managed reporting resource locations must not contain credentials");
654
- };
655
- if (/\r|\n|-----BEGIN|\bbearer\s|(?:token|password|secret|signature)=/i.test(location)) refuse();
656
- if (/[?#]/.test(location)) refuse();
657
- if (hasColonSeparatedUserinfo(location)) refuse();
658
- try {
659
- const parsed = new URL(location);
660
- if (parsed.password || parsed.search || parsed.hash) refuse();
661
- if (parsed.username && (parsed.protocol === "http:" || parsed.protocol === "https:")) refuse();
662
- } catch (error) {
663
- if (error instanceof Error && error.message.includes("must not contain credentials")) throw error;
664
- }
665
- }
666
- function hasColonSeparatedUserinfo(location) {
667
- let scanningCandidate = true;
668
- let sawColon = false;
669
- let previousWasSlash = false;
670
- for (let index = 0; index < location.length; index += 1) {
671
- const code = location.charCodeAt(index);
672
- if (scanningCandidate) {
673
- if (code === 64) {
674
- if (sawColon) return true;
675
- scanningCandidate = false;
676
- } else if (code === 58) {
677
- sawColon = true;
678
- } else if (code === 47 || code === 63 || code === 35 || isLocationWhitespace(code)) {
679
- scanningCandidate = false;
680
- }
681
- }
682
- const startsAuthorityCandidate = code === 47 && previousWasSlash;
683
- previousWasSlash = code === 47;
684
- if (startsAuthorityCandidate) {
685
- scanningCandidate = true;
686
- sawColon = false;
687
- }
688
- }
689
- return false;
690
- }
691
- function isLocationWhitespace(code) {
692
- return code >= 9 && code <= 13 || code === 32 || code === 160 || code === 5760 || code >= 8192 && code <= 8202 || code === 8232 || code === 8233 || code === 8239 || code === 8287 || code === 12288 || code === 65279;
693
- }
694
- async function withinDeadline(operation, milliseconds, message, outerSignal) {
695
- outerSignal?.throwIfAborted();
696
- const controller = new AbortController();
697
- const signal = outerSignal ? AbortSignal.any([outerSignal, controller.signal]) : controller.signal;
698
- let cancelTimer;
699
- try {
700
- return await Promise.race([
701
- operation(signal),
702
- new Promise((_resolve, reject) => {
703
- cancelTimer = scheduleDeadline(milliseconds, () => {
704
- const error = new Error(message);
705
- controller.abort(error);
706
- reject(error);
707
- });
708
- })
709
- ]);
710
- } finally {
711
- cancelTimer?.();
712
- }
713
- }
714
- function scheduleDeadline(milliseconds, onElapsed) {
715
- const normalizedMilliseconds = Math.ceil(milliseconds);
716
- if (milliseconds < 0 || !Number.isSafeInteger(normalizedMilliseconds)) {
717
- throw new RangeError("Reporting deadline must be a finite non-negative safe number of milliseconds");
718
- }
719
- const expiresAt = process.hrtime.bigint() + BigInt(normalizedMilliseconds) * NANOSECONDS_PER_MILLISECOND;
720
- let cancelled = false;
721
- let timer;
722
- const scheduleRemaining = () => {
723
- if (cancelled) return;
724
- const remainingNanoseconds = expiresAt - process.hrtime.bigint();
725
- if (remainingNanoseconds <= 0n) {
726
- onElapsed();
727
- return;
728
- }
729
- const remainingMilliseconds = Number(
730
- (remainingNanoseconds + NANOSECONDS_PER_MILLISECOND - 1n) / NANOSECONDS_PER_MILLISECOND
731
- );
732
- timer = setTimeout(scheduleRemaining, Math.min(remainingMilliseconds, MAX_NODE_TIMER_DELAY_MILLISECONDS));
733
- };
734
- scheduleRemaining();
735
- return () => {
736
- cancelled = true;
737
- if (timer) clearTimeout(timer);
738
- };
739
- }
740
- function reportingManagedDeliveryBindingV1(input) {
741
- const created_at = input.created_at ?? (/* @__PURE__ */ new Date()).toISOString();
742
- const { semantic_fingerprint: _predecessor, ...semantic } = input;
743
- const semantic_fingerprint = sha256({ ...semantic, created_at: void 0 });
744
- return { ...semantic, created_at, semantic_fingerprint };
745
- }
746
- // Annotate the CommonJS export names for ESM import in node:
747
- 0 && (module.exports = {
748
- REPORTING_ADAPTER_PROBE_DEADLINE_MILLISECONDS_V1,
749
- REPORTING_DESTINATION_PATTERNS_V1,
750
- REPORTING_DESTINATION_TRANSPORT_PATTERN_V1,
751
- UNROUTED_REPORTING_ROUTE_KEY_V1,
752
- adjustmentReceiptEvidenceMatches,
753
- assertCredentialFreeReportingResourceLocationV1,
754
- assertMaterializationOutcome,
755
- createReportingManagedDeliveryRuntime,
756
- createSyncReportingReceiptsHandler,
757
- readManagedReportingResource,
758
- receiptEvidenceMatches,
759
- reportingManagedDeliveryBindingV1,
760
- runManagedDeliveryWorker
761
- });