@opendatalabs/vana-sdk 3.23.0 → 4.0.0

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 (84) hide show
  1. package/README.md +57 -0
  2. package/dist/auth/errors.cjs +1 -1
  3. package/dist/auth/web3-signed.cjs +1 -1
  4. package/dist/crypto/envelope/job-stream.test.d.ts +1 -0
  5. package/dist/crypto/envelope/job.cjs +593 -38
  6. package/dist/crypto/envelope/job.cjs.map +1 -1
  7. package/dist/crypto/envelope/job.d.ts +44 -27
  8. package/dist/crypto/envelope/job.js +589 -37
  9. package/dist/crypto/envelope/job.js.map +1 -1
  10. package/dist/direct/access-request-client.cjs +1 -1
  11. package/dist/direct/connect-flow.cjs +43 -1
  12. package/dist/direct/connect-flow.cjs.map +1 -1
  13. package/dist/direct/connect-flow.d.ts +12 -0
  14. package/dist/direct/connect-flow.js +43 -1
  15. package/dist/direct/connect-flow.js.map +1 -1
  16. package/dist/direct/controller.cjs +1 -1
  17. package/dist/direct/errors.cjs +1 -1
  18. package/dist/direct/escrow-payment.cjs.map +1 -1
  19. package/dist/direct/escrow-payment.d.ts +2 -2
  20. package/dist/direct/escrow-payment.js.map +1 -1
  21. package/dist/direct/personal-server-read.cjs +2 -2
  22. package/dist/direct/use-direct-vana-connect.cjs +2 -1
  23. package/dist/direct/use-direct-vana-connect.cjs.map +1 -1
  24. package/dist/direct/use-direct-vana-connect.d.ts +3 -1
  25. package/dist/direct/use-direct-vana-connect.js +2 -1
  26. package/dist/direct/use-direct-vana-connect.js.map +1 -1
  27. package/dist/error-entry-points.test.d.ts +1 -0
  28. package/dist/errors.cjs +7 -0
  29. package/dist/errors.cjs.map +1 -1
  30. package/dist/errors.d.ts +10 -0
  31. package/dist/errors.js +6 -0
  32. package/dist/errors.js.map +1 -1
  33. package/dist/index.browser.d.ts +4 -4
  34. package/dist/index.browser.js +882 -518
  35. package/dist/index.browser.js.map +4 -4
  36. package/dist/index.node.cjs +1035 -705
  37. package/dist/index.node.cjs.map +4 -4
  38. package/dist/index.node.d.ts +4 -4
  39. package/dist/index.node.js +989 -567
  40. package/dist/index.node.js.map +4 -4
  41. package/dist/protocol/data-point-deletion.cjs +1 -1
  42. package/dist/protocol/derivative-questions.cjs +1 -1
  43. package/dist/protocol/derivative-status.cjs +1 -1
  44. package/dist/protocol/eip712.cjs +28 -2
  45. package/dist/protocol/eip712.cjs.map +1 -1
  46. package/dist/protocol/eip712.d.ts +70 -0
  47. package/dist/protocol/eip712.js +24 -1
  48. package/dist/protocol/eip712.js.map +1 -1
  49. package/dist/protocol/escrow.cjs +154 -2
  50. package/dist/protocol/escrow.cjs.map +1 -1
  51. package/dist/protocol/escrow.d.ts +145 -2
  52. package/dist/protocol/escrow.js +152 -1
  53. package/dist/protocol/escrow.js.map +1 -1
  54. package/dist/protocol/fixtures/moksha-identity.json +20 -0
  55. package/dist/protocol/gateway.cjs +1 -1
  56. package/dist/protocol/gateway.cjs.map +1 -1
  57. package/dist/protocol/gateway.d.ts +8 -38
  58. package/dist/protocol/gateway.js.map +1 -1
  59. package/dist/protocol/identity.cjs +7 -2
  60. package/dist/protocol/identity.cjs.map +1 -1
  61. package/dist/protocol/identity.js +7 -2
  62. package/dist/protocol/identity.js.map +1 -1
  63. package/dist/protocol/jobs-client.cjs +73 -21
  64. package/dist/protocol/jobs-client.cjs.map +1 -1
  65. package/dist/protocol/jobs-client.d.ts +7 -5
  66. package/dist/protocol/jobs-client.js +74 -21
  67. package/dist/protocol/jobs-client.js.map +1 -1
  68. package/dist/protocol/jobs.cjs +0 -3
  69. package/dist/protocol/jobs.cjs.map +1 -1
  70. package/dist/protocol/jobs.d.ts +21 -13
  71. package/dist/protocol/jobs.js +0 -2
  72. package/dist/protocol/jobs.js.map +1 -1
  73. package/dist/protocol/lineage.cjs +1 -1
  74. package/dist/protocol/personal-server-data.cjs +1 -1
  75. package/dist/protocol/personal-server-write.cjs +1 -1
  76. package/dist/protocol/write-request.cjs +1 -1
  77. package/dist/protocol/write-signer.cjs +1 -1
  78. package/dist/react.cjs.map +1 -1
  79. package/dist/react.d.ts +1 -1
  80. package/dist/react.js.map +1 -1
  81. package/dist/session-relay/client.cjs +1 -1
  82. package/dist/session-relay/errors.cjs +1 -1
  83. package/dist/session-relay/index.cjs +1 -1
  84. package/package.json +1 -1
@@ -20,6 +20,7 @@ var __copyProps = (to, from, except, desc) => {
20
20
  }
21
21
  return to;
22
22
  };
23
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
23
24
  var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
25
  // If the importer is in node compatibility mode or this is not an ESM
25
26
  // file that has been converted to a CommonJS file using a Babel-
@@ -1178,14 +1179,11 @@ __export(index_node_exports, {
1178
1179
  AccountPersonalServerLiteOwnerBindingError: () => AccountPersonalServerLiteOwnerBindingError,
1179
1180
  AccountPersonalServerRegistrationError: () => AccountPersonalServerRegistrationError,
1180
1181
  BUILDER_REGISTRATION_TYPES: () => BUILDER_REGISTRATION_TYPES,
1181
- BlockchainError: () => BlockchainError,
1182
1182
  BrowserPlatformAdapter: () => BrowserPlatformAdapter,
1183
- BuilderUnknownError: () => BuilderUnknownError,
1184
1183
  CLAIM_POLL_FLOOR_MS: () => CLAIM_POLL_FLOOR_MS,
1185
1184
  CONTRACTS: () => CONTRACTS,
1186
1185
  CallbackStorage: () => CallbackStorage,
1187
1186
  ContractFactory: () => ContractFactory,
1188
- ContractNotFoundError: () => ContractNotFoundError,
1189
1187
  DATA_ACCESS_OP_TYPE: () => DATA_ACCESS_OP_TYPE,
1190
1188
  DATA_REGISTRY_STATUS_ABI: () => DATA_REGISTRY_STATUS_ABI,
1191
1189
  DEFAULT_DERIVATIVE_STATUS_POLL_INTERVAL_MS: () => DEFAULT_DERIVATIVE_STATUS_POLL_INTERVAL_MS,
@@ -1198,21 +1196,9 @@ __export(index_node_exports, {
1198
1196
  DERIVATIVE_QUESTIONS_PATH: () => DERIVATIVE_QUESTIONS_PATH,
1199
1197
  DERIVATIVE_STATUS_PATH: () => DERIVATIVE_STATUS_PATH,
1200
1198
  DataFileEnvelopeSchema: () => DataFileEnvelopeSchema,
1201
- DataPointDeletedError: () => DataPointDeletedError,
1202
- DataPointNotFoundError: () => DataPointNotFoundError,
1203
1199
  DataPointStatus: () => DataPointStatus,
1204
- DataPointVersionConflictError: () => DataPointVersionConflictError,
1205
- DerivativeComputeUnavailableError: () => DerivativeComputeUnavailableError,
1206
- DerivativeCycleError: () => DerivativeCycleError,
1207
- DerivativeDerivedScopeRequiredError: () => DerivativeDerivedScopeRequiredError,
1208
1200
  DerivativeErrorCodeSchema: () => DerivativeErrorCodeSchema,
1209
- DerivativeQuestionFailedError: () => DerivativeQuestionFailedError,
1210
- DerivativeQuestionInvalidError: () => DerivativeQuestionInvalidError,
1211
- DerivativeQuestionNotFoundError: () => DerivativeQuestionNotFoundError,
1212
- DerivativeQuestionRejectedError: () => DerivativeQuestionRejectedError,
1213
1201
  DerivativeQuestionSchema: () => DerivativeQuestionSchema,
1214
- DerivativeQuestionTimeoutError: () => DerivativeQuestionTimeoutError,
1215
- DerivativeSourceNotGrantedError: () => DerivativeSourceNotGrantedError,
1216
1202
  DerivativeStatusSchema: () => DerivativeStatusSchema,
1217
1203
  DropboxStorage: () => DropboxStorage,
1218
1204
  ECIESError: () => ECIESError,
@@ -1220,42 +1206,35 @@ __export(index_node_exports, {
1220
1206
  ENCLAVE_TRUST_ANCHORS: () => ENCLAVE_TRUST_ANCHORS,
1221
1207
  ENCLAVE_WALLET_PURPOSE: () => ENCLAVE_WALLET_PURPOSE,
1222
1208
  ESCROW_DEPOSIT_ABI: () => ESCROW_DEPOSIT_ABI2,
1223
- ExpiredTokenError: () => ExpiredTokenError,
1209
+ EscrowWithdrawalLifecycleError: () => EscrowWithdrawalLifecycleError,
1210
+ EscrowWithdrawalRejectionError: () => EscrowWithdrawalRejectionError,
1211
+ ExpiredTokenError: () => import_errors14.ExpiredTokenError,
1224
1212
  FEE_REGISTRY_ABI: () => FEE_REGISTRY_ABI,
1225
1213
  GENERIC_PAYMENT_TYPES: () => GENERIC_PAYMENT_TYPES,
1226
1214
  GRANT_OP_TYPE: () => GRANT_OP_TYPE,
1227
1215
  GRANT_REGISTRATION_TYPES: () => GRANT_REGISTRATION_TYPES,
1228
1216
  GRANT_REVOCATION_TYPES: () => GRANT_REVOCATION_TYPES,
1229
1217
  GoogleDriveStorage: () => GoogleDriveStorage,
1230
- GrantInvalidError: () => GrantInvalidError,
1231
1218
  InMemoryTokenStore: () => InMemoryTokenStore,
1232
1219
  IngestResponseSchema: () => IngestResponseSchema,
1233
- InvalidConfigurationError: () => InvalidConfigurationError,
1234
1220
  InvalidScopeEntryError: () => InvalidScopeEntryError,
1235
- InvalidSignatureError: () => InvalidSignatureError,
1221
+ InvalidSignatureError: () => import_errors14.InvalidSignatureError,
1236
1222
  IpfsStorage: () => IpfsStorage,
1237
1223
  JOB_OPERATIONS: () => JOB_OPERATIONS,
1238
1224
  JOB_PROTOCOL_VERSION: () => JOB_PROTOCOL_VERSION,
1225
+ JOB_RESULT_CHUNK_BYTES: () => JOB_RESULT_CHUNK_BYTES,
1226
+ JOB_RESULT_FORMAT_VERSION: () => JOB_RESULT_FORMAT_VERSION,
1239
1227
  JOB_STATES: () => JOB_STATES,
1240
1228
  JobEnvelopeError: () => JobEnvelopeError,
1241
- JobIdTakenError: () => JobIdTakenError,
1242
- JobNotFoundError: () => JobNotFoundError,
1243
- JobRejectedError: () => JobRejectedError,
1244
- JobRequestTooLargeError: () => JobRequestTooLargeError,
1245
- JobTimeoutError: () => JobTimeoutError,
1246
- JobTransportError: () => JobTransportError,
1247
- JobsClientError: () => JobsClientError,
1248
1229
  LINEAGE_FIELD: () => LINEAGE_FIELD,
1249
1230
  LINEAGE_KEY: () => LINEAGE_KEY,
1250
1231
  LineageEntrySchema: () => LineageEntrySchema,
1251
1232
  LineageGraphSchema: () => LineageGraphSchema,
1252
1233
  LineageNodeSchema: () => LineageNodeSchema,
1253
- LineageReadError: () => LineageReadError,
1254
1234
  MASTER_KEY_MESSAGE: () => MASTER_KEY_MESSAGE,
1255
1235
  MASTER_SIGNATURE_DELIVERY_MAX_AGE_SECONDS: () => MASTER_SIGNATURE_DELIVERY_MAX_AGE_SECONDS,
1256
1236
  MASTER_SIGNATURE_DELIVERY_VERSION: () => MASTER_SIGNATURE_DELIVERY_VERSION,
1257
1237
  MAX_ATTEMPTS: () => MAX_ATTEMPTS,
1258
- MAX_INLINE_RESULT_BYTES: () => MAX_INLINE_RESULT_BYTES,
1259
1238
  MAX_JOB_DEADLINE_SECONDS: () => MAX_JOB_DEADLINE_SECONDS,
1260
1239
  MAX_LEASE_SECONDS: () => MAX_LEASE_SECONDS,
1261
1240
  MAX_LINEAGE_SOURCES: () => MAX_LINEAGE_SOURCES,
@@ -1263,15 +1242,12 @@ __export(index_node_exports, {
1263
1242
  MAX_QUESTION_MODEL_CHARS: () => MAX_QUESTION_MODEL_CHARS,
1264
1243
  MAX_QUESTION_SOURCE_SCOPES: () => MAX_QUESTION_SOURCE_SCOPES,
1265
1244
  MAX_WAIT_SECONDS: () => MAX_WAIT_SECONDS,
1266
- MissingAuthError: () => MissingAuthError,
1245
+ MissingAuthError: () => import_errors14.MissingAuthError,
1267
1246
  NATIVE_ASSET_ADDRESS: () => NATIVE_ASSET_ADDRESS,
1268
1247
  NATIVE_VANA_ASSET: () => NATIVE_VANA_ASSET,
1269
- NetworkError: () => NetworkError,
1270
1248
  NodeECIESProvider: () => NodeECIESUint8Provider,
1271
1249
  NodePlatformAdapter: () => NodePlatformAdapter,
1272
- NonceError: () => NonceError,
1273
1250
  OAuthClient: () => OAuthClient,
1274
- OwnerNotReadyError: () => OwnerNotReadyError,
1275
1251
  PERSONAL_SERVER_LITE_OWNER_BINDING_PREFIX: () => PERSONAL_SERVER_LITE_OWNER_BINDING_PREFIX,
1276
1252
  PERSONAL_SERVER_LITE_OWNER_BINDING_PURPOSE: () => PERSONAL_SERVER_LITE_OWNER_BINDING_PURPOSE,
1277
1253
  PERSONAL_SERVER_LITE_OWNER_BINDING_VERSION: () => PERSONAL_SERVER_LITE_OWNER_BINDING_VERSION,
@@ -1280,9 +1256,6 @@ __export(index_node_exports, {
1280
1256
  PKCE_CHALLENGE_PATTERN: () => PKCE_CHALLENGE_PATTERN,
1281
1257
  PKCE_VERIFIER_PATTERN: () => PKCE_VERIFIER_PATTERN,
1282
1258
  PSError: () => PSError,
1283
- PermissionError: () => PermissionError,
1284
- PersonalServerError: () => PersonalServerError,
1285
- PersonalServerWriteError: () => PersonalServerWriteError,
1286
1259
  PinataStorage: () => PinataStorage,
1287
1260
  QUESTION_STATUSES: () => QUESTION_STATUSES,
1288
1261
  QuestionDeleteResultSchema: () => QuestionDeleteResultSchema,
@@ -1293,42 +1266,26 @@ __export(index_node_exports, {
1293
1266
  RECORD_DATA_ACCESS_TYPES: () => RECORD_DATA_ACCESS_TYPES,
1294
1267
  REGISTRATION_KIND_FOR_OP: () => REGISTRATION_KIND_FOR_OP,
1295
1268
  RESERVED_WRITE_KEYS: () => RESERVED_WRITE_KEYS,
1296
- ReadOnlyError: () => ReadOnlyError,
1297
1269
  RedactedLineageNodeSchema: () => RedactedLineageNodeSchema,
1298
- RelayerError: () => RelayerError,
1299
1270
  SCOPE_ACTIONS: () => SCOPE_ACTIONS,
1300
1271
  SEALED_ENVELOPE_VERSION: () => SEALED_ENVELOPE_VERSION,
1301
1272
  SERVER_REGISTRATION_TYPES: () => SERVER_REGISTRATION_TYPES,
1302
1273
  ScopeSchema: () => ScopeSchema,
1303
- SerializationError: () => SerializationError,
1304
- ServerUrlMismatchError: () => ServerUrlMismatchError,
1305
- SignatureError: () => SignatureError,
1306
1274
  StorageError: () => StorageError,
1307
1275
  StorageManager: () => StorageManager,
1308
1276
  TOMBSTONE_DATA_HASH: () => TOMBSTONE_DATA_HASH,
1309
1277
  TOMBSTONE_DATA_HASH_PREIMAGE: () => TOMBSTONE_DATA_HASH_PREIMAGE,
1310
1278
  TOMBSTONE_METADATA_HASH: () => TOMBSTONE_METADATA_HASH,
1311
1279
  TOMBSTONE_METADATA_HASH_PREIMAGE: () => TOMBSTONE_METADATA_HASH_PREIMAGE,
1312
- TransactionPendingError: () => TransactionPendingError,
1313
1280
  USER_PS_ID_DOMAIN: () => USER_PS_ID_DOMAIN,
1314
- UserRejectedRequestError: () => UserRejectedRequestError,
1315
- VanaError: () => VanaError,
1316
1281
  VanaStorage: () => VanaStorage,
1282
+ WITHDRAW_AUTHORIZATION_TYPES: () => WITHDRAW_AUTHORIZATION_TYPES,
1317
1283
  WRITER_ATTRIBUTION_KEY: () => WRITER_ATTRIBUTION_KEY,
1318
1284
  WRITE_CONTENT_DISPOSITION_HEADER: () => WRITE_CONTENT_DISPOSITION_HEADER,
1319
1285
  WRITE_FILENAME_HEADER: () => WRITE_FILENAME_HEADER,
1320
1286
  WRITE_METADATA_HEADER: () => WRITE_METADATA_HEADER,
1321
1287
  WRITE_SESSION_PATH: () => WRITE_SESSION_PATH,
1322
1288
  WRITE_SIGNATURE_HEADER: () => WRITE_SIGNATURE_HEADER,
1323
- WriteConflictError: () => WriteConflictError,
1324
- WriteForbiddenError: () => WriteForbiddenError,
1325
- WriteLineageError: () => WriteLineageError,
1326
- WriteRejectedError: () => WriteRejectedError,
1327
- WriteRequestError: () => WriteRequestError,
1328
- WriteSessionError: () => WriteSessionError,
1329
- WriteSessionExpiredError: () => WriteSessionExpiredError,
1330
- WriteTransportError: () => WriteTransportError,
1331
- WriteUnauthorizedError: () => WriteUnauthorizedError,
1332
1289
  appRootPreimage: () => appRootPreimage,
1333
1290
  askPersonalServer: () => askPersonalServer,
1334
1291
  assertDerivedScopeNaming: () => assertDerivedScopeNaming,
@@ -1351,6 +1308,7 @@ __export(index_node_exports, {
1351
1308
  buildPersonalServerRegistrationTypedData: () => buildPersonalServerRegistrationTypedData,
1352
1309
  buildSetDataPointStatusRequest: () => buildSetDataPointStatusRequest,
1353
1310
  buildWeb3SignedHeader: () => buildWeb3SignedHeader,
1311
+ buildWithdrawAuthorizationTypedData: () => buildWithdrawAuthorizationTypedData,
1354
1312
  builderRegistrationDomain: () => builderRegistrationDomain,
1355
1313
  canonicalJobRequestBytes: () => canonicalJobRequestBytes,
1356
1314
  chains: () => chains,
@@ -1433,6 +1391,7 @@ __export(index_node_exports, {
1433
1391
  normalizeBinaryMimeType: () => normalizeBinaryMimeType,
1434
1392
  openJobRequest: () => openJobRequest,
1435
1393
  openJobResult: () => openJobResult,
1394
+ openJobResultStream: () => openJobResultStream,
1436
1395
  openWriteSession: () => openWriteSession,
1437
1396
  parsePSError: () => parsePSError,
1438
1397
  parsePersonalServerPaymentRequired: () => parsePersonalServerPaymentRequired,
@@ -1458,6 +1417,7 @@ __export(index_node_exports, {
1458
1417
  scopeToPathSegments: () => scopeToPathSegments,
1459
1418
  sealJobRequest: () => sealJobRequest,
1460
1419
  sealJobResult: () => sealJobResult,
1420
+ sealJobResultStream: () => sealJobResultStream,
1461
1421
  serializeECIES: () => serializeECIES,
1462
1422
  serverRegistrationDomain: () => serverRegistrationDomain,
1463
1423
  sessionCoversScope: () => sessionCoversScope,
@@ -1476,351 +1436,12 @@ __export(index_node_exports, {
1476
1436
  verifyWeb3Signed: () => verifyWeb3Signed,
1477
1437
  waitForDerivativeStatus: () => waitForDerivativeStatus,
1478
1438
  waitForQuestion: () => waitForQuestion,
1439
+ withdrawAuthorizationDomain: () => withdrawAuthorizationDomain,
1479
1440
  writeData: () => writeData,
1480
1441
  writePersonalServerData: () => writePersonalServerData
1481
1442
  });
1482
1443
  module.exports = __toCommonJS(index_node_exports);
1483
-
1484
- // src/errors.ts
1485
- var VanaError = class extends Error {
1486
- constructor(message, code) {
1487
- super(message);
1488
- this.code = code;
1489
- this.name = this.constructor.name;
1490
- if (Error.captureStackTrace) {
1491
- Error.captureStackTrace(this, this.constructor);
1492
- }
1493
- }
1494
- code;
1495
- };
1496
- var RelayerError = class extends VanaError {
1497
- constructor(message, statusCode, response) {
1498
- super(message, "RELAYER_ERROR");
1499
- this.statusCode = statusCode;
1500
- this.response = response;
1501
- }
1502
- statusCode;
1503
- response;
1504
- };
1505
- var UserRejectedRequestError = class extends VanaError {
1506
- constructor(message = "User rejected the signature request") {
1507
- super(message, "USER_REJECTED_REQUEST");
1508
- }
1509
- };
1510
- var InvalidConfigurationError = class extends VanaError {
1511
- constructor(message) {
1512
- super(message, "INVALID_CONFIGURATION");
1513
- }
1514
- };
1515
- var ContractNotFoundError = class extends VanaError {
1516
- constructor(contractName, chainId) {
1517
- super(
1518
- `Contract ${contractName} not found on chain ${chainId}`,
1519
- "CONTRACT_NOT_FOUND"
1520
- );
1521
- }
1522
- };
1523
- var BlockchainError = class extends VanaError {
1524
- constructor(message, originalError) {
1525
- super(message, "BLOCKCHAIN_ERROR");
1526
- this.originalError = originalError;
1527
- }
1528
- originalError;
1529
- };
1530
- var SerializationError = class extends VanaError {
1531
- constructor(message) {
1532
- super(message, "SERIALIZATION_ERROR");
1533
- }
1534
- };
1535
- var SignatureError = class extends VanaError {
1536
- constructor(message, originalError) {
1537
- super(message, "SIGNATURE_ERROR");
1538
- this.originalError = originalError;
1539
- }
1540
- originalError;
1541
- };
1542
- var NetworkError = class extends VanaError {
1543
- constructor(message, originalError) {
1544
- super(message, "NETWORK_ERROR");
1545
- this.originalError = originalError;
1546
- }
1547
- originalError;
1548
- };
1549
- var NonceError = class extends VanaError {
1550
- constructor(message) {
1551
- super(message, "NONCE_ERROR");
1552
- }
1553
- };
1554
- var PersonalServerError = class extends VanaError {
1555
- constructor(message, originalError) {
1556
- super(message, "PERSONAL_SERVER_ERROR");
1557
- this.originalError = originalError;
1558
- }
1559
- originalError;
1560
- };
1561
- var ServerUrlMismatchError = class extends VanaError {
1562
- constructor(existingUrl, providedUrl, serverId) {
1563
- super(
1564
- `Server ${serverId} is already registered with URL "${existingUrl}". Cannot change to "${providedUrl}".`,
1565
- "SERVER_URL_MISMATCH"
1566
- );
1567
- this.existingUrl = existingUrl;
1568
- this.providedUrl = providedUrl;
1569
- this.serverId = serverId;
1570
- }
1571
- existingUrl;
1572
- providedUrl;
1573
- serverId;
1574
- };
1575
- var PermissionError = class extends VanaError {
1576
- constructor(message, originalError) {
1577
- super(message, "PERMISSION_ERROR");
1578
- this.originalError = originalError;
1579
- }
1580
- originalError;
1581
- };
1582
- var ReadOnlyError = class extends VanaError {
1583
- constructor(operation, suggestion = "Initialize the SDK with a walletClient to perform this operation") {
1584
- super(
1585
- `Operation '${operation}' requires a wallet client. ${suggestion}`,
1586
- "READ_ONLY_ERROR"
1587
- );
1588
- this.operation = operation;
1589
- this.suggestion = suggestion;
1590
- }
1591
- /** The operation that was attempted */
1592
- operation;
1593
- /** Suggested solution for fixing the error */
1594
- suggestion;
1595
- };
1596
- var TransactionPendingError = class extends VanaError {
1597
- constructor(operationId, message, lastKnownStatus) {
1598
- super(
1599
- `Transaction operation pending: ${message} (operationId: ${operationId})`,
1600
- "TRANSACTION_PENDING"
1601
- );
1602
- this.operationId = operationId;
1603
- this.lastKnownStatus = lastKnownStatus;
1604
- }
1605
- operationId;
1606
- lastKnownStatus;
1607
- /**
1608
- * Converts the error to a JSON-serializable format.
1609
- *
1610
- * @remarks
1611
- * Useful for logging, storage, or transmission of error details.
1612
- *
1613
- * @returns JSON representation of the error
1614
- */
1615
- toJSON() {
1616
- return {
1617
- name: this.name,
1618
- code: this.code,
1619
- message: this.message,
1620
- operationId: this.operationId,
1621
- lastKnownStatus: this.lastKnownStatus
1622
- };
1623
- }
1624
- };
1625
- var PersonalServerWriteError = class extends VanaError {
1626
- constructor(message, code, status, errorCode = null, details) {
1627
- super(message, code);
1628
- this.status = status;
1629
- this.errorCode = errorCode;
1630
- this.details = details;
1631
- }
1632
- status;
1633
- errorCode;
1634
- details;
1635
- };
1636
- var WriteRequestError = class extends PersonalServerWriteError {
1637
- constructor(message, details) {
1638
- super(message, "WRITE_INVALID_REQUEST", void 0, null, details);
1639
- }
1640
- };
1641
- var WriteTransportError = class extends PersonalServerWriteError {
1642
- constructor(message, attempts, cause) {
1643
- super(message, "WRITE_TRANSPORT_ERROR", void 0, null, { attempts });
1644
- this.attempts = attempts;
1645
- this.cause = cause;
1646
- }
1647
- attempts;
1648
- };
1649
- var WriteSessionError = class extends PersonalServerWriteError {
1650
- constructor(message, status, errorCode = null, details) {
1651
- super(message, "WRITE_SESSION_REJECTED", status, errorCode, details);
1652
- }
1653
- };
1654
- var WriteSessionExpiredError = class extends PersonalServerWriteError {
1655
- constructor(message, details) {
1656
- super(message, "WRITE_SESSION_EXPIRED", void 0, null, details);
1657
- }
1658
- };
1659
- var WriteUnauthorizedError = class extends PersonalServerWriteError {
1660
- constructor(message, errorCode = null, details) {
1661
- super(message, "WRITE_UNAUTHORIZED", 401, errorCode, details);
1662
- }
1663
- };
1664
- var WriteForbiddenError = class extends PersonalServerWriteError {
1665
- constructor(message, errorCode = null, details) {
1666
- super(message, "WRITE_FORBIDDEN", 403, errorCode, details);
1667
- }
1668
- };
1669
- var WriteConflictError = class extends PersonalServerWriteError {
1670
- constructor(message, errorCode = null, details) {
1671
- super(message, "WRITE_CONFLICT", 409, errorCode, details);
1672
- }
1673
- };
1674
- var WriteLineageError = class extends PersonalServerWriteError {
1675
- constructor(message, status = 422, errorCode = null, details) {
1676
- super(message, "WRITE_LINEAGE_REJECTED", status, errorCode, details);
1677
- }
1678
- };
1679
- var WriteRejectedError = class extends PersonalServerWriteError {
1680
- constructor(message, status, errorCode = null, details) {
1681
- super(message, "WRITE_REJECTED", status, errorCode, details);
1682
- }
1683
- };
1684
- var JobsClientError = class extends VanaError {
1685
- constructor(message, code, status, errorCode = null, details) {
1686
- super(message, code);
1687
- this.status = status;
1688
- this.errorCode = errorCode;
1689
- this.details = details;
1690
- }
1691
- status;
1692
- errorCode;
1693
- details;
1694
- };
1695
- var BuilderUnknownError = class extends JobsClientError {
1696
- constructor(message, details) {
1697
- super(message, "JOB_BUILDER_UNKNOWN", 403, "BUILDER_UNKNOWN", details);
1698
- }
1699
- };
1700
- var GrantInvalidError = class extends JobsClientError {
1701
- constructor(message, details) {
1702
- super(message, "JOB_GRANT_INVALID", 403, "GRANT_INVALID", details);
1703
- }
1704
- };
1705
- var OwnerNotReadyError = class extends JobsClientError {
1706
- constructor(message, details) {
1707
- super(message, "JOB_OWNER_NOT_READY", 403, "OWNER_NOT_READY", details);
1708
- }
1709
- };
1710
- var JobIdTakenError = class extends JobsClientError {
1711
- constructor(message, details) {
1712
- super(message, "JOB_ID_TAKEN", 409, "JOB_ID_TAKEN", details);
1713
- }
1714
- };
1715
- var JobNotFoundError = class extends JobsClientError {
1716
- constructor(message, details) {
1717
- super(message, "JOB_NOT_FOUND", 404, "JOB_NOT_FOUND", details);
1718
- }
1719
- };
1720
- var JobRequestTooLargeError = class extends JobsClientError {
1721
- constructor(message, errorCode = "BODY_TOO_LARGE", details) {
1722
- super(message, "JOB_REQUEST_TOO_LARGE", 413, errorCode, details);
1723
- }
1724
- };
1725
- var JobTimeoutError = class extends JobsClientError {
1726
- constructor(message, details) {
1727
- super(message, "JOB_TIMEOUT", void 0, null, details);
1728
- }
1729
- };
1730
- var JobRejectedError = class extends JobsClientError {
1731
- constructor(message, status, errorCode = null, details) {
1732
- super(message, "JOB_REJECTED", status, errorCode, details);
1733
- }
1734
- };
1735
- var JobTransportError = class extends JobsClientError {
1736
- constructor(message, cause) {
1737
- super(message, "JOB_TRANSPORT_ERROR");
1738
- this.cause = cause;
1739
- }
1740
- };
1741
- var LineageReadError = class extends VanaError {
1742
- constructor(message, status, errorCode = null, details) {
1743
- super(message, "LINEAGE_READ_ERROR");
1744
- this.status = status;
1745
- this.errorCode = errorCode;
1746
- this.details = details;
1747
- }
1748
- status;
1749
- errorCode;
1750
- details;
1751
- };
1752
- var DerivativeQuestionRejectedError = class extends PersonalServerWriteError {
1753
- constructor(message, status, errorCode = null, details) {
1754
- super(message, "DERIVATIVE_QUESTION_REJECTED", status, errorCode, details);
1755
- }
1756
- };
1757
- var DerivativeQuestionInvalidError = class extends PersonalServerWriteError {
1758
- constructor(message, status = 400, errorCode = null, details) {
1759
- super(message, "DERIVATIVE_QUESTION_INVALID", status, errorCode, details);
1760
- }
1761
- };
1762
- var DerivativeQuestionNotFoundError = class extends PersonalServerWriteError {
1763
- constructor(message, errorCode = null, details) {
1764
- super(message, "DERIVATIVE_QUESTION_NOT_FOUND", 404, errorCode, details);
1765
- }
1766
- };
1767
- var DerivativeDerivedScopeRequiredError = class extends PersonalServerWriteError {
1768
- constructor(message, errorCode = null, details) {
1769
- super(
1770
- message,
1771
- "DERIVATIVE_DERIVED_SCOPE_REQUIRED",
1772
- 400,
1773
- errorCode,
1774
- details
1775
- );
1776
- }
1777
- };
1778
- var DerivativeSourceNotGrantedError = class extends PersonalServerWriteError {
1779
- constructor(message, errorCode = null, details) {
1780
- super(message, "DERIVATIVE_SOURCE_NOT_GRANTED", 403, errorCode, details);
1781
- }
1782
- };
1783
- var DerivativeCycleError = class extends PersonalServerWriteError {
1784
- constructor(message, errorCode = null, details) {
1785
- super(message, "DERIVATIVE_CYCLE", 409, errorCode, details);
1786
- }
1787
- };
1788
- var DerivativeComputeUnavailableError = class extends PersonalServerWriteError {
1789
- constructor(message, errorCode = null, details) {
1790
- super(message, "DERIVATIVE_COMPUTE_UNAVAILABLE", 503, errorCode, details);
1791
- }
1792
- };
1793
- var DerivativeQuestionTimeoutError = class extends PersonalServerWriteError {
1794
- constructor(message, details) {
1795
- super(message, "DERIVATIVE_QUESTION_TIMEOUT", void 0, null, details);
1796
- }
1797
- };
1798
- var DerivativeQuestionFailedError = class extends PersonalServerWriteError {
1799
- constructor(message, details) {
1800
- super(message, "DERIVATIVE_QUESTION_FAILED", void 0, null, details);
1801
- }
1802
- };
1803
- var DataPointDeletedError = class extends VanaError {
1804
- constructor(message, details = {}) {
1805
- super(message, "DATA_POINT_DELETED");
1806
- this.details = details;
1807
- }
1808
- details;
1809
- };
1810
- var DataPointNotFoundError = class extends VanaError {
1811
- constructor(message, details = {}) {
1812
- super(message, "DATA_POINT_NOT_FOUND");
1813
- this.details = details;
1814
- }
1815
- details;
1816
- };
1817
- var DataPointVersionConflictError = class extends VanaError {
1818
- constructor(message, details = {}) {
1819
- super(message, "DATA_POINT_VERSION_CONFLICT");
1820
- this.details = details;
1821
- }
1822
- details;
1823
- };
1444
+ __reExport(index_node_exports, require("./errors.cjs"), module.exports);
1824
1445
 
1825
1446
  // src/contracts/contractController.ts
1826
1447
  var import_viem3 = require("viem");
@@ -32182,31 +31803,7 @@ async function decryptWithPassword(encrypted, password) {
32182
31803
 
32183
31804
  // src/auth/web3-signed.ts
32184
31805
  var import_viem13 = require("viem");
32185
-
32186
- // src/auth/errors.ts
32187
- var MissingAuthError = class extends VanaError {
32188
- constructor(message = "Missing authentication", details) {
32189
- super(message, "MISSING_AUTH");
32190
- this.details = details;
32191
- }
32192
- details;
32193
- };
32194
- var InvalidSignatureError = class extends VanaError {
32195
- constructor(details, message = "Invalid signature") {
32196
- super(message, "INVALID_SIGNATURE");
32197
- this.details = details;
32198
- }
32199
- details;
32200
- };
32201
- var ExpiredTokenError = class extends VanaError {
32202
- constructor(details, message = "Token has expired") {
32203
- super(message, "EXPIRED_TOKEN");
32204
- this.details = details;
32205
- }
32206
- details;
32207
- };
32208
-
32209
- // src/auth/web3-signed.ts
31806
+ var import_errors = require("./auth/errors.cjs");
32210
31807
  var WEB3_SIGNED_PREFIX = "Web3Signed ";
32211
31808
  var CLOCK_SKEW_SECONDS = 60;
32212
31809
  function base64urlDecode(input) {
@@ -32220,14 +31817,14 @@ function isFiniteNumber(value) {
32220
31817
  }
32221
31818
  function parsePayload(value) {
32222
31819
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
32223
- throw new InvalidSignatureError({ reason: "Invalid payload shape" });
31820
+ throw new import_errors.InvalidSignatureError({ reason: "Invalid payload shape" });
32224
31821
  }
32225
31822
  const payload = value;
32226
31823
  if (typeof payload["aud"] !== "string" || typeof payload["method"] !== "string" || typeof payload["uri"] !== "string" || typeof payload["bodyHash"] !== "string" || !isFiniteNumber(payload["iat"]) || !isFiniteNumber(payload["exp"])) {
32227
- throw new InvalidSignatureError({ reason: "Invalid payload claims" });
31824
+ throw new import_errors.InvalidSignatureError({ reason: "Invalid payload claims" });
32228
31825
  }
32229
31826
  if (payload["grantId"] !== void 0 && typeof payload["grantId"] !== "string") {
32230
- throw new InvalidSignatureError({ reason: "Invalid grantId claim" });
31827
+ throw new import_errors.InvalidSignatureError({ reason: "Invalid grantId claim" });
32231
31828
  }
32232
31829
  return {
32233
31830
  aud: payload["aud"],
@@ -32241,28 +31838,28 @@ function parsePayload(value) {
32241
31838
  }
32242
31839
  function parseWeb3SignedHeader(headerValue) {
32243
31840
  if (!headerValue) {
32244
- throw new MissingAuthError();
31841
+ throw new import_errors.MissingAuthError();
32245
31842
  }
32246
31843
  if (!headerValue.startsWith(WEB3_SIGNED_PREFIX)) {
32247
- throw new InvalidSignatureError({ reason: "Missing Web3Signed prefix" });
31844
+ throw new import_errors.InvalidSignatureError({ reason: "Missing Web3Signed prefix" });
32248
31845
  }
32249
31846
  const value = headerValue.slice(WEB3_SIGNED_PREFIX.length);
32250
31847
  const dotIndex = value.indexOf(".");
32251
31848
  if (dotIndex === -1 || dotIndex === 0 || dotIndex === value.length - 1) {
32252
- throw new InvalidSignatureError({ reason: "Invalid header format" });
31849
+ throw new import_errors.InvalidSignatureError({ reason: "Invalid header format" });
32253
31850
  }
32254
31851
  const payloadBase64 = value.slice(0, dotIndex);
32255
31852
  const signatureStr = value.slice(dotIndex + 1);
32256
31853
  if (!signatureStr.startsWith("0x")) {
32257
- throw new InvalidSignatureError({ reason: "Invalid signature format" });
31854
+ throw new import_errors.InvalidSignatureError({ reason: "Invalid signature format" });
32258
31855
  }
32259
31856
  let payload;
32260
31857
  try {
32261
31858
  const decoded = base64urlDecode(payloadBase64);
32262
31859
  payload = parsePayload(JSON.parse(decoded));
32263
31860
  } catch (err) {
32264
- if (err instanceof InvalidSignatureError) throw err;
32265
- throw new InvalidSignatureError({ reason: "Invalid payload encoding" });
31861
+ if (err instanceof import_errors.InvalidSignatureError) throw err;
31862
+ throw new import_errors.InvalidSignatureError({ reason: "Invalid payload encoding" });
32266
31863
  }
32267
31864
  return {
32268
31865
  payloadBase64,
@@ -32281,24 +31878,24 @@ async function verifyWeb3Signed(params) {
32281
31878
  signature
32282
31879
  });
32283
31880
  } catch {
32284
- throw new InvalidSignatureError({ reason: "Signature recovery failed" });
31881
+ throw new import_errors.InvalidSignatureError({ reason: "Signature recovery failed" });
32285
31882
  }
32286
31883
  if (payload.aud !== params.expectedOrigin) {
32287
- throw new InvalidSignatureError({
31884
+ throw new import_errors.InvalidSignatureError({
32288
31885
  reason: "Audience mismatch",
32289
31886
  expected: params.expectedOrigin,
32290
31887
  actual: payload.aud
32291
31888
  });
32292
31889
  }
32293
31890
  if (payload.method !== params.expectedMethod) {
32294
- throw new InvalidSignatureError({
31891
+ throw new import_errors.InvalidSignatureError({
32295
31892
  reason: "Method mismatch",
32296
31893
  expected: params.expectedMethod,
32297
31894
  actual: payload.method
32298
31895
  });
32299
31896
  }
32300
31897
  if (payload.uri !== params.expectedPath) {
32301
- throw new InvalidSignatureError({
31898
+ throw new import_errors.InvalidSignatureError({
32302
31899
  reason: "URI mismatch",
32303
31900
  expected: params.expectedPath,
32304
31901
  actual: payload.uri
@@ -32307,7 +31904,7 @@ async function verifyWeb3Signed(params) {
32307
31904
  if (params.bodyBytes !== void 0) {
32308
31905
  const expectedBodyHash = computeBodyHash(params.bodyBytes);
32309
31906
  if (payload.bodyHash !== expectedBodyHash) {
32310
- throw new InvalidSignatureError({
31907
+ throw new import_errors.InvalidSignatureError({
32311
31908
  reason: "Body hash mismatch",
32312
31909
  expected: expectedBodyHash,
32313
31910
  actual: payload.bodyHash
@@ -32316,14 +31913,17 @@ async function verifyWeb3Signed(params) {
32316
31913
  }
32317
31914
  const now = params.now ?? Math.floor(Date.now() / 1e3);
32318
31915
  if (payload.exp < now - CLOCK_SKEW_SECONDS) {
32319
- throw new ExpiredTokenError({ reason: "Token expired" });
31916
+ throw new import_errors.ExpiredTokenError({ reason: "Token expired" });
32320
31917
  }
32321
31918
  if (payload.iat > now + CLOCK_SKEW_SECONDS) {
32322
- throw new ExpiredTokenError({ reason: "Token issued in the future" });
31919
+ throw new import_errors.ExpiredTokenError({ reason: "Token issued in the future" });
32323
31920
  }
32324
31921
  return { signer, payload };
32325
31922
  }
32326
31923
 
31924
+ // src/index.node.ts
31925
+ var import_errors14 = require("./auth/errors.cjs");
31926
+
32327
31927
  // src/auth/pkce.ts
32328
31928
  var PKCE_VERIFIER_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
32329
31929
  var PKCE_VERIFIER_MIN_LENGTH = 43;
@@ -32691,6 +32291,9 @@ function escrowPaymentDomain(config) {
32691
32291
  config.contracts.dataPortabilityEscrow
32692
32292
  );
32693
32293
  }
32294
+ function withdrawAuthorizationDomain(config) {
32295
+ return escrowPaymentDomain(config);
32296
+ }
32694
32297
  var GRANT_REGISTRATION_TYPES = {
32695
32298
  GrantRegistration: [
32696
32299
  { name: "grantorAddress", type: "address" },
@@ -32723,6 +32326,15 @@ var BUILDER_REGISTRATION_TYPES = {
32723
32326
  { name: "appUrl", type: "string" }
32724
32327
  ]
32725
32328
  };
32329
+ var WITHDRAW_AUTHORIZATION_TYPES = {
32330
+ WithdrawAuthorization: [
32331
+ { name: "account", type: "address" },
32332
+ { name: "asset", type: "address" },
32333
+ { name: "amount", type: "uint256" },
32334
+ { name: "withdrawNonce", type: "uint256" },
32335
+ { name: "deadline", type: "uint256" }
32336
+ ]
32337
+ };
32726
32338
  var ADD_DATA_TYPES = {
32727
32339
  AddData: [
32728
32340
  { name: "ownerAddress", type: "address" },
@@ -32741,6 +32353,14 @@ var RECORD_DATA_ACCESS_TYPES = {
32741
32353
  { name: "recordId", type: "bytes32" }
32742
32354
  ]
32743
32355
  };
32356
+ function buildWithdrawAuthorizationTypedData(config, message) {
32357
+ return {
32358
+ domain: withdrawAuthorizationDomain(config),
32359
+ types: WITHDRAW_AUTHORIZATION_TYPES,
32360
+ primaryType: "WithdrawAuthorization",
32361
+ message
32362
+ };
32363
+ }
32744
32364
 
32745
32365
  // src/protocol/identity.ts
32746
32366
  var secp256k14 = __toESM(require("@noble/secp256k1"), 1);
@@ -32769,8 +32389,13 @@ function emptyAnchor() {
32769
32389
  var ENCLAVE_TRUST_ANCHORS = Object.freeze({
32770
32390
  // filled at fleet provisioning; verify fails closed while empty
32771
32391
  [VANA_MAINNET_CHAIN_ID]: emptyAnchor(),
32772
- // filled at fleet provisioning; verify fails closed while empty
32773
- [MOKSHA_CHAIN_ID]: emptyAnchor()
32392
+ // Moksha workers share this dstack app and KMS root; the controller does not derive owner keys.
32393
+ [MOKSHA_CHAIN_ID]: Object.freeze({
32394
+ kmsRootPubkey: "0x0434c76e0c3f52ec64cbf9bbf5c910c272330166fd656c0a86bb330963e46910e1a0e6fa51bec74be2f9129342707636060d85856d102cee8290185409ecf7422f",
32395
+ appIds: Object.freeze([
32396
+ "0xec9a39de98c760e1ded9f1e97016dc5f0e357cf2"
32397
+ ])
32398
+ })
32774
32399
  });
32775
32400
  function userPsId(chainId, ownerAddress) {
32776
32401
  const packed = (0, import_viem14.encodePacked)(
@@ -32917,21 +32542,36 @@ var MAX_LEASE_SECONDS = 300;
32917
32542
  var MAX_ATTEMPTS = 3;
32918
32543
  var MAX_WAIT_SECONDS = 25;
32919
32544
  var CLAIM_POLL_FLOOR_MS = 1e3;
32920
- var MAX_INLINE_RESULT_BYTES = 1048576;
32921
32545
  var DEFAULT_JOB_DEADLINE_SECONDS = 600;
32922
32546
  var MAX_JOB_DEADLINE_SECONDS = 3600;
32923
32547
 
32924
32548
  // src/protocol/jobs-client.ts
32925
32549
  var import_node_crypto = require("node:crypto");
32550
+ var import_sha26 = require("@noble/hashes/sha2");
32926
32551
  var import_viem16 = require("viem");
32927
32552
  var import_accounts2 = require("viem/accounts");
32928
32553
 
32929
32554
  // src/crypto/envelope/job.ts
32930
32555
  var import_sha25 = require("@noble/hashes/sha2");
32931
32556
  var import_viem15 = require("viem");
32557
+ init_constants();
32932
32558
  init_interface();
32933
32559
  var textDecoder = new TextDecoder();
32934
32560
  var textEncoder = new TextEncoder();
32561
+ var MAX_JOB_RESULT_HEADER_BYTES = 4096;
32562
+ var WRAPPED_KEY_LENGTH_BYTES = 4;
32563
+ var FRAME_LENGTH_BYTES = 4;
32564
+ var FRAME_FLAGS_BYTES = 1;
32565
+ var AES_KEY_BYTES = 32;
32566
+ var AES_GCM_NONCE_BYTES = 12;
32567
+ var AES_GCM_TAG_BYTES = 16;
32568
+ var WRAPPED_METADATA_LENGTH_BYTES = 4;
32569
+ var WRAPPED_KEY_PLAINTEXT_PREFIX_BYTES = AES_KEY_BYTES + AES_GCM_NONCE_BYTES + WRAPPED_METADATA_LENGTH_BYTES;
32570
+ var MAX_WRAPPED_KEY_BYTES = 8192;
32571
+ var FINAL_FRAME_FLAG = 1;
32572
+ var MAX_CHUNK_INDEX = 4294967295;
32573
+ var JOB_RESULT_FORMAT_VERSION = 2;
32574
+ var JOB_RESULT_CHUNK_BYTES = 1024 * 1024;
32935
32575
  var JobEnvelopeError = class extends Error {
32936
32576
  constructor(message) {
32937
32577
  super(message);
@@ -32963,21 +32603,68 @@ function requestPlaintext(envelope) {
32963
32603
  validateRequestEnvelope(envelope);
32964
32604
  return canonicalJsonBytes(envelope);
32965
32605
  }
32966
- function resultPlaintext(result) {
32967
- return textEncoder.encode(
32968
- JSON.stringify({
32969
- v: result.v,
32970
- jobId: result.jobId,
32971
- scope: result.scope,
32972
- version: result.version,
32973
- contentType: result.contentType,
32974
- body: result.body
32975
- })
32976
- );
32606
+ function resultMetadata(result) {
32607
+ return {
32608
+ v: result.v,
32609
+ jobId: result.jobId,
32610
+ scope: result.scope,
32611
+ version: result.version,
32612
+ contentType: result.contentType
32613
+ };
32977
32614
  }
32978
32615
  function encryptedBytesToBase64(encrypted) {
32979
32616
  return toBase64((0, import_viem15.fromHex)(`0x${serializeECIES(encrypted)}`, "bytes"));
32980
32617
  }
32618
+ function encryptedToBytes(encrypted) {
32619
+ const bytes = new Uint8Array(
32620
+ encrypted.iv.length + encrypted.ephemPublicKey.length + encrypted.ciphertext.length + encrypted.mac.length
32621
+ );
32622
+ let offset = 0;
32623
+ bytes.set(encrypted.iv, offset);
32624
+ offset += encrypted.iv.length;
32625
+ bytes.set(encrypted.ephemPublicKey, offset);
32626
+ offset += encrypted.ephemPublicKey.length;
32627
+ bytes.set(encrypted.ciphertext, offset);
32628
+ offset += encrypted.ciphertext.length;
32629
+ bytes.set(encrypted.mac, offset);
32630
+ return bytes;
32631
+ }
32632
+ function bytesToEncrypted(bytes) {
32633
+ const absoluteMinLength = FORMAT.IV_LENGTH + 1 + MAC.LENGTH + 1;
32634
+ if (bytes.length < absoluteMinLength) {
32635
+ throw new ECIESError(
32636
+ `Invalid ECIES data: too short (${bytes.length} bytes, minimum ${absoluteMinLength} bytes required)`,
32637
+ "DECRYPTION_FAILED"
32638
+ );
32639
+ }
32640
+ const prefix = bytes[FORMAT.EPHEMERAL_KEY_OFFSET];
32641
+ if (prefix !== CURVE.PREFIX.UNCOMPRESSED) {
32642
+ throw new ECIESError(
32643
+ `Invalid ephemeral public key: must be uncompressed format (0x04 prefix), got 0x${prefix.toString(16).padStart(2, "0")}`,
32644
+ "DECRYPTION_FAILED"
32645
+ );
32646
+ }
32647
+ const ephemKeySize = CURVE.UNCOMPRESSED_PUBLIC_KEY_LENGTH;
32648
+ const minLength = FORMAT.IV_LENGTH + ephemKeySize + MAC.LENGTH + 1;
32649
+ if (bytes.length < minLength) {
32650
+ throw new ECIESError(
32651
+ `Invalid ECIES data: too short (${bytes.length} bytes, minimum ${minLength} bytes required)`,
32652
+ "DECRYPTION_FAILED"
32653
+ );
32654
+ }
32655
+ return {
32656
+ iv: bytes.subarray(FORMAT.IV_OFFSET, FORMAT.IV_OFFSET + FORMAT.IV_LENGTH),
32657
+ ephemPublicKey: bytes.subarray(
32658
+ FORMAT.EPHEMERAL_KEY_OFFSET,
32659
+ FORMAT.EPHEMERAL_KEY_OFFSET + ephemKeySize
32660
+ ),
32661
+ ciphertext: bytes.subarray(
32662
+ FORMAT.EPHEMERAL_KEY_OFFSET + ephemKeySize,
32663
+ bytes.length - MAC.LENGTH
32664
+ ),
32665
+ mac: bytes.subarray(bytes.length - MAC.LENGTH)
32666
+ };
32667
+ }
32981
32668
  function base64ToEncrypted(ciphertext) {
32982
32669
  return deserializeECIES((0, import_viem15.toHex)(fromBase64(ciphertext)));
32983
32670
  }
@@ -33078,11 +32765,11 @@ function validateRequestEnvelope(value) {
33078
32765
  requireString(value.auth, "auth", "job request envelope");
33079
32766
  return value;
33080
32767
  }
33081
- function validateResult(value) {
33082
- requirePlainObject(value, "result", "job result");
32768
+ function validateResultMetadata(value) {
32769
+ requirePlainObject(value, "metadata", "job result");
33083
32770
  requireExactKeys(
33084
32771
  value,
33085
- ["v", "jobId", "scope", "version", "contentType", "body"],
32772
+ ["v", "jobId", "scope", "version", "contentType"],
33086
32773
  "job result"
33087
32774
  );
33088
32775
  if (value.v !== JOB_PROTOCOL_VERSION) {
@@ -33093,14 +32780,222 @@ function validateResult(value) {
33093
32780
  for (const field of ["jobId", "scope", "contentType"]) {
33094
32781
  requireString(value[field], field, "job result");
33095
32782
  }
33096
- if (typeof value.body !== "string") {
33097
- throw new JobEnvelopeError("Invalid job result: missing body");
33098
- }
33099
32783
  if (value.version !== null && typeof value.version !== "string") {
33100
32784
  throw new JobEnvelopeError("Invalid job result: missing version");
33101
32785
  }
33102
32786
  return value;
33103
32787
  }
32788
+ function validateResult(value) {
32789
+ requirePlainObject(value, "result", "job result");
32790
+ requireExactKeys(
32791
+ value,
32792
+ ["v", "jobId", "scope", "version", "contentType", "body"],
32793
+ "job result"
32794
+ );
32795
+ validateResultMetadata(resultMetadata(value));
32796
+ if (!(value.body instanceof Uint8Array)) {
32797
+ throw new JobEnvelopeError("Invalid job result: missing body");
32798
+ }
32799
+ return value;
32800
+ }
32801
+ function webCrypto() {
32802
+ if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.getRandomValues !== "function" || !globalThis.crypto.subtle) {
32803
+ throw new JobEnvelopeError(
32804
+ "Job result streaming requires the Web Crypto API"
32805
+ );
32806
+ }
32807
+ return globalThis.crypto;
32808
+ }
32809
+ function uint32(value) {
32810
+ const bytes = new Uint8Array(4);
32811
+ new DataView(bytes.buffer).setUint32(0, value);
32812
+ return bytes;
32813
+ }
32814
+ function readUint32(bytes, offset = 0) {
32815
+ return new DataView(bytes.buffer, bytes.byteOffset + offset, 4).getUint32(0);
32816
+ }
32817
+ function wrappedKeyPlaintext(contentKey, noncePrefix, metadataBytes) {
32818
+ const plaintext = new Uint8Array(
32819
+ WRAPPED_KEY_PLAINTEXT_PREFIX_BYTES + metadataBytes.length
32820
+ );
32821
+ plaintext.set(contentKey, 0);
32822
+ plaintext.set(noncePrefix, AES_KEY_BYTES);
32823
+ new DataView(plaintext.buffer).setUint32(
32824
+ AES_KEY_BYTES + AES_GCM_NONCE_BYTES,
32825
+ metadataBytes.length
32826
+ );
32827
+ plaintext.set(metadataBytes, WRAPPED_KEY_PLAINTEXT_PREFIX_BYTES);
32828
+ return plaintext;
32829
+ }
32830
+ function parseWrappedKeyPlaintext(plaintext) {
32831
+ if (plaintext.length < WRAPPED_KEY_PLAINTEXT_PREFIX_BYTES) {
32832
+ throw new JobEnvelopeError("Invalid job result: wrapped key is truncated");
32833
+ }
32834
+ const metadataLength = readUint32(
32835
+ plaintext,
32836
+ AES_KEY_BYTES + AES_GCM_NONCE_BYTES
32837
+ );
32838
+ if (metadataLength > MAX_JOB_RESULT_HEADER_BYTES) {
32839
+ throw new JobEnvelopeError(
32840
+ `Invalid job result: header exceeds ${MAX_JOB_RESULT_HEADER_BYTES} bytes`
32841
+ );
32842
+ }
32843
+ if (plaintext.length !== WRAPPED_KEY_PLAINTEXT_PREFIX_BYTES + metadataLength) {
32844
+ throw new JobEnvelopeError(
32845
+ "Invalid job result: header length exceeds payload"
32846
+ );
32847
+ }
32848
+ const metadataBytes = plaintext.slice(WRAPPED_KEY_PLAINTEXT_PREFIX_BYTES);
32849
+ const metadata = validateResultMetadata(
32850
+ parseObject(metadataBytes, "job result header")
32851
+ );
32852
+ return {
32853
+ contentKey: plaintext.slice(0, AES_KEY_BYTES),
32854
+ noncePrefix: plaintext.slice(
32855
+ AES_KEY_BYTES,
32856
+ AES_KEY_BYTES + AES_GCM_NONCE_BYTES
32857
+ ),
32858
+ metadataBytes,
32859
+ metadata
32860
+ };
32861
+ }
32862
+ async function importAesKey(contentKey, usage) {
32863
+ return webCrypto().subtle.importKey(
32864
+ "raw",
32865
+ contentKey,
32866
+ { name: "AES-GCM" },
32867
+ false,
32868
+ [usage]
32869
+ );
32870
+ }
32871
+ function chunkNonce(noncePrefix, chunkIndex) {
32872
+ if (chunkIndex > MAX_CHUNK_INDEX) {
32873
+ throw new JobEnvelopeError("Invalid job result: too many chunks");
32874
+ }
32875
+ const nonce = noncePrefix.slice();
32876
+ const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength);
32877
+ view.setUint32(8, view.getUint32(8) ^ chunkIndex);
32878
+ return nonce;
32879
+ }
32880
+ function chunkAad(metadataBytes, chunkIndex, final, plaintextLength) {
32881
+ const aad = new Uint8Array(14 + metadataBytes.length);
32882
+ aad[0] = JOB_RESULT_FORMAT_VERSION;
32883
+ aad.set(uint32(metadataBytes.length), 1);
32884
+ aad.set(metadataBytes, 5);
32885
+ aad.set(uint32(chunkIndex), 5 + metadataBytes.length);
32886
+ aad[9 + metadataBytes.length] = final ? FINAL_FRAME_FLAG : 0;
32887
+ aad.set(uint32(plaintextLength), 10 + metadataBytes.length);
32888
+ return aad;
32889
+ }
32890
+ async function encryptResultChunk(key, noncePrefix, metadataBytes, plaintext, chunkIndex, final) {
32891
+ const encrypted = new Uint8Array(
32892
+ await webCrypto().subtle.encrypt(
32893
+ {
32894
+ name: "AES-GCM",
32895
+ iv: chunkNonce(noncePrefix, chunkIndex),
32896
+ additionalData: chunkAad(
32897
+ metadataBytes,
32898
+ chunkIndex,
32899
+ final,
32900
+ plaintext.length
32901
+ ),
32902
+ tagLength: AES_GCM_TAG_BYTES * 8
32903
+ },
32904
+ key,
32905
+ plaintext
32906
+ )
32907
+ );
32908
+ const frame = new Uint8Array(
32909
+ FRAME_LENGTH_BYTES + FRAME_FLAGS_BYTES + encrypted.length
32910
+ );
32911
+ new DataView(frame.buffer).setUint32(0, encrypted.length);
32912
+ frame[FRAME_LENGTH_BYTES] = final ? FINAL_FRAME_FLAG : 0;
32913
+ frame.set(encrypted, FRAME_LENGTH_BYTES + FRAME_FLAGS_BYTES);
32914
+ return frame;
32915
+ }
32916
+ function verifyResultBindings(metadata, expect) {
32917
+ if (metadata.jobId !== expect.jobId) {
32918
+ throw new JobEnvelopeError(
32919
+ `Job result ID ${metadata.jobId} does not match expected job ID ${expect.jobId}`
32920
+ );
32921
+ }
32922
+ if (expect.scope !== void 0 && metadata.scope !== expect.scope) {
32923
+ throw new JobEnvelopeError(
32924
+ `Job result scope ${metadata.scope} does not match expected scope ${expect.scope}`
32925
+ );
32926
+ }
32927
+ if (expect.version !== void 0 && metadata.version !== expect.version) {
32928
+ throw new JobEnvelopeError(
32929
+ `Job result version ${String(metadata.version)} does not match expected version ${String(expect.version)}`
32930
+ );
32931
+ }
32932
+ }
32933
+ var ByteStreamReader = class {
32934
+ reader;
32935
+ current;
32936
+ offset = 0;
32937
+ ended = false;
32938
+ constructor(stream) {
32939
+ this.reader = stream.getReader();
32940
+ }
32941
+ async ensureBytes() {
32942
+ while (!this.current || this.offset === this.current.length) {
32943
+ if (this.ended) return false;
32944
+ const next = await this.reader.read();
32945
+ if (next.done) {
32946
+ this.ended = true;
32947
+ this.current = void 0;
32948
+ return false;
32949
+ }
32950
+ if (!(next.value instanceof Uint8Array)) {
32951
+ throw new JobEnvelopeError(
32952
+ "Invalid job result: stream yielded non-byte data"
32953
+ );
32954
+ }
32955
+ this.current = next.value;
32956
+ this.offset = 0;
32957
+ }
32958
+ return true;
32959
+ }
32960
+ async readExactOrNull(length) {
32961
+ if (!await this.ensureBytes()) return null;
32962
+ const bytes = new Uint8Array(length);
32963
+ let written = 0;
32964
+ while (written < length) {
32965
+ if (!await this.ensureBytes()) {
32966
+ throw new JobEnvelopeError("Invalid job result: truncated payload");
32967
+ }
32968
+ const available = this.current.length - this.offset;
32969
+ const count = Math.min(available, length - written);
32970
+ bytes.set(
32971
+ this.current.subarray(this.offset, this.offset + count),
32972
+ written
32973
+ );
32974
+ this.offset += count;
32975
+ written += count;
32976
+ }
32977
+ return bytes;
32978
+ }
32979
+ async readExact(length) {
32980
+ const bytes = await this.readExactOrNull(length);
32981
+ if (!bytes) {
32982
+ throw new JobEnvelopeError("Invalid job result: truncated payload");
32983
+ }
32984
+ return bytes;
32985
+ }
32986
+ async hasRemaining() {
32987
+ return this.ensureBytes();
32988
+ }
32989
+ async cancel(reason) {
32990
+ await this.reader.cancel(reason);
32991
+ }
32992
+ };
32993
+ function normalizeChunkError(error) {
32994
+ if (error instanceof JobEnvelopeError) return error;
32995
+ return new JobEnvelopeError(
32996
+ `Invalid job result: chunk authentication failed${error instanceof Error ? `: ${error.message}` : ""}`
32997
+ );
32998
+ }
33104
32999
  async function sealJobRequest(envelope, enclavePublicKey, ecies) {
33105
33000
  const encrypted = await ecies.encrypt(
33106
33001
  (0, import_viem15.fromHex)(enclavePublicKey, "bytes"),
@@ -33117,41 +33012,322 @@ async function openJobRequest(ciphertext, privateKey, ecies) {
33117
33012
  parseObject(plaintext, "job request envelope")
33118
33013
  );
33119
33014
  }
33120
- async function sealJobResult(result, builderPublicKey, ecies) {
33121
- validateResult(result);
33122
- const encrypted = await ecies.encrypt(
33015
+ async function sealJobResultStream(metadataValue, builderPublicKey, ecies) {
33016
+ const metadata = validateResultMetadata(metadataValue);
33017
+ const metadataBytes = canonicalJsonBytes(metadata);
33018
+ if (metadataBytes.length > MAX_JOB_RESULT_HEADER_BYTES) {
33019
+ throw new JobEnvelopeError(
33020
+ `Invalid job result: header exceeds ${MAX_JOB_RESULT_HEADER_BYTES} bytes`
33021
+ );
33022
+ }
33023
+ const crypto2 = webCrypto();
33024
+ const contentKey = crypto2.getRandomValues(new Uint8Array(AES_KEY_BYTES));
33025
+ const noncePrefix = crypto2.getRandomValues(
33026
+ new Uint8Array(AES_GCM_NONCE_BYTES)
33027
+ );
33028
+ const key = await importAesKey(contentKey, "encrypt");
33029
+ const keyPlaintext = wrappedKeyPlaintext(
33030
+ contentKey,
33031
+ noncePrefix,
33032
+ metadataBytes
33033
+ );
33034
+ const encryptedKey = await ecies.encrypt(
33123
33035
  (0, import_viem15.fromHex)(builderPublicKey, "bytes"),
33124
- resultPlaintext(result)
33036
+ keyPlaintext
33037
+ );
33038
+ contentKey.fill(0);
33039
+ keyPlaintext.fill(0);
33040
+ const wrappedKey = encryptedToBytes(encryptedKey);
33041
+ if (wrappedKey.length > MAX_WRAPPED_KEY_BYTES) {
33042
+ throw new JobEnvelopeError("Invalid job result: wrapped key is too large");
33043
+ }
33044
+ const header = new Uint8Array(
33045
+ 1 + WRAPPED_KEY_LENGTH_BYTES + wrappedKey.length
33125
33046
  );
33126
- const ciphertext = encryptedBytesToBase64(encrypted);
33127
- const bytes = fromBase64(ciphertext);
33128
- return { ciphertext, hash: (0, import_viem15.bytesToHex)((0, import_sha25.sha256)(bytes)), size: bytes.length };
33047
+ header[0] = JOB_RESULT_FORMAT_VERSION;
33048
+ new DataView(header.buffer).setUint32(1, wrappedKey.length);
33049
+ header.set(wrappedKey, 1 + WRAPPED_KEY_LENGTH_BYTES);
33050
+ let pending = new Uint8Array(JOB_RESULT_CHUNK_BYTES);
33051
+ let pendingLength = 0;
33052
+ let chunkIndex = 0;
33053
+ const transform = new TransformStream({
33054
+ async transform(chunk, controller) {
33055
+ if (!(chunk instanceof Uint8Array)) {
33056
+ throw new JobEnvelopeError(
33057
+ "Invalid job result: stream yielded non-byte data"
33058
+ );
33059
+ }
33060
+ let offset = 0;
33061
+ while (offset < chunk.length) {
33062
+ if (pendingLength === JOB_RESULT_CHUNK_BYTES) {
33063
+ controller.enqueue(
33064
+ await encryptResultChunk(
33065
+ key,
33066
+ noncePrefix,
33067
+ metadataBytes,
33068
+ pending,
33069
+ chunkIndex,
33070
+ false
33071
+ )
33072
+ );
33073
+ chunkIndex += 1;
33074
+ pending = new Uint8Array(JOB_RESULT_CHUNK_BYTES);
33075
+ pendingLength = 0;
33076
+ }
33077
+ const count = Math.min(
33078
+ chunk.length - offset,
33079
+ JOB_RESULT_CHUNK_BYTES - pendingLength
33080
+ );
33081
+ pending.set(chunk.subarray(offset, offset + count), pendingLength);
33082
+ pendingLength += count;
33083
+ offset += count;
33084
+ }
33085
+ },
33086
+ async flush(controller) {
33087
+ controller.enqueue(
33088
+ await encryptResultChunk(
33089
+ key,
33090
+ noncePrefix,
33091
+ metadataBytes,
33092
+ pending.subarray(0, pendingLength),
33093
+ chunkIndex,
33094
+ true
33095
+ )
33096
+ );
33097
+ }
33098
+ });
33099
+ return { header, transform };
33129
33100
  }
33130
- async function openJobResult(ciphertext, builderPrivateKey, ecies, expect) {
33131
- const plaintext = await ecies.decrypt(
33132
- (0, import_viem15.fromHex)(builderPrivateKey, "bytes"),
33133
- base64ToEncrypted(ciphertext)
33101
+ async function sealJobResult(result, builderPublicKey, ecies) {
33102
+ validateResult(result);
33103
+ const sealed = await sealJobResultStream(
33104
+ resultMetadata(result),
33105
+ builderPublicKey,
33106
+ ecies
33107
+ );
33108
+ const frameCount = Math.max(
33109
+ 1,
33110
+ Math.ceil(result.body.length / JOB_RESULT_CHUNK_BYTES)
33134
33111
  );
33135
- const result = validateResult(parseObject(plaintext, "job result"));
33136
- if (result.jobId !== expect.jobId) {
33112
+ const size = sealed.header.length + result.body.length + frameCount * (FRAME_LENGTH_BYTES + FRAME_FLAGS_BYTES + AES_GCM_TAG_BYTES);
33113
+ const bytes = new Uint8Array(size);
33114
+ bytes.set(sealed.header, 0);
33115
+ let outputOffset = sealed.header.length;
33116
+ const reader = sealed.transform.readable.getReader();
33117
+ const drain = (async () => {
33118
+ for (; ; ) {
33119
+ const next = await reader.read();
33120
+ if (next.done) break;
33121
+ bytes.set(next.value, outputOffset);
33122
+ outputOffset += next.value.length;
33123
+ }
33124
+ })();
33125
+ const writer = sealed.transform.writable.getWriter();
33126
+ const fill = (async () => {
33127
+ for (let offset = 0; offset < result.body.length; offset += JOB_RESULT_CHUNK_BYTES) {
33128
+ await writer.write(
33129
+ result.body.subarray(offset, offset + JOB_RESULT_CHUNK_BYTES)
33130
+ );
33131
+ }
33132
+ await writer.close();
33133
+ })();
33134
+ await Promise.all([drain, fill]);
33135
+ if (outputOffset !== bytes.length) {
33136
+ throw new JobEnvelopeError("Invalid job result: sealed size mismatch");
33137
+ }
33138
+ return { bytes, hash: (0, import_viem15.bytesToHex)((0, import_sha25.sha256)(bytes)), size };
33139
+ }
33140
+ async function openJobResultStream(bytesStream, builderPrivateKey, ecies, expect) {
33141
+ const reader = new ByteStreamReader(bytesStream);
33142
+ const headerPrefix = await reader.readExact(1 + WRAPPED_KEY_LENGTH_BYTES);
33143
+ const formatVersion = headerPrefix[0];
33144
+ if (formatVersion !== JOB_RESULT_FORMAT_VERSION) {
33137
33145
  throw new JobEnvelopeError(
33138
- `Job result ID ${result.jobId} does not match expected job ID ${expect.jobId}`
33146
+ `Unsupported job result format: ${String(formatVersion)}`
33139
33147
  );
33140
33148
  }
33141
- if (expect.scope !== void 0 && result.scope !== expect.scope) {
33149
+ const wrappedKeyLength = readUint32(headerPrefix, 1);
33150
+ if (wrappedKeyLength === 0 || wrappedKeyLength > MAX_WRAPPED_KEY_BYTES) {
33142
33151
  throw new JobEnvelopeError(
33143
- `Job result scope ${result.scope} does not match expected scope ${expect.scope}`
33152
+ "Invalid job result: invalid wrapped key length"
33144
33153
  );
33145
33154
  }
33146
- if (expect.version !== void 0 && result.version !== expect.version) {
33155
+ const wrappedKey = await reader.readExact(wrappedKeyLength);
33156
+ const keyPlaintext = await ecies.decrypt(
33157
+ (0, import_viem15.fromHex)(builderPrivateKey, "bytes"),
33158
+ bytesToEncrypted(wrappedKey)
33159
+ );
33160
+ const parsed = parseWrappedKeyPlaintext(keyPlaintext);
33161
+ verifyResultBindings(parsed.metadata, expect);
33162
+ const key = await importAesKey(parsed.contentKey, "decrypt");
33163
+ parsed.contentKey.fill(0);
33164
+ keyPlaintext.fill(0);
33165
+ let chunkIndex = 0;
33166
+ let finished = false;
33167
+ const body = new ReadableStream({
33168
+ async pull(controller) {
33169
+ if (finished) {
33170
+ controller.close();
33171
+ return;
33172
+ }
33173
+ try {
33174
+ const frameHeader = await reader.readExactOrNull(
33175
+ FRAME_LENGTH_BYTES + FRAME_FLAGS_BYTES
33176
+ );
33177
+ if (!frameHeader) {
33178
+ throw new JobEnvelopeError("Invalid job result: missing final chunk");
33179
+ }
33180
+ const encryptedLength = readUint32(frameHeader);
33181
+ if (encryptedLength < AES_GCM_TAG_BYTES || encryptedLength > JOB_RESULT_CHUNK_BYTES + AES_GCM_TAG_BYTES) {
33182
+ throw new JobEnvelopeError(
33183
+ "Invalid job result: invalid chunk length"
33184
+ );
33185
+ }
33186
+ const flags = frameHeader[FRAME_LENGTH_BYTES];
33187
+ if (flags !== 0 && flags !== FINAL_FRAME_FLAG) {
33188
+ throw new JobEnvelopeError("Invalid job result: invalid chunk flags");
33189
+ }
33190
+ const final = flags === FINAL_FRAME_FLAG;
33191
+ const plaintextLength = encryptedLength - AES_GCM_TAG_BYTES;
33192
+ if (!final && plaintextLength !== JOB_RESULT_CHUNK_BYTES) {
33193
+ throw new JobEnvelopeError(
33194
+ "Invalid job result: short non-final chunk"
33195
+ );
33196
+ }
33197
+ const encrypted = await reader.readExact(encryptedLength);
33198
+ const plaintext = new Uint8Array(
33199
+ await webCrypto().subtle.decrypt(
33200
+ {
33201
+ name: "AES-GCM",
33202
+ iv: chunkNonce(parsed.noncePrefix, chunkIndex),
33203
+ additionalData: chunkAad(
33204
+ parsed.metadataBytes,
33205
+ chunkIndex,
33206
+ final,
33207
+ plaintextLength
33208
+ ),
33209
+ tagLength: AES_GCM_TAG_BYTES * 8
33210
+ },
33211
+ key,
33212
+ encrypted
33213
+ )
33214
+ );
33215
+ if (plaintext.length !== plaintextLength) {
33216
+ throw new JobEnvelopeError(
33217
+ "Invalid job result: decrypted chunk length mismatch"
33218
+ );
33219
+ }
33220
+ chunkIndex += 1;
33221
+ if (final) {
33222
+ if (await reader.hasRemaining()) {
33223
+ throw new JobEnvelopeError(
33224
+ "Invalid job result: bytes follow final chunk"
33225
+ );
33226
+ }
33227
+ finished = true;
33228
+ }
33229
+ controller.enqueue(plaintext);
33230
+ if (finished) controller.close();
33231
+ } catch (error) {
33232
+ controller.error(normalizeChunkError(error));
33233
+ void reader.cancel(error).catch(() => void 0);
33234
+ }
33235
+ },
33236
+ cancel(reason) {
33237
+ return reader.cancel(reason);
33238
+ }
33239
+ });
33240
+ return { metadata: parsed.metadata, body };
33241
+ }
33242
+ function bufferedResultBodySize(sealedBytes) {
33243
+ if (sealedBytes.length < 1 + WRAPPED_KEY_LENGTH_BYTES) {
33244
+ throw new JobEnvelopeError("Invalid job result: truncated payload");
33245
+ }
33246
+ if (sealedBytes[0] !== JOB_RESULT_FORMAT_VERSION) {
33147
33247
  throw new JobEnvelopeError(
33148
- `Job result version ${String(result.version)} does not match expected version ${String(expect.version)}`
33248
+ `Unsupported job result format: ${String(sealedBytes[0])}`
33149
33249
  );
33150
33250
  }
33151
- return result;
33251
+ const wrappedKeyLength = readUint32(sealedBytes, 1);
33252
+ if (wrappedKeyLength === 0 || wrappedKeyLength > MAX_WRAPPED_KEY_BYTES) {
33253
+ throw new JobEnvelopeError(
33254
+ "Invalid job result: invalid wrapped key length"
33255
+ );
33256
+ }
33257
+ let offset = 1 + WRAPPED_KEY_LENGTH_BYTES + wrappedKeyLength;
33258
+ if (offset > sealedBytes.length) {
33259
+ throw new JobEnvelopeError("Invalid job result: truncated payload");
33260
+ }
33261
+ let bodySize = 0;
33262
+ let sawFinal = false;
33263
+ while (offset < sealedBytes.length) {
33264
+ if (sealedBytes.length - offset < FRAME_LENGTH_BYTES + FRAME_FLAGS_BYTES) {
33265
+ throw new JobEnvelopeError("Invalid job result: truncated payload");
33266
+ }
33267
+ const encryptedLength = readUint32(sealedBytes, offset);
33268
+ const flags = sealedBytes[offset + FRAME_LENGTH_BYTES];
33269
+ if (encryptedLength < AES_GCM_TAG_BYTES || encryptedLength > JOB_RESULT_CHUNK_BYTES + AES_GCM_TAG_BYTES || flags !== 0 && flags !== FINAL_FRAME_FLAG) {
33270
+ throw new JobEnvelopeError("Invalid job result: invalid chunk framing");
33271
+ }
33272
+ const plaintextLength = encryptedLength - AES_GCM_TAG_BYTES;
33273
+ if (flags === 0 && plaintextLength !== JOB_RESULT_CHUNK_BYTES) {
33274
+ throw new JobEnvelopeError("Invalid job result: short non-final chunk");
33275
+ }
33276
+ offset += FRAME_LENGTH_BYTES + FRAME_FLAGS_BYTES;
33277
+ if (encryptedLength > sealedBytes.length - offset) {
33278
+ throw new JobEnvelopeError("Invalid job result: truncated payload");
33279
+ }
33280
+ offset += encryptedLength;
33281
+ bodySize += plaintextLength;
33282
+ if (flags === FINAL_FRAME_FLAG) {
33283
+ sawFinal = true;
33284
+ if (offset !== sealedBytes.length) {
33285
+ throw new JobEnvelopeError(
33286
+ "Invalid job result: bytes follow final chunk"
33287
+ );
33288
+ }
33289
+ }
33290
+ }
33291
+ if (!sawFinal) {
33292
+ throw new JobEnvelopeError("Invalid job result: missing final chunk");
33293
+ }
33294
+ return bodySize;
33152
33295
  }
33296
+ async function openJobResult(sealedBytes, builderPrivateKey, ecies, expect) {
33297
+ const bodySize = bufferedResultBodySize(sealedBytes);
33298
+ const stream = new ReadableStream({
33299
+ start(controller) {
33300
+ controller.enqueue(sealedBytes);
33301
+ controller.close();
33302
+ }
33303
+ });
33304
+ const opened = await openJobResultStream(
33305
+ stream,
33306
+ builderPrivateKey,
33307
+ ecies,
33308
+ expect
33309
+ );
33310
+ const body = new Uint8Array(bodySize);
33311
+ let offset = 0;
33312
+ await opened.body.pipeTo(
33313
+ new WritableStream({
33314
+ write(chunk) {
33315
+ body.set(chunk, offset);
33316
+ offset += chunk.length;
33317
+ }
33318
+ })
33319
+ );
33320
+ if (offset !== body.length) {
33321
+ throw new JobEnvelopeError("Invalid job result: opened size mismatch");
33322
+ }
33323
+ return { ...opened.metadata, body };
33324
+ }
33325
+
33326
+ // src/protocol/jobs-client.ts
33327
+ var import_errors3 = require("./errors.cjs");
33153
33328
 
33154
33329
  // src/protocol/write-signer.ts
33330
+ var import_errors2 = require("./errors.cjs");
33155
33331
  function isRecord(value) {
33156
33332
  return value !== null && typeof value === "object";
33157
33333
  }
@@ -33168,7 +33344,7 @@ function resolveWriteSigner(source, options = {}) {
33168
33344
  if (isViemWriteWalletClient(source)) {
33169
33345
  const account = options.account ?? source.account;
33170
33346
  if (account === void 0) {
33171
- throw new WriteRequestError(
33347
+ throw new import_errors2.WriteRequestError(
33172
33348
  "Viem wallet client requires an account option or account property"
33173
33349
  );
33174
33350
  }
@@ -33184,7 +33360,7 @@ function resolveWriteSigner(source, options = {}) {
33184
33360
  };
33185
33361
  }
33186
33362
  if (!isRecord(source) || typeof source.signMessage !== "function") {
33187
- throw new WriteRequestError(
33363
+ throw new import_errors2.WriteRequestError(
33188
33364
  "signer must be a viem LocalAccount, a viem WalletClient, or a { signMessage } object"
33189
33365
  );
33190
33366
  }
@@ -33225,7 +33401,7 @@ function normalizeGateway(gatewayUrl) {
33225
33401
  try {
33226
33402
  const url = new URL(gatewayUrl);
33227
33403
  if (url.pathname !== "/" || url.search !== "" || url.hash !== "") {
33228
- throw new JobRejectedError(
33404
+ throw new import_errors3.JobRejectedError(
33229
33405
  "gatewayUrl must be an origin without a path, query, or fragment"
33230
33406
  );
33231
33407
  }
@@ -33234,8 +33410,8 @@ function normalizeGateway(gatewayUrl) {
33234
33410
  audience: url.origin
33235
33411
  };
33236
33412
  } catch (error) {
33237
- if (error instanceof JobRejectedError) throw error;
33238
- throw new JobRejectedError(
33413
+ if (error instanceof import_errors3.JobRejectedError) throw error;
33414
+ throw new import_errors3.JobRejectedError(
33239
33415
  "gatewayUrl must be an absolute URL",
33240
33416
  void 0,
33241
33417
  null,
@@ -33248,7 +33424,7 @@ function normalizeGateway(gatewayUrl) {
33248
33424
  function resolveFetch(fetchFn) {
33249
33425
  const resolved = fetchFn ?? globalThis.fetch;
33250
33426
  if (resolved === void 0) {
33251
- throw new JobRejectedError("No fetch implementation available");
33427
+ throw new import_errors3.JobRejectedError("No fetch implementation available");
33252
33428
  }
33253
33429
  return resolved;
33254
33430
  }
@@ -33260,7 +33436,7 @@ function sourcePublicKey(source) {
33260
33436
  }
33261
33437
  function resolveBuilder(options) {
33262
33438
  if (options.builderPrivateKey && options.builderAccount) {
33263
- throw new JobRejectedError(
33439
+ throw new import_errors3.JobRejectedError(
33264
33440
  "Provide builderPrivateKey or builderAccount, not both"
33265
33441
  );
33266
33442
  }
@@ -33268,12 +33444,12 @@ function resolveBuilder(options) {
33268
33444
  try {
33269
33445
  source = options.builderPrivateKey ? (0, import_accounts2.privateKeyToAccount)(options.builderPrivateKey) : options.builderAccount;
33270
33446
  } catch (error) {
33271
- throw new JobRejectedError("Invalid builder private key", void 0, null, {
33447
+ throw new import_errors3.JobRejectedError("Invalid builder private key", void 0, null, {
33272
33448
  cause: error instanceof Error ? error.message : String(error)
33273
33449
  });
33274
33450
  }
33275
33451
  if (!source) {
33276
- throw new JobRejectedError(
33452
+ throw new import_errors3.JobRejectedError(
33277
33453
  "builderPrivateKey or builderAccount is required"
33278
33454
  );
33279
33455
  }
@@ -33281,13 +33457,13 @@ function resolveBuilder(options) {
33281
33457
  try {
33282
33458
  signer = resolveWriteSigner(source);
33283
33459
  } catch (error) {
33284
- throw new JobRejectedError("Invalid builder signer", void 0, null, {
33460
+ throw new import_errors3.JobRejectedError("Invalid builder signer", void 0, null, {
33285
33461
  cause: error instanceof Error ? error.message : String(error)
33286
33462
  });
33287
33463
  }
33288
33464
  const publicKey = sourcePublicKey(source);
33289
33465
  if (!signer.address || !publicKey) {
33290
- throw new JobRejectedError(
33466
+ throw new import_errors3.JobRejectedError(
33291
33467
  "Builder signer must expose both address and publicKey"
33292
33468
  );
33293
33469
  }
@@ -33303,7 +33479,7 @@ function resolveBuilder(options) {
33303
33479
  function clampInteger(value, fallback, minimum, maximum, field) {
33304
33480
  const resolved = value ?? fallback;
33305
33481
  if (!Number.isFinite(resolved)) {
33306
- throw new JobRejectedError(`${field} must be a finite number`);
33482
+ throw new import_errors3.JobRejectedError(`${field} must be a finite number`);
33307
33483
  }
33308
33484
  return Math.min(maximum, Math.max(minimum, Math.trunc(resolved)));
33309
33485
  }
@@ -33333,29 +33509,29 @@ async function rejectedResponse(response, fallback) {
33333
33509
  const message = response.status === HTTP_UNAUTHORIZED && parsed.reason ? `${parsed.message}: ${parsed.reason}` : parsed.message;
33334
33510
  if (response.status === HTTP_FORBIDDEN) {
33335
33511
  if (parsed.code === "BUILDER_UNKNOWN") {
33336
- return new BuilderUnknownError(parsed.message, details);
33512
+ return new import_errors3.BuilderUnknownError(parsed.message, details);
33337
33513
  }
33338
33514
  if (parsed.code === "GRANT_INVALID") {
33339
- return new GrantInvalidError(parsed.message, details);
33515
+ return new import_errors3.GrantInvalidError(parsed.message, details);
33340
33516
  }
33341
33517
  if (parsed.code === "OWNER_NOT_READY") {
33342
- return new OwnerNotReadyError(parsed.message, details);
33518
+ return new import_errors3.OwnerNotReadyError(parsed.message, details);
33343
33519
  }
33344
33520
  }
33345
33521
  if (response.status === HTTP_NOT_FOUND) {
33346
- return new JobNotFoundError(parsed.message, details);
33522
+ return new import_errors3.JobNotFoundError(parsed.message, details);
33347
33523
  }
33348
33524
  if (response.status === HTTP_CONFLICT && parsed.code === "JOB_ID_TAKEN") {
33349
- return new JobIdTakenError(parsed.message, details);
33525
+ return new import_errors3.JobIdTakenError(parsed.message, details);
33350
33526
  }
33351
33527
  if (response.status === HTTP_PAYLOAD_TOO_LARGE) {
33352
- return new JobRequestTooLargeError(parsed.message, parsed.code, details);
33528
+ return new import_errors3.JobRequestTooLargeError(parsed.message, parsed.code, details);
33353
33529
  }
33354
- return new JobRejectedError(message, response.status, parsed.code, details);
33530
+ return new import_errors3.JobRejectedError(message, response.status, parsed.code, details);
33355
33531
  }
33356
33532
  function requireStatus(value, status) {
33357
- if (!isRecord2(value) || !isNonEmptyString(value["jobId"]) || typeof value["state"] !== "string" || !JOB_STATES.includes(value["state"]) || !isNonEmptyString(value["owner"]) || !isNonEmptyString(value["grantId"]) || !isNonEmptyString(value["scope"]) || !isNonEmptyString(value["operation"]) || !JOB_OPERATIONS.includes(value["operation"])) {
33358
- throw new JobRejectedError(
33533
+ if (!isRecord2(value) || !isNonEmptyString(value["jobId"]) || typeof value["state"] !== "string" || !JOB_STATES.includes(value["state"]) || !isNonEmptyString(value["owner"]) || !isNonEmptyString(value["grantId"]) || !isNonEmptyString(value["scope"]) || !isNonEmptyString(value["operation"]) || !JOB_OPERATIONS.includes(value["operation"]) || value["state"] === "completed" && !isResultHandle(value["result"])) {
33534
+ throw new import_errors3.JobRejectedError(
33359
33535
  "Gateway response did not contain a job status",
33360
33536
  status
33361
33537
  );
@@ -33365,6 +33541,17 @@ function requireStatus(value, status) {
33365
33541
  function isNonEmptyString(value) {
33366
33542
  return typeof value === "string" && value.length > 0;
33367
33543
  }
33544
+ function isResultHandle(value) {
33545
+ if (!isRecord2(value) || !isNonEmptyString(value["objectKey"]) || !isNonEmptyString(value["url"]) || typeof value["size"] !== "number" || !Number.isInteger(value["size"]) || value["size"] < 0 || typeof value["hash"] !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(value["hash"]) || typeof value["expiresAt"] !== "string" || Number.isNaN(Date.parse(value["expiresAt"]))) {
33546
+ return false;
33547
+ }
33548
+ try {
33549
+ const url = new URL(value["url"]);
33550
+ return url.protocol === "https:" || url.protocol === "http:";
33551
+ } catch {
33552
+ return false;
33553
+ }
33554
+ }
33368
33555
  function hasMatchingIdentityKey(value) {
33369
33556
  const address = value["address"];
33370
33557
  const publicKey = value["publicKey"];
@@ -33391,7 +33578,7 @@ function sleep2(ms) {
33391
33578
  }
33392
33579
  function requireFiniteDuration(value, field) {
33393
33580
  if (!Number.isFinite(value)) {
33394
- throw new JobRejectedError(`${field} must be a finite number`);
33581
+ throw new import_errors3.JobRejectedError(`${field} must be a finite number`);
33395
33582
  }
33396
33583
  return Math.max(0, value);
33397
33584
  }
@@ -33405,7 +33592,7 @@ function createJobsClient(options) {
33405
33592
  try {
33406
33593
  return await fetchFn(url, init);
33407
33594
  } catch (error) {
33408
- throw new JobTransportError(
33595
+ throw new import_errors3.JobTransportError(
33409
33596
  `${description} failed: ${error instanceof Error ? error.message : String(error)}`,
33410
33597
  error
33411
33598
  );
@@ -33426,19 +33613,19 @@ function createJobsClient(options) {
33426
33613
  await responseBody(response),
33427
33614
  "Owner identity not found"
33428
33615
  );
33429
- throw new OwnerNotReadyError(parsed.message, parsed.details);
33616
+ throw new import_errors3.OwnerNotReadyError(parsed.message, parsed.details);
33430
33617
  }
33431
33618
  if (!response.ok) {
33432
33619
  throw await rejectedResponse(response, "Owner identity lookup rejected");
33433
33620
  }
33434
33621
  const body = await responseBody(response);
33435
33622
  if (!isRecord2(body) || body["state"] !== SEALED_IDENTITY_STATE || !isRecord2(body["identity"])) {
33436
- throw new OwnerNotReadyError("Owner identity is not sealed", {
33623
+ throw new import_errors3.OwnerNotReadyError("Owner identity is not sealed", {
33437
33624
  state: isRecord2(body) ? body["state"] : void 0
33438
33625
  });
33439
33626
  }
33440
33627
  if (!hasExpectedIdentity(body["identity"], owner, options.chainId)) {
33441
- throw new JobRejectedError(
33628
+ throw new import_errors3.JobRejectedError(
33442
33629
  "Gateway returned a malformed or mismatched owner identity",
33443
33630
  response.status
33444
33631
  );
@@ -33459,7 +33646,7 @@ function createJobsClient(options) {
33459
33646
  const jobId = (0, import_node_crypto.randomUUID)();
33460
33647
  const nowMs = now().getTime();
33461
33648
  if (!Number.isFinite(nowMs)) {
33462
- throw new JobRejectedError("now must return a valid Date");
33649
+ throw new import_errors3.JobRejectedError("now must return a valid Date");
33463
33650
  }
33464
33651
  const deadline = new Date(
33465
33652
  nowMs + deadlineSeconds * MILLISECONDS_PER_SECOND
@@ -33527,7 +33714,7 @@ function createJobsClient(options) {
33527
33714
  if (response.status === HTTP_OK && isRecord2(body)) {
33528
33715
  const job = requireStatus(body["job"], response.status);
33529
33716
  if (job.jobId !== jobId) {
33530
- throw new JobRejectedError(
33717
+ throw new import_errors3.JobRejectedError(
33531
33718
  "Gateway returned a job id that does not match the submission",
33532
33719
  response.status
33533
33720
  );
@@ -33537,7 +33724,7 @@ function createJobsClient(options) {
33537
33724
  if (response.status === HTTP_ACCEPTED && isRecord2(body) && body["jobId"] === jobId && typeof body["state"] === "string" && JOB_STATES.includes(body["state"])) {
33538
33725
  return { jobId, state: body["state"] };
33539
33726
  }
33540
- throw new JobRejectedError(
33727
+ throw new import_errors3.JobRejectedError(
33541
33728
  "Gateway returned an undocumented job submission response",
33542
33729
  response.status
33543
33730
  );
@@ -33585,7 +33772,7 @@ function createJobsClient(options) {
33585
33772
  let latest;
33586
33773
  for (; ; ) {
33587
33774
  if (Date.now() >= callerDeadline) {
33588
- throw new JobTimeoutError(
33775
+ throw new import_errors3.JobTimeoutError(
33589
33776
  `Timed out waiting for terminal job ${jobId}`,
33590
33777
  {
33591
33778
  jobId,
@@ -33598,7 +33785,7 @@ function createJobsClient(options) {
33598
33785
  if (TERMINAL_JOB_STATES.has(latest.state)) return latest;
33599
33786
  const remaining = callerDeadline - Date.now();
33600
33787
  if (remaining <= 0) {
33601
- throw new JobTimeoutError(
33788
+ throw new import_errors3.JobTimeoutError(
33602
33789
  `Timed out waiting for terminal job ${jobId}`,
33603
33790
  {
33604
33791
  jobId,
@@ -33610,31 +33797,51 @@ function createJobsClient(options) {
33610
33797
  await sleep2(Math.min(pollMs, remaining));
33611
33798
  }
33612
33799
  },
33613
- async openResult(job, openOptions) {
33614
- if (!job.resultCiphertext) {
33615
- throw new JobRejectedError(
33616
- "Job status does not include inline resultCiphertext",
33617
- void 0,
33618
- null,
33800
+ async openResult(handle, openOptions) {
33801
+ if (!privateKey) {
33802
+ throw new import_errors3.JobRejectedError(
33803
+ "openResult requires createJobsClient({ builderPrivateKey })"
33804
+ );
33805
+ }
33806
+ const response = await request(
33807
+ handle.url,
33808
+ { method: GET_METHOD },
33809
+ "Job result fetch"
33810
+ );
33811
+ if (!response.ok) {
33812
+ throw await rejectedResponse(response, "Job result fetch rejected");
33813
+ }
33814
+ let bytes;
33815
+ try {
33816
+ bytes = new Uint8Array(await response.arrayBuffer());
33817
+ } catch (error) {
33818
+ throw new import_errors3.JobTransportError(
33819
+ `Job result fetch failed: ${error instanceof Error ? error.message : String(error)}`,
33820
+ error
33821
+ );
33822
+ }
33823
+ const actualHash = (0, import_viem16.bytesToHex)((0, import_sha26.sha256)(bytes));
33824
+ if (actualHash.toLowerCase() !== handle.hash.toLowerCase()) {
33825
+ throw new import_errors3.JobResultIntegrityError(
33826
+ "Fetched job result hash does not match its handle",
33619
33827
  {
33620
- jobId: job.jobId,
33621
- state: job.state,
33622
- resultHandle: job.resultHandle,
33623
- maxInlineResultBytes: MAX_INLINE_RESULT_BYTES
33828
+ objectKey: handle.objectKey,
33829
+ expectedHash: handle.hash,
33830
+ actualHash
33624
33831
  }
33625
33832
  );
33626
33833
  }
33627
- if (!privateKey) {
33628
- throw new JobRejectedError(
33629
- "openResult requires createJobsClient({ builderPrivateKey })"
33834
+ if (bytes.length !== handle.size) {
33835
+ throw new import_errors3.JobResultIntegrityError(
33836
+ "Fetched job result size does not match its handle",
33837
+ {
33838
+ objectKey: handle.objectKey,
33839
+ expectedSize: handle.size,
33840
+ actualSize: bytes.length
33841
+ }
33630
33842
  );
33631
33843
  }
33632
- return openJobResult(
33633
- job.resultCiphertext,
33634
- privateKey,
33635
- ecies,
33636
- openOptions.expect
33637
- );
33844
+ return openJobResult(bytes, privateKey, ecies, openOptions.expect);
33638
33845
  },
33639
33846
  async readRaw(params) {
33640
33847
  const submitted = await client.submitRawRead(params);
@@ -33642,7 +33849,27 @@ function createJobsClient(options) {
33642
33849
  timeoutMs: params.timeoutMs,
33643
33850
  pollMs: params.pollMs
33644
33851
  });
33645
- return client.openResult(job, {
33852
+ if (job.state !== "completed") {
33853
+ throw new import_errors3.JobRejectedError(
33854
+ `Job ${job.jobId} ended in state ${job.state}${job.failureReason ? `: ${job.failureReason}` : ""}`,
33855
+ void 0,
33856
+ null,
33857
+ {
33858
+ jobId: job.jobId,
33859
+ state: job.state,
33860
+ ...job.failureReason ? { failureReason: job.failureReason } : {}
33861
+ }
33862
+ );
33863
+ }
33864
+ if (!job.result) {
33865
+ throw new import_errors3.JobRejectedError(
33866
+ "Completed job status does not include a result handle",
33867
+ void 0,
33868
+ null,
33869
+ { jobId: job.jobId, state: job.state }
33870
+ );
33871
+ }
33872
+ return client.openResult(job.result, {
33646
33873
  expect: {
33647
33874
  jobId: submitted.jobId,
33648
33875
  scope: params.scope,
@@ -34348,10 +34575,12 @@ function buildMarkDataPointUnavailableRequest(config, input) {
34348
34575
 
34349
34576
  // src/protocol/data-point-deletion.ts
34350
34577
  var import_viem25 = require("viem");
34578
+ var import_errors5 = require("./errors.cjs");
34351
34579
 
34352
34580
  // src/protocol/lineage.ts
34353
34581
  var import_viem24 = require("viem");
34354
34582
  var import_zod = require("zod");
34583
+ var import_errors4 = require("./errors.cjs");
34355
34584
 
34356
34585
  // src/protocol/personal-server-error-body.ts
34357
34586
  function isRecord4(value) {
@@ -34423,7 +34652,7 @@ function derivedScopeViolatesNaming(derivedScope, sourceScope) {
34423
34652
  function assertDerivedScopeNaming(derivedScope, sourceScopes) {
34424
34653
  for (const sourceScope of sourceScopes) {
34425
34654
  if (derivedScopeViolatesNaming(derivedScope, sourceScope)) {
34426
- throw new WriteRequestError(
34655
+ throw new import_errors4.WriteRequestError(
34427
34656
  `Derived scope ${derivedScope} must not share its first segment with source scope ${sourceScope}; put derivatives in the app's own namespace`,
34428
34657
  { scope: derivedScope, sourceScope }
34429
34658
  );
@@ -34486,7 +34715,7 @@ function normalizeBaseUrl(url) {
34486
34715
  function resolveFetch2(fetchFn) {
34487
34716
  const resolved = fetchFn ?? globalThis.fetch;
34488
34717
  if (resolved === void 0) {
34489
- throw new LineageReadError("No fetch implementation available");
34718
+ throw new import_errors4.LineageReadError("No fetch implementation available");
34490
34719
  }
34491
34720
  return resolved;
34492
34721
  }
@@ -34494,7 +34723,7 @@ function normalizeVersion(version) {
34494
34723
  if (version === void 0) return void 0;
34495
34724
  const text = String(version);
34496
34725
  if (!VERSION_PATTERN.test(text)) {
34497
- throw new LineageReadError(
34726
+ throw new import_errors4.LineageReadError(
34498
34727
  "version must be a positive decimal integer",
34499
34728
  void 0,
34500
34729
  "INVALID_VERSION",
@@ -34505,7 +34734,7 @@ function normalizeVersion(version) {
34505
34734
  }
34506
34735
  async function lineageReadFailure(source, response) {
34507
34736
  const { errorCode, message, details } = await readPersonalServerErrorBody(response);
34508
- return new LineageReadError(
34737
+ return new import_errors4.LineageReadError(
34509
34738
  message ?? `${source} lineage read failed: ${response.status} ${response.statusText}`,
34510
34739
  response.status,
34511
34740
  errorCode,
@@ -34517,7 +34746,7 @@ async function parseLineageGraph(source, response) {
34517
34746
  try {
34518
34747
  body = await response.json();
34519
34748
  } catch (err) {
34520
- throw new LineageReadError(
34749
+ throw new import_errors4.LineageReadError(
34521
34750
  `${source} lineage response is not JSON`,
34522
34751
  response.status,
34523
34752
  null,
@@ -34527,7 +34756,7 @@ async function parseLineageGraph(source, response) {
34527
34756
  const envelope = isRecord4(body) && isRecord4(body.data) ? body : void 0;
34528
34757
  const parsed = LineageGraphSchema.safeParse(envelope?.data ?? body);
34529
34758
  if (!parsed.success) {
34530
- throw new LineageReadError(
34759
+ throw new import_errors4.LineageReadError(
34531
34760
  `${source} lineage response is not a lineage view`,
34532
34761
  response.status,
34533
34762
  null,
@@ -34542,7 +34771,7 @@ async function sendLineageRead(source, fetchFn, url, headers) {
34542
34771
  try {
34543
34772
  response = await fetchFn(url, { method: "GET", headers });
34544
34773
  } catch (err) {
34545
- throw new LineageReadError(
34774
+ throw new import_errors4.LineageReadError(
34546
34775
  `${source} lineage read failed: ${err instanceof Error ? err.message : String(err)}`,
34547
34776
  void 0,
34548
34777
  null,
@@ -34583,7 +34812,7 @@ async function getPersonalServerLineage(params) {
34583
34812
  }
34584
34813
  async function getGatewayLineage(params) {
34585
34814
  if (!isDataPointId(params.dataPointId)) {
34586
- throw new LineageReadError(
34815
+ throw new import_errors4.LineageReadError(
34587
34816
  "dataPointId must be a 32-byte hex string (see deriveDataPointId)",
34588
34817
  void 0,
34589
34818
  "INVALID_DATA_POINT_ID",
@@ -34729,13 +34958,13 @@ async function deleteDataPoint(input) {
34729
34958
  if (currentVersion === void 0) {
34730
34959
  const record = await input.gateway.getDataPoint(dataPointId);
34731
34960
  if (record === null) {
34732
- throw new DataPointNotFoundError(
34961
+ throw new import_errors5.DataPointNotFoundError(
34733
34962
  `No data point registered for scope '${input.scope}' owned by ${ownerAddress}`,
34734
34963
  { dataPointId, scope: input.scope, ownerAddress }
34735
34964
  );
34736
34965
  }
34737
34966
  if (isDataPointTombstone(record)) {
34738
- throw new DataPointDeletedError(
34967
+ throw new import_errors5.DataPointDeletedError(
34739
34968
  `Data point ${dataPointId} (scope '${input.scope}') is already deleted`,
34740
34969
  {
34741
34970
  dataPointId,
@@ -34781,6 +35010,9 @@ async function deleteDataPoint(input) {
34781
35010
  }
34782
35011
  }
34783
35012
 
35013
+ // src/protocol/personal-server-data.ts
35014
+ var import_errors6 = require("./errors.cjs");
35015
+
34784
35016
  // src/protocol/data-file.ts
34785
35017
  var import_zod2 = require("zod");
34786
35018
  var DataFileEnvelopeSchema = import_zod2.z.object({
@@ -34839,7 +35071,7 @@ async function readPersonalServerData(params) {
34839
35071
  const request = await buildPersonalServerDataReadRequest(params);
34840
35072
  const response = await fetchFn(request);
34841
35073
  if (response.status === 410) {
34842
- throw new DataPointDeletedError(
35074
+ throw new import_errors6.DataPointDeletedError(
34843
35075
  `Personal Server scope '${params.scope}' has been deleted`,
34844
35076
  {
34845
35077
  scope: params.scope,
@@ -34854,7 +35086,7 @@ async function readPersonalServerData(params) {
34854
35086
  }
34855
35087
  const body = await response.json();
34856
35088
  if (isDataPointTombstone(body)) {
34857
- throw new DataPointDeletedError(
35089
+ throw new import_errors6.DataPointDeletedError(
34858
35090
  `Personal Server scope '${params.scope}' has been deleted`,
34859
35091
  { scope: params.scope, deletedAt: tombstoneDeletedAt(body) }
34860
35092
  );
@@ -35054,20 +35286,22 @@ function tryGrantPermissions(scopes) {
35054
35286
  }
35055
35287
 
35056
35288
  // src/protocol/personal-server-write.ts
35057
- var import_sha27 = require("@noble/hashes/sha2");
35289
+ var import_sha28 = require("@noble/hashes/sha2");
35058
35290
  var import_viem27 = require("viem");
35059
35291
  var import_zod4 = require("zod");
35292
+ var import_errors8 = require("./errors.cjs");
35060
35293
 
35061
35294
  // src/protocol/write-request.ts
35062
- var import_sha26 = require("@noble/hashes/sha2");
35295
+ var import_sha27 = require("@noble/hashes/sha2");
35063
35296
  var import_viem26 = require("viem");
35297
+ var import_errors7 = require("./errors.cjs");
35064
35298
  function normalizeBaseUrl2(url) {
35065
35299
  return url.replace(/\/+$/, "");
35066
35300
  }
35067
35301
  function resolveFetch3(fetchFn) {
35068
35302
  const resolved = fetchFn ?? globalThis.fetch;
35069
35303
  if (resolved === void 0) {
35070
- throw new WriteRequestError("No fetch implementation available");
35304
+ throw new import_errors7.WriteRequestError("No fetch implementation available");
35071
35305
  }
35072
35306
  return resolved;
35073
35307
  }
@@ -35122,27 +35356,27 @@ function nextProofIat(proofKey) {
35122
35356
  return sleep3(waitSec * 1e3).then(() => iat);
35123
35357
  }
35124
35358
  function freshProofNonce() {
35125
- const webCrypto = globalThis.crypto;
35126
- if (typeof webCrypto?.randomUUID === "function") {
35127
- return webCrypto.randomUUID();
35359
+ const webCrypto2 = globalThis.crypto;
35360
+ if (typeof webCrypto2?.randomUUID === "function") {
35361
+ return webCrypto2.randomUUID();
35128
35362
  }
35129
- if (typeof webCrypto?.getRandomValues === "function") {
35130
- return (0, import_viem26.bytesToHex)(webCrypto.getRandomValues(new Uint8Array(16)));
35363
+ if (typeof webCrypto2?.getRandomValues === "function") {
35364
+ return (0, import_viem26.bytesToHex)(webCrypto2.getRandomValues(new Uint8Array(16)));
35131
35365
  }
35132
- throw new WriteRequestError(
35366
+ throw new import_errors7.WriteRequestError(
35133
35367
  "No secure random source available to build a proof nonce; provide a crypto global"
35134
35368
  );
35135
35369
  }
35136
35370
  function proofKeyFor(parts) {
35137
35371
  return (0, import_viem26.bytesToHex)(
35138
- (0, import_sha26.sha256)(
35372
+ (0, import_sha27.sha256)(
35139
35373
  new TextEncoder().encode(
35140
35374
  JSON.stringify([
35141
35375
  parts.aud,
35142
35376
  parts.method,
35143
35377
  parts.uri,
35144
35378
  parts.grantId,
35145
- parts.signedBytes ? (0, import_viem26.bytesToHex)((0, import_sha26.sha256)(parts.signedBytes)) : ""
35379
+ parts.signedBytes ? (0, import_viem26.bytesToHex)((0, import_sha27.sha256)(parts.signedBytes)) : ""
35146
35380
  ])
35147
35381
  )
35148
35382
  )
@@ -35164,7 +35398,7 @@ async function sendWithFreshProof(label, fetchFn, options, proofKey, build) {
35164
35398
  delayMs *= 2;
35165
35399
  }
35166
35400
  }
35167
- throw new WriteTransportError(
35401
+ throw new import_errors7.WriteTransportError(
35168
35402
  `${label} failed after ${attempts} attempt(s): ${errorMessage(lastError)}`,
35169
35403
  attempts,
35170
35404
  lastError
@@ -35235,7 +35469,7 @@ async function openWriteSession(params) {
35235
35469
  const mintedAt = Date.now();
35236
35470
  if (!response.ok) {
35237
35471
  const { errorCode, message, details } = await readPersonalServerErrorBody(response);
35238
- throw new WriteSessionError(
35472
+ throw new import_errors8.WriteSessionError(
35239
35473
  message ?? `Write session handshake failed: ${response.status} ${response.statusText}`,
35240
35474
  response.status,
35241
35475
  errorCode,
@@ -35246,7 +35480,7 @@ async function openWriteSession(params) {
35246
35480
  try {
35247
35481
  body = await response.json();
35248
35482
  } catch (err) {
35249
- throw new WriteSessionError(
35483
+ throw new import_errors8.WriteSessionError(
35250
35484
  "Write session response is not JSON",
35251
35485
  response.status,
35252
35486
  null,
@@ -35255,7 +35489,7 @@ async function openWriteSession(params) {
35255
35489
  }
35256
35490
  const parsed = WriteSessionResponseSchema.safeParse(body);
35257
35491
  if (!parsed.success) {
35258
- throw new WriteSessionError(
35492
+ throw new import_errors8.WriteSessionError(
35259
35493
  "Write session response is not a session",
35260
35494
  response.status,
35261
35495
  null,
@@ -35263,7 +35497,7 @@ async function openWriteSession(params) {
35263
35497
  );
35264
35498
  }
35265
35499
  if (parsed.data.token_type.toLowerCase() !== "bearer") {
35266
- throw new WriteSessionError(
35500
+ throw new import_errors8.WriteSessionError(
35267
35501
  `Write session token type is not Bearer: ${parsed.data.token_type}`,
35268
35502
  response.status
35269
35503
  );
@@ -35285,7 +35519,7 @@ function isWriteSession(value) {
35285
35519
  }
35286
35520
  function sessionCoversScope(session, scope) {
35287
35521
  if (!isRecord4(session) || !Array.isArray(session.writeScopes) || !session.writeScopes.every((pattern) => typeof pattern === "string")) {
35288
- throw new WriteRequestError("session must come from openWriteSession");
35522
+ throw new import_errors8.WriteRequestError("session must come from openWriteSession");
35289
35523
  }
35290
35524
  return session.writeScopes.some(
35291
35525
  (pattern) => scopeMatchesPattern(scope, pattern)
@@ -35310,12 +35544,12 @@ function encodeWriteMetadataHeader(metadata) {
35310
35544
  try {
35311
35545
  json = JSON.stringify(metadata);
35312
35546
  } catch (err) {
35313
- throw new WriteRequestError(
35547
+ throw new import_errors8.WriteRequestError(
35314
35548
  `metadata is not JSON-serialisable: ${errorMessage(err)}`
35315
35549
  );
35316
35550
  }
35317
35551
  if (typeof json !== "string") {
35318
- throw new WriteRequestError("metadata must serialise to JSON");
35552
+ throw new import_errors8.WriteRequestError("metadata must serialise to JSON");
35319
35553
  }
35320
35554
  return json.replace(
35321
35555
  /[\u007f-\uffff]/g,
@@ -35329,7 +35563,7 @@ function binaryWriteSignedBytes(input) {
35329
35563
  mimeType: normalizeBinaryMimeType(input.contentType),
35330
35564
  ...input.filename ? { filename: input.filename } : {},
35331
35565
  sizeBytes: input.bytes.length,
35332
- contentHash: (0, import_viem27.bytesToHex)((0, import_sha27.sha256)(input.bytes)),
35566
+ contentHash: (0, import_viem27.bytesToHex)((0, import_sha28.sha256)(input.bytes)),
35333
35567
  encoding: "base64",
35334
35568
  content: toBase64(input.bytes),
35335
35569
  ...metadata !== void 0 ? { metadata } : {}
@@ -35350,7 +35584,7 @@ function setFilenameHeader(headers, filename) {
35350
35584
  function assertNoReservedKeys(value, where) {
35351
35585
  for (const key of RESERVED_WRITE_KEYS) {
35352
35586
  if (Object.prototype.hasOwnProperty.call(value, key)) {
35353
- throw new WriteRequestError(
35587
+ throw new import_errors8.WriteRequestError(
35354
35588
  `${where} must not contain the reserved ${key} key; the Personal Server stamps it`,
35355
35589
  { key }
35356
35590
  );
@@ -35362,10 +35596,10 @@ function isLineagePair(value) {
35362
35596
  }
35363
35597
  function normalizeLineage(lineage, derivedScope) {
35364
35598
  if (!Array.isArray(lineage)) {
35365
- throw new WriteRequestError("lineage must be an array of data point ids");
35599
+ throw new import_errors8.WriteRequestError("lineage must be an array of data point ids");
35366
35600
  }
35367
35601
  if (lineage.length > MAX_LINEAGE_SOURCES) {
35368
- throw new WriteRequestError(
35602
+ throw new import_errors8.WriteRequestError(
35369
35603
  `lineage lists ${lineage.length} sources; the maximum is ${MAX_LINEAGE_SOURCES}`,
35370
35604
  { max: MAX_LINEAGE_SOURCES, count: lineage.length }
35371
35605
  );
@@ -35378,13 +35612,13 @@ function normalizeLineage(lineage, derivedScope) {
35378
35612
  let id;
35379
35613
  if (isLineagePair(entry)) {
35380
35614
  if (!(0, import_viem27.isAddress)(entry.ownerAddress, { strict: false })) {
35381
- throw new WriteRequestError(
35615
+ throw new import_errors8.WriteRequestError(
35382
35616
  "lineage source ownerAddress must be an EVM address",
35383
35617
  { ownerAddress: entry.ownerAddress }
35384
35618
  );
35385
35619
  }
35386
35620
  if (entry.scope.length === 0) {
35387
- throw new WriteRequestError("lineage source scope is required");
35621
+ throw new import_errors8.WriteRequestError("lineage source scope is required");
35388
35622
  }
35389
35623
  id = deriveDataPointId(entry.ownerAddress, entry.scope);
35390
35624
  sourceScopes.push(entry.scope);
@@ -35392,14 +35626,14 @@ function normalizeLineage(lineage, derivedScope) {
35392
35626
  } else if (isDataPointId(entry)) {
35393
35627
  id = entry;
35394
35628
  } else {
35395
- throw new WriteRequestError(
35629
+ throw new import_errors8.WriteRequestError(
35396
35630
  "lineage entries must be 32-byte hex data point ids or { ownerAddress, scope } pairs",
35397
35631
  { entry }
35398
35632
  );
35399
35633
  }
35400
35634
  const normalized = id.toLowerCase();
35401
35635
  if (seen.has(normalized)) {
35402
- throw new WriteRequestError("lineage must not repeat a data point id", {
35636
+ throw new import_errors8.WriteRequestError("lineage must not repeat a data point id", {
35403
35637
  dataPointId: normalized
35404
35638
  });
35405
35639
  }
@@ -35408,7 +35642,7 @@ function normalizeLineage(lineage, derivedScope) {
35408
35642
  }
35409
35643
  for (const own of ownIds) {
35410
35644
  if (seen.has(own)) {
35411
- throw new WriteRequestError(
35645
+ throw new import_errors8.WriteRequestError(
35412
35646
  "lineage must not cite the record's own data point",
35413
35647
  { dataPointId: own, scope: derivedScope }
35414
35648
  );
@@ -35419,7 +35653,7 @@ function normalizeLineage(lineage, derivedScope) {
35419
35653
  }
35420
35654
  function assertNoLineageField(value, where) {
35421
35655
  if (Object.prototype.hasOwnProperty.call(value, LINEAGE_FIELD)) {
35422
- throw new WriteRequestError(
35656
+ throw new import_errors8.WriteRequestError(
35423
35657
  `${where}.${LINEAGE_FIELD} is reserved; pass sources through the lineage option`
35424
35658
  );
35425
35659
  }
@@ -35427,7 +35661,7 @@ function assertNoLineageField(value, where) {
35427
35661
  function buildMetadataHeader(metadata, sources) {
35428
35662
  if (metadata !== void 0) {
35429
35663
  if (!isRecord4(metadata)) {
35430
- throw new WriteRequestError("metadata must be a plain object");
35664
+ throw new import_errors8.WriteRequestError("metadata must be a plain object");
35431
35665
  }
35432
35666
  assertNoReservedKeys(metadata, "metadata");
35433
35667
  assertNoLineageField(metadata, "metadata");
@@ -35440,24 +35674,24 @@ function buildMetadataHeader(metadata, sources) {
35440
35674
  }
35441
35675
  function prepareWrite(params) {
35442
35676
  if (params.binary !== void 0 && params.data !== void 0) {
35443
- throw new WriteRequestError("Pass either data or binary, not both");
35677
+ throw new import_errors8.WriteRequestError("Pass either data or binary, not both");
35444
35678
  }
35445
35679
  const rawLineage = params.lineage;
35446
35680
  const sources = rawLineage === void 0 || rawLineage === null ? void 0 : normalizeLineage(rawLineage, params.scope);
35447
35681
  if (params.binary !== void 0) {
35448
35682
  const { bytes, contentType, filename } = params.binary;
35449
35683
  if (!(bytes instanceof Uint8Array)) {
35450
- throw new WriteRequestError("binary.bytes must be a Uint8Array");
35684
+ throw new import_errors8.WriteRequestError("binary.bytes must be a Uint8Array");
35451
35685
  }
35452
35686
  if (typeof contentType !== "string" || contentType.trim() === "") {
35453
- throw new WriteRequestError("binary.contentType is required");
35687
+ throw new import_errors8.WriteRequestError("binary.contentType is required");
35454
35688
  }
35455
35689
  if (filename !== void 0) {
35456
35690
  if (typeof filename !== "string") {
35457
- throw new WriteRequestError("binary.filename must be a string");
35691
+ throw new import_errors8.WriteRequestError("binary.filename must be a string");
35458
35692
  }
35459
35693
  if (filename !== filename.trim()) {
35460
- throw new WriteRequestError(
35694
+ throw new import_errors8.WriteRequestError(
35461
35695
  "binary.filename must not have leading or trailing whitespace"
35462
35696
  );
35463
35697
  }
@@ -35477,13 +35711,13 @@ function prepareWrite(params) {
35477
35711
  };
35478
35712
  }
35479
35713
  if (params.data === void 0) {
35480
- throw new WriteRequestError("Pass data (a JSON object) or binary");
35714
+ throw new import_errors8.WriteRequestError("Pass data (a JSON object) or binary");
35481
35715
  }
35482
35716
  if (!isRecord4(params.data)) {
35483
- throw new WriteRequestError("data must be a plain JSON object");
35717
+ throw new import_errors8.WriteRequestError("data must be a plain JSON object");
35484
35718
  }
35485
35719
  if (params.metadata !== void 0) {
35486
- throw new WriteRequestError(
35720
+ throw new import_errors8.WriteRequestError(
35487
35721
  "metadata applies to binary writes; put fields to store inside data"
35488
35722
  );
35489
35723
  }
@@ -35494,12 +35728,12 @@ function prepareWrite(params) {
35494
35728
  try {
35495
35729
  text = JSON.stringify(record);
35496
35730
  } catch (err) {
35497
- throw new WriteRequestError(
35731
+ throw new import_errors8.WriteRequestError(
35498
35732
  `data is not JSON-serialisable: ${errorMessage(err)}`
35499
35733
  );
35500
35734
  }
35501
35735
  if (typeof text !== "string" || !text.startsWith("{")) {
35502
- throw new WriteRequestError("data must serialise to a JSON object");
35736
+ throw new import_errors8.WriteRequestError("data must serialise to a JSON object");
35503
35737
  }
35504
35738
  const body = new TextEncoder().encode(text);
35505
35739
  return {
@@ -35512,31 +35746,31 @@ async function writeErrorFromResponse(response) {
35512
35746
  const { errorCode, message, details } = await readPersonalServerErrorBody(response);
35513
35747
  const text = message ?? `Personal Server write failed: ${response.status} ${response.statusText}`;
35514
35748
  if (response.status === 422 || errorCode?.startsWith("LINEAGE_")) {
35515
- return new WriteLineageError(text, response.status, errorCode, details);
35749
+ return new import_errors8.WriteLineageError(text, response.status, errorCode, details);
35516
35750
  }
35517
35751
  switch (response.status) {
35518
35752
  case 401:
35519
- return new WriteUnauthorizedError(text, errorCode, details);
35753
+ return new import_errors8.WriteUnauthorizedError(text, errorCode, details);
35520
35754
  case 403:
35521
- return new WriteForbiddenError(text, errorCode, details);
35755
+ return new import_errors8.WriteForbiddenError(text, errorCode, details);
35522
35756
  case 409:
35523
- return new WriteConflictError(text, errorCode, details);
35757
+ return new import_errors8.WriteConflictError(text, errorCode, details);
35524
35758
  default:
35525
- return new WriteRejectedError(text, response.status, errorCode, details);
35759
+ return new import_errors8.WriteRejectedError(text, response.status, errorCode, details);
35526
35760
  }
35527
35761
  }
35528
35762
  async function writeData(params) {
35529
35763
  const { session } = params;
35530
35764
  if (!isWriteSession(session)) {
35531
- throw new WriteRequestError("session must come from openWriteSession");
35765
+ throw new import_errors8.WriteRequestError("session must come from openWriteSession");
35532
35766
  }
35533
35767
  const fetchFn = resolveFetch3(params.fetch);
35534
35768
  if (typeof params.scope !== "string" || params.scope.length === 0) {
35535
- throw new WriteRequestError("scope is required");
35769
+ throw new import_errors8.WriteRequestError("scope is required");
35536
35770
  }
35537
35771
  const prepared = prepareWrite(params);
35538
35772
  if (Date.now() >= session.expiresAt) {
35539
- throw new WriteSessionExpiredError(
35773
+ throw new import_errors8.WriteSessionExpiredError(
35540
35774
  "Write session has expired; open a new session",
35541
35775
  { grantId: session.grantId, expiresAt: session.expiresAt }
35542
35776
  );
@@ -35592,7 +35826,7 @@ async function writeData(params) {
35592
35826
  try {
35593
35827
  body = await response.json();
35594
35828
  } catch (err) {
35595
- throw new WriteRejectedError(
35829
+ throw new import_errors8.WriteRejectedError(
35596
35830
  "Personal Server write response is not JSON",
35597
35831
  response.status,
35598
35832
  null,
@@ -35601,7 +35835,7 @@ async function writeData(params) {
35601
35835
  }
35602
35836
  const parsed = WriteDataResultSchema.safeParse(body);
35603
35837
  if (!parsed.success) {
35604
- throw new WriteRejectedError(
35838
+ throw new import_errors8.WriteRejectedError(
35605
35839
  "Personal Server write response is not an ingest result",
35606
35840
  response.status,
35607
35841
  null,
@@ -35628,6 +35862,7 @@ async function writePersonalServerData(params) {
35628
35862
 
35629
35863
  // src/protocol/derivative-questions.ts
35630
35864
  var import_zod5 = require("zod");
35865
+ var import_errors9 = require("./errors.cjs");
35631
35866
  var DERIVATIVE_QUESTIONS_PATH = "/v1/derivatives/questions";
35632
35867
  var MAX_QUESTION_SOURCE_SCOPES = 16;
35633
35868
  var MAX_QUESTION_CHARS = 8e3;
@@ -35710,15 +35945,15 @@ function fetchIdOf(fetchFn) {
35710
35945
  }
35711
35946
  function resolveRequest(params) {
35712
35947
  if (typeof params.personalServerUrl !== "string" || params.personalServerUrl.length === 0) {
35713
- throw new WriteRequestError("personalServerUrl is required");
35948
+ throw new import_errors9.WriteRequestError("personalServerUrl is required");
35714
35949
  }
35715
35950
  if (typeof params.grantId !== "string" || params.grantId.length === 0) {
35716
- throw new WriteRequestError(
35951
+ throw new import_errors9.WriteRequestError(
35717
35952
  "grantId is required; a question call runs under the grant carrying write:<derivedScope>"
35718
35953
  );
35719
35954
  }
35720
35955
  if (params.signer === null || typeof params.signer !== "object") {
35721
- throw new WriteRequestError(
35956
+ throw new import_errors9.WriteRequestError(
35722
35957
  "signer must be a viem LocalAccount, a viem WalletClient, or a { signMessage } object"
35723
35958
  );
35724
35959
  }
@@ -35772,37 +36007,37 @@ async function questionErrorFromResponse(response, body) {
35772
36007
  const text = message ?? `Derivative question request failed: ${response.status} ${response.statusText}`;
35773
36008
  switch (errorCode) {
35774
36009
  case "DERIVATIVE_SOURCE_NOT_GRANTED":
35775
- return new DerivativeSourceNotGrantedError(text, errorCode, details);
36010
+ return new import_errors9.DerivativeSourceNotGrantedError(text, errorCode, details);
35776
36011
  case "DERIVATIVE_CYCLE":
35777
- return new DerivativeCycleError(text, errorCode, details);
36012
+ return new import_errors9.DerivativeCycleError(text, errorCode, details);
35778
36013
  case "DERIVATIVE_COMPUTE_UNAVAILABLE":
35779
- return new DerivativeComputeUnavailableError(text, errorCode, details);
36014
+ return new import_errors9.DerivativeComputeUnavailableError(text, errorCode, details);
35780
36015
  case "DERIVATIVE_QUESTION_INVALID":
35781
36016
  case "LINEAGE_SCOPE_UNDER_SOURCE_PREFIX":
35782
- return new DerivativeQuestionInvalidError(
36017
+ return new import_errors9.DerivativeQuestionInvalidError(
35783
36018
  text,
35784
36019
  response.status,
35785
36020
  errorCode,
35786
36021
  details
35787
36022
  );
35788
36023
  case "DERIVATIVE_QUESTION_NOT_FOUND":
35789
- return new DerivativeQuestionNotFoundError(text, errorCode, details);
36024
+ return new import_errors9.DerivativeQuestionNotFoundError(text, errorCode, details);
35790
36025
  case "DERIVATIVE_DERIVED_SCOPE_REQUIRED":
35791
- return new DerivativeDerivedScopeRequiredError(text, errorCode, details);
36026
+ return new import_errors9.DerivativeDerivedScopeRequiredError(text, errorCode, details);
35792
36027
  default:
35793
36028
  break;
35794
36029
  }
35795
36030
  switch (response.status) {
35796
36031
  case 401:
35797
- return new WriteUnauthorizedError(text, errorCode, details);
36032
+ return new import_errors9.WriteUnauthorizedError(text, errorCode, details);
35798
36033
  case 403:
35799
- return new WriteForbiddenError(text, errorCode, details);
36034
+ return new import_errors9.WriteForbiddenError(text, errorCode, details);
35800
36035
  case 404:
35801
- return new DerivativeQuestionNotFoundError(text, errorCode, details);
36036
+ return new import_errors9.DerivativeQuestionNotFoundError(text, errorCode, details);
35802
36037
  case 409:
35803
- return new WriteConflictError(text, errorCode, details);
36038
+ return new import_errors9.WriteConflictError(text, errorCode, details);
35804
36039
  default:
35805
- return new DerivativeQuestionRejectedError(
36040
+ return new import_errors9.DerivativeQuestionRejectedError(
35806
36041
  text,
35807
36042
  response.status,
35808
36043
  errorCode,
@@ -35882,7 +36117,7 @@ async function sendQuestionRequest(params, spec, schema) {
35882
36117
  try {
35883
36118
  body = await response.json();
35884
36119
  } catch (err) {
35885
- throw new DerivativeQuestionRejectedError(
36120
+ throw new import_errors9.DerivativeQuestionRejectedError(
35886
36121
  `${spec.label} response is not JSON`,
35887
36122
  response.status,
35888
36123
  null,
@@ -35891,7 +36126,7 @@ async function sendQuestionRequest(params, spec, schema) {
35891
36126
  }
35892
36127
  const parsed = schema.safeParse(body);
35893
36128
  if (!parsed.success) {
35894
- throw new DerivativeQuestionRejectedError(
36129
+ throw new import_errors9.DerivativeQuestionRejectedError(
35895
36130
  `${spec.label} response is not a derivative question answer`,
35896
36131
  response.status,
35897
36132
  null,
@@ -35902,22 +36137,22 @@ async function sendQuestionRequest(params, spec, schema) {
35902
36137
  }
35903
36138
  function assertQuestionId(questionId) {
35904
36139
  if (typeof questionId !== "string" || questionId.length === 0) {
35905
- throw new WriteRequestError("questionId is required");
36140
+ throw new import_errors9.WriteRequestError("questionId is required");
35906
36141
  }
35907
36142
  return `${DERIVATIVE_QUESTIONS_PATH}/${encodeURIComponent(questionId)}`;
35908
36143
  }
35909
36144
  function registrationBody(params) {
35910
36145
  const { derivedScope, question } = params;
35911
36146
  if (typeof derivedScope !== "string" || derivedScope.length === 0) {
35912
- throw new WriteRequestError("derivedScope is required");
36147
+ throw new import_errors9.WriteRequestError("derivedScope is required");
35913
36148
  }
35914
36149
  if (!Array.isArray(params.sourceScopes) || params.sourceScopes.length === 0) {
35915
- throw new WriteRequestError(
36150
+ throw new import_errors9.WriteRequestError(
35916
36151
  "sourceScopes must be a non-empty array of scopes"
35917
36152
  );
35918
36153
  }
35919
36154
  if (params.sourceScopes.length > MAX_QUESTION_SOURCE_SCOPES) {
35920
- throw new WriteRequestError(
36155
+ throw new import_errors9.WriteRequestError(
35921
36156
  `sourceScopes lists ${params.sourceScopes.length} scopes; the maximum is ${MAX_QUESTION_SOURCE_SCOPES}`,
35922
36157
  { max: MAX_QUESTION_SOURCE_SCOPES, count: params.sourceScopes.length }
35923
36158
  );
@@ -35925,15 +36160,15 @@ function registrationBody(params) {
35925
36160
  const sourceScopes = [];
35926
36161
  for (const scope of params.sourceScopes) {
35927
36162
  if (typeof scope !== "string" || scope.length === 0) {
35928
- throw new WriteRequestError("sourceScopes entries must be scope strings");
36163
+ throw new import_errors9.WriteRequestError("sourceScopes entries must be scope strings");
35929
36164
  }
35930
36165
  if (sourceScopes.includes(scope)) {
35931
- throw new WriteRequestError("sourceScopes must not repeat a scope", {
36166
+ throw new import_errors9.WriteRequestError("sourceScopes must not repeat a scope", {
35932
36167
  duplicate: scope
35933
36168
  });
35934
36169
  }
35935
36170
  if (scope === derivedScope) {
35936
- throw new WriteRequestError(
36171
+ throw new import_errors9.WriteRequestError(
35937
36172
  "derivedScope cannot be one of its own sources",
35938
36173
  { scope }
35939
36174
  );
@@ -35941,17 +36176,17 @@ function registrationBody(params) {
35941
36176
  sourceScopes.push(scope);
35942
36177
  }
35943
36178
  if (typeof question !== "string" || question.trim() === "") {
35944
- throw new WriteRequestError("question must be a non-empty string");
36179
+ throw new import_errors9.WriteRequestError("question must be a non-empty string");
35945
36180
  }
35946
36181
  if (question.length > MAX_QUESTION_CHARS) {
35947
- throw new WriteRequestError(
36182
+ throw new import_errors9.WriteRequestError(
35948
36183
  `question is ${question.length} characters; the maximum is ${MAX_QUESTION_CHARS}`,
35949
36184
  { max: MAX_QUESTION_CHARS, length: question.length }
35950
36185
  );
35951
36186
  }
35952
36187
  if (params.model !== void 0) {
35953
36188
  if (typeof params.model !== "string" || params.model.length > MAX_QUESTION_MODEL_CHARS || !MODEL_ID_PATTERN.test(params.model)) {
35954
- throw new WriteRequestError("model must be a provider model id", {
36189
+ throw new import_errors9.WriteRequestError("model must be a provider model id", {
35955
36190
  model: params.model
35956
36191
  });
35957
36192
  }
@@ -35987,7 +36222,7 @@ async function getQuestion(params) {
35987
36222
  }
35988
36223
  async function listQuestions(params) {
35989
36224
  if (typeof params.derivedScope !== "string" || params.derivedScope.length === 0) {
35990
- throw new WriteRequestError(
36225
+ throw new import_errors9.WriteRequestError(
35991
36226
  "derivedScope is required; a builder may only list its own questions on a scope it may write"
35992
36227
  );
35993
36228
  }
@@ -36045,7 +36280,7 @@ async function waitForQuestion(params) {
36045
36280
  if (isSettled(latest.status)) return latest;
36046
36281
  const remaining = deadline - Date.now();
36047
36282
  if (remaining <= 0) {
36048
- throw new DerivativeQuestionTimeoutError(
36283
+ throw new import_errors9.DerivativeQuestionTimeoutError(
36049
36284
  `Derivative question ${latest.questionId} was still ${latest.status} after ${timeoutMs}ms`,
36050
36285
  {
36051
36286
  questionId: latest.questionId,
@@ -36065,7 +36300,7 @@ async function askPersonalServer(params) {
36065
36300
  questionId: registered.questionId
36066
36301
  });
36067
36302
  if (registration.status !== "ready") {
36068
- throw new DerivativeQuestionFailedError(
36303
+ throw new import_errors9.DerivativeQuestionFailedError(
36069
36304
  `Derivative question ${registration.questionId} failed: ${registration.error ?? "no reason given"}`,
36070
36305
  {
36071
36306
  questionId: registration.questionId,
@@ -36092,6 +36327,7 @@ async function askPersonalServer(params) {
36092
36327
 
36093
36328
  // src/protocol/derivative-status.ts
36094
36329
  var import_zod6 = require("zod");
36330
+ var import_errors10 = require("./errors.cjs");
36095
36331
  var DERIVATIVE_STATUS_PATH = "/v1/derivatives/status";
36096
36332
  var DEFAULT_DERIVATIVE_STATUS_TIMEOUT_MS = 12e4;
36097
36333
  var DEFAULT_DERIVATIVE_STATUS_POLL_INTERVAL_MS = 2e3;
@@ -36122,13 +36358,13 @@ function normalizeBaseUrl3(url) {
36122
36358
  function resolveFetch4(fetchFn) {
36123
36359
  const resolved = fetchFn ?? globalThis.fetch;
36124
36360
  if (resolved === void 0) {
36125
- throw new WriteRequestError("No fetch implementation available");
36361
+ throw new import_errors10.WriteRequestError("No fetch implementation available");
36126
36362
  }
36127
36363
  return resolved;
36128
36364
  }
36129
36365
  function requireDerivedScope(derivedScope) {
36130
36366
  if (typeof derivedScope !== "string" || derivedScope.length === 0) {
36131
- throw new WriteRequestError("derivedScope is required");
36367
+ throw new import_errors10.WriteRequestError("derivedScope is required");
36132
36368
  }
36133
36369
  return derivedScope;
36134
36370
  }
@@ -36147,7 +36383,7 @@ function sleep4(ms, signal) {
36147
36383
  });
36148
36384
  }
36149
36385
  function timeoutError(latest, timeoutMs) {
36150
- return new DerivativeQuestionTimeoutError(
36386
+ return new import_errors10.DerivativeQuestionTimeoutError(
36151
36387
  `Derived scope ${latest.derivedScope} was still ${latest.status} after ${timeoutMs}ms`,
36152
36388
  {
36153
36389
  derivedScope: latest.derivedScope,
@@ -36160,7 +36396,7 @@ function timeoutError(latest, timeoutMs) {
36160
36396
  }
36161
36397
  function abortError2(signal) {
36162
36398
  const reason = signal?.reason;
36163
- return reason instanceof Error ? reason : new WriteRequestError("Derivative status wait was aborted");
36399
+ return reason instanceof Error ? reason : new import_errors10.WriteRequestError("Derivative status wait was aborted");
36164
36400
  }
36165
36401
  function isDerivativeStatusSettled(status) {
36166
36402
  if (status.status === "ready") return true;
@@ -36193,7 +36429,7 @@ async function getDerivativeStatus(params) {
36193
36429
  }
36194
36430
  );
36195
36431
  } catch (err) {
36196
- throw new WriteTransportError(
36432
+ throw new import_errors10.WriteTransportError(
36197
36433
  `Derivative status read failed: ${err instanceof Error ? err.message : String(err)}`,
36198
36434
  1,
36199
36435
  err
@@ -36208,7 +36444,7 @@ async function getDerivativeStatus(params) {
36208
36444
  try {
36209
36445
  body = await response.json();
36210
36446
  } catch (err) {
36211
- throw new DerivativeQuestionRejectedError(
36447
+ throw new import_errors10.DerivativeQuestionRejectedError(
36212
36448
  "Derivative status response is not JSON",
36213
36449
  response.status,
36214
36450
  null,
@@ -36217,7 +36453,7 @@ async function getDerivativeStatus(params) {
36217
36453
  }
36218
36454
  const parsed = DerivativeStatusSchema.safeParse(body);
36219
36455
  if (!parsed.success) {
36220
- throw new DerivativeQuestionRejectedError(
36456
+ throw new import_errors10.DerivativeQuestionRejectedError(
36221
36457
  "Derivative status response is not a status view",
36222
36458
  response.status,
36223
36459
  null,
@@ -36251,6 +36487,7 @@ async function waitForDerivativeStatus(params) {
36251
36487
  }
36252
36488
 
36253
36489
  // src/protocol/gateway.ts
36490
+ var import_errors11 = require("./errors.cjs");
36254
36491
  function withGrantPermissions(grant) {
36255
36492
  const stripped = { ...grant };
36256
36493
  delete stripped.permissions;
@@ -36296,7 +36533,7 @@ function createGatewayClient(baseUrl) {
36296
36533
  }
36297
36534
  async function deletedError(res, details) {
36298
36535
  const body = await readBody(res);
36299
- return new DataPointDeletedError(
36536
+ return new import_errors11.DataPointDeletedError(
36300
36537
  `Data point ${details.dataPointId ?? details.scope ?? ""} has been deleted`,
36301
36538
  { ...details, deletedAt: tombstoneDeletedAt(body) }
36302
36539
  );
@@ -36369,7 +36606,7 @@ function createGatewayClient(baseUrl) {
36369
36606
  }
36370
36607
  const record = await unwrapEnvelope(res);
36371
36608
  if (!options?.includeDeleted && isDataPointTombstone(record)) {
36372
- throw new DataPointDeletedError(
36609
+ throw new import_errors11.DataPointDeletedError(
36373
36610
  `Data point ${dataPointId} has been deleted`,
36374
36611
  {
36375
36612
  dataPointId,
@@ -36531,7 +36768,7 @@ function createGatewayClient(baseUrl) {
36531
36768
  })
36532
36769
  });
36533
36770
  if (res.status === 404) {
36534
- throw new DataPointNotFoundError(
36771
+ throw new import_errors11.DataPointNotFoundError(
36535
36772
  `Data point ${dataPointId} (scope '${params.scope}') is not registered`,
36536
36773
  details
36537
36774
  );
@@ -36542,7 +36779,7 @@ function createGatewayClient(baseUrl) {
36542
36779
  body2["currentExpectedVersion"]
36543
36780
  );
36544
36781
  const detail = stringOrUndefined(body2["error"]) ?? res.statusText;
36545
- throw new DataPointVersionConflictError(
36782
+ throw new import_errors11.DataPointVersionConflictError(
36546
36783
  `Gateway error: 409 ${detail}`,
36547
36784
  {
36548
36785
  ...details,
@@ -36673,6 +36910,7 @@ function createGatewayClient(baseUrl) {
36673
36910
  }
36674
36911
 
36675
36912
  // src/protocol/escrow.ts
36913
+ var import_viem28 = require("viem");
36676
36914
  var GENERIC_PAYMENT_TYPES = {
36677
36915
  GenericPayment: [
36678
36916
  { name: "payerAddress", type: "address" },
@@ -36712,6 +36950,26 @@ var ESCROW_DEPOSIT_ABI2 = [
36712
36950
  }
36713
36951
  ];
36714
36952
  var NATIVE_ASSET_ADDRESS = "0x0000000000000000000000000000000000000000";
36953
+ var EscrowWithdrawalLifecycleError = class extends Error {
36954
+ constructor(httpStatus, result) {
36955
+ super(result.error);
36956
+ this.httpStatus = httpStatus;
36957
+ this.result = result;
36958
+ }
36959
+ httpStatus;
36960
+ result;
36961
+ name = "EscrowWithdrawalLifecycleError";
36962
+ };
36963
+ var EscrowWithdrawalRejectionError = class extends Error {
36964
+ constructor(httpStatus, result) {
36965
+ super(result.error);
36966
+ this.httpStatus = httpStatus;
36967
+ this.result = result;
36968
+ }
36969
+ httpStatus;
36970
+ result;
36971
+ name = "EscrowWithdrawalRejectionError";
36972
+ };
36715
36973
  function createEscrowGatewayClient(baseUrl) {
36716
36974
  const base = baseUrl.replace(/\/+$/, "");
36717
36975
  async function throwOnError(res, context) {
@@ -36727,6 +36985,27 @@ function createEscrowGatewayClient(baseUrl) {
36727
36985
  );
36728
36986
  }
36729
36987
  }
36988
+ async function throwOnWithdrawError(res) {
36989
+ if (res.ok) return;
36990
+ let body;
36991
+ try {
36992
+ body = await res.json();
36993
+ } catch {
36994
+ throw new Error(
36995
+ `Escrow gateway error (POST /v1/escrow/withdraw): ${res.status} ${res.statusText}`
36996
+ );
36997
+ }
36998
+ if (isEscrowWithdrawalFailureResult(body)) {
36999
+ throw new EscrowWithdrawalLifecycleError(res.status, body);
37000
+ }
37001
+ if (isEscrowWithdrawalRejectedResult(body)) {
37002
+ throw new EscrowWithdrawalRejectionError(res.status, body);
37003
+ }
37004
+ const error = getGatewayErrorMessage(body);
37005
+ throw new Error(
37006
+ `Escrow gateway error (POST /v1/escrow/withdraw): ${res.status} ${res.statusText}${error ? `: ${error}` : ""}`
37007
+ );
37008
+ }
36730
37009
  return {
36731
37010
  async submitDeposit({ txHash }) {
36732
37011
  const res = await fetch(`${base}/v1/escrow/deposit`, {
@@ -36782,9 +37061,108 @@ function createEscrowGatewayClient(baseUrl) {
36782
37061
  });
36783
37062
  await throwOnError(res, "POST /v1/escrow/pay");
36784
37063
  return res.json();
37064
+ },
37065
+ async withdraw({
37066
+ account,
37067
+ asset,
37068
+ amount,
37069
+ withdrawNonce,
37070
+ deadline,
37071
+ signature
37072
+ }) {
37073
+ const res = await fetch(`${base}/v1/escrow/withdraw`, {
37074
+ method: "POST",
37075
+ headers: {
37076
+ "Content-Type": "application/json",
37077
+ Authorization: `Web3Signed ${signature}`
37078
+ },
37079
+ body: JSON.stringify({
37080
+ account,
37081
+ asset,
37082
+ amount,
37083
+ withdrawNonce,
37084
+ deadline
37085
+ })
37086
+ });
37087
+ await throwOnWithdrawError(res);
37088
+ return res.json();
37089
+ },
37090
+ async getWithdrawNonce(account) {
37091
+ const res = await fetch(
37092
+ `${base}/v1/escrow/withdraw/nonce?account=${encodeURIComponent(account)}`,
37093
+ { cache: "no-store" }
37094
+ );
37095
+ await throwOnError(res, "GET /v1/escrow/withdraw/nonce");
37096
+ const body = await res.json();
37097
+ if (!isWithdrawNonceResponse(body, account)) {
37098
+ throw new Error(
37099
+ "GET /v1/escrow/withdraw/nonce: invalid response structure"
37100
+ );
37101
+ }
37102
+ return body;
36785
37103
  }
36786
37104
  };
36787
37105
  }
37106
+ function getGatewayErrorMessage(body) {
37107
+ if (typeof body === "object" && body !== null && "error" in body && typeof body.error === "string") {
37108
+ return body.error;
37109
+ }
37110
+ return void 0;
37111
+ }
37112
+ function isEscrowWithdrawalFailureResult(body) {
37113
+ if (typeof body !== "object" || body === null) return false;
37114
+ const value = body;
37115
+ return value.success === false && (value.status === "retryable" || value.status === "reorged" || value.status === "failed") && typeof value.error === "string" && isAddressHex(value.account) && isAddressHex(value.asset) && isUint256Decimal(value.amount) && isUint256Decimal(value.withdrawNonce) && isUint256Decimal(value.deadline) && (isHash(value.txHash) || value.txHash === null) && (!("blockNumber" in value) || isBlockNumber(value.blockNumber));
37116
+ }
37117
+ function isEscrowWithdrawalRejectedResult(body) {
37118
+ if (typeof body !== "object" || body === null) return false;
37119
+ const value = body;
37120
+ return value.success === false && value.status === "rejected" && isWithdrawalRejectionCode(value.code) && typeof value.error === "string" && isAddressHex(value.account) && isAddressHex(value.asset) && isUint256Decimal(value.amount) && isUint256Decimal(value.withdrawNonce) && isUint256Decimal(value.deadline) && optionalUint256Decimal(value.balance) && optionalUint256Decimal(value.authorizedAmount) && optionalUint256Decimal(value.withdrawingAmount) && optionalUint256Decimal(value.availableAmount) && optionalUint256Decimal(value.requestedAmount) && optionalUint256Decimal(value.minimumAmount);
37121
+ }
37122
+ function isWithdrawalRejectionCode(value) {
37123
+ return value === "below_minimum" || value === "deadline_too_far" || value === "expired" || value === "insufficient_available" || value === "stale_nonce";
37124
+ }
37125
+ function optionalUint256Decimal(value) {
37126
+ return value === void 0 || isUint256Decimal(value);
37127
+ }
37128
+ function isAddressHex(value) {
37129
+ return typeof value === "string" && (0, import_viem28.isHex)(value, { strict: true }) && value.length === 42;
37130
+ }
37131
+ function isHash(value) {
37132
+ return typeof value === "string" && (0, import_viem28.isHex)(value, { strict: true }) && value.length === 66;
37133
+ }
37134
+ function isUint256Decimal(value) {
37135
+ if (typeof value !== "string" || value.length === 0 || value.length > 78) {
37136
+ return false;
37137
+ }
37138
+ if (!/^(0|[1-9]\d*)$/.test(value)) return false;
37139
+ return BigInt(value) <= 2n ** 256n - 1n;
37140
+ }
37141
+ function isBlockNumber(value) {
37142
+ return value === null || isUint256Decimal(value);
37143
+ }
37144
+ function isWithdrawNonceResponse(body, requestedAccount) {
37145
+ if (typeof body !== "object" || body === null) return false;
37146
+ const value = body;
37147
+ if (value.success !== true) return false;
37148
+ if (!isAddressHex(value.account)) return false;
37149
+ if (value.account.toLowerCase() !== requestedAccount.toLowerCase())
37150
+ return false;
37151
+ if (typeof value.chainId !== "string") return false;
37152
+ if (!/^(0|[1-9]\d*)$/.test(value.chainId)) return false;
37153
+ const isLastNull = value.lastWithdrawNonce === null;
37154
+ const lastNonceValid = isLastNull || isUint256Decimal(value.lastWithdrawNonce);
37155
+ if (!lastNonceValid) return false;
37156
+ if (!isUint256Decimal(value.nextWithdrawNonce)) return false;
37157
+ if (isLastNull) {
37158
+ return value.nextWithdrawNonce === "1";
37159
+ }
37160
+ const lastNonce = BigInt(value.lastWithdrawNonce);
37161
+ const nextNonce = BigInt(value.nextWithdrawNonce);
37162
+ const expectedNextNonce = lastNonce + 1n;
37163
+ if (expectedNextNonce > 2n ** 256n - 1n) return false;
37164
+ return nextNonce === expectedNextNonce;
37165
+ }
36788
37166
 
36789
37167
  // src/direct/escrow-payment.ts
36790
37168
  var GRANT_OP_TYPE = "grant";
@@ -36821,12 +37199,12 @@ var UINT256_MAX = (1n << 256n) - 1n;
36821
37199
  var ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
36822
37200
  var BYTES32_RE = /^0x[0-9a-fA-F]{64}$/;
36823
37201
  var SIGNATURE_RE = /^0x[0-9a-fA-F]{130}$/;
36824
- function isUint256Decimal(value, allowZero) {
37202
+ function isUint256Decimal2(value, allowZero) {
36825
37203
  const pattern = allowZero ? /^(0|[1-9]\d*)$/ : /^[1-9]\d*$/;
36826
37204
  return value.length <= UINT256_MAX.toString().length && pattern.test(value) && BigInt(value) <= UINT256_MAX;
36827
37205
  }
36828
37206
  function isValidAccessRecord(record) {
36829
- return BYTES32_RE.test(record.dataPointId) && isUint256Decimal(record.version, false) && ADDRESS_RE.test(record.accessor) && BYTES32_RE.test(record.recordId) && SIGNATURE_RE.test(record.signature);
37207
+ return BYTES32_RE.test(record.dataPointId) && isUint256Decimal2(record.version, false) && ADDRESS_RE.test(record.accessor) && BYTES32_RE.test(record.recordId) && SIGNATURE_RE.test(record.signature);
36830
37208
  }
36831
37209
  function validateSigningOperation(payerAddress, required) {
36832
37210
  if (!ADDRESS_RE.test(payerAddress)) {
@@ -36838,10 +37216,10 @@ function validateSigningOperation(payerAddress, required) {
36838
37216
  if (!ADDRESS_RE.test(required.asset || NATIVE_ASSET_ADDRESS)) {
36839
37217
  throw new Error("Payment asset must be a 20-byte EVM address");
36840
37218
  }
36841
- if (!isUint256Decimal(required.amount, true)) {
37219
+ if (!isUint256Decimal2(required.amount, true)) {
36842
37220
  throw new Error("Payment amount must be a canonical uint256 decimal");
36843
37221
  }
36844
- if (required.paymentNonce !== void 0 && !isUint256Decimal(required.paymentNonce, false)) {
37222
+ if (required.paymentNonce !== void 0 && !isUint256Decimal2(required.paymentNonce, false)) {
36845
37223
  throw new Error("Payment nonce must be a positive uint256 decimal");
36846
37224
  }
36847
37225
  const accessRecord = required.accessRecord;
@@ -36972,7 +37350,7 @@ function paymentResponseMetadataFromHeader(header) {
36972
37350
  const registrationFee = stringField(breakdown, "registrationFee");
36973
37351
  const dataAccessFee = stringField(breakdown, "dataAccessFee");
36974
37352
  const paidAt = stringField(result, "paidAt");
36975
- if (result?.success !== true || !opType || !opId || !BYTES32_RE.test(opId) || !payerAddress || !ADDRESS_RE.test(payerAddress) || !asset || !ADDRESS_RE.test(asset) || !amount || !isUint256Decimal(amount, true) || !paymentNonce || !isUint256Decimal(paymentNonce, false) || !registrationFee || !isUint256Decimal(registrationFee, true) || !dataAccessFee || !isUint256Decimal(dataAccessFee, true) || typeof breakdown?.registrationPaid !== "boolean" || !paidAt || !isCanonicalIsoTimestamp(paidAt)) {
37353
+ if (result?.success !== true || !opType || !opId || !BYTES32_RE.test(opId) || !payerAddress || !ADDRESS_RE.test(payerAddress) || !asset || !ADDRESS_RE.test(asset) || !amount || !isUint256Decimal2(amount, true) || !paymentNonce || !isUint256Decimal2(paymentNonce, false) || !registrationFee || !isUint256Decimal2(registrationFee, true) || !dataAccessFee || !isUint256Decimal2(dataAccessFee, true) || typeof breakdown?.registrationPaid !== "boolean" || !paidAt || !isCanonicalIsoTimestamp(paidAt)) {
36976
37354
  return void 0;
36977
37355
  }
36978
37356
  return {
@@ -37021,18 +37399,9 @@ async function authorizeEscrowPayment(params) {
37021
37399
  return toDirectPaymentReceipt(result);
37022
37400
  }
37023
37401
 
37024
- // src/direct/errors.ts
37025
- var PersonalServerReadError = class extends VanaError {
37026
- constructor(message, status, details) {
37027
- super(message, "DIRECT_PERSONAL_SERVER_READ_ERROR");
37028
- this.status = status;
37029
- this.details = details;
37030
- }
37031
- status;
37032
- details;
37033
- };
37034
-
37035
37402
  // src/direct/personal-server-read.ts
37403
+ var import_errors12 = require("./direct/errors.cjs");
37404
+ var import_errors13 = require("./errors.cjs");
37036
37405
  function asRecord2(value) {
37037
37406
  return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
37038
37407
  }
@@ -37062,21 +37431,21 @@ function isBytes32Hex(value) {
37062
37431
  return /^0x[0-9a-fA-F]{64}$/.test(value);
37063
37432
  }
37064
37433
  var UINT256_MAX2 = (1n << 256n) - 1n;
37065
- function isAddressHex(value) {
37434
+ function isAddressHex2(value) {
37066
37435
  return /^0x[0-9a-fA-F]{40}$/.test(value);
37067
37436
  }
37068
- function isUint256Decimal2(value, allowZero) {
37437
+ function isUint256Decimal3(value, allowZero) {
37069
37438
  const pattern = allowZero ? /^(0|[1-9]\d*)$/ : /^[1-9]\d*$/;
37070
37439
  return value.length <= UINT256_MAX2.toString().length && pattern.test(value) && BigInt(value) <= UINT256_MAX2;
37071
37440
  }
37072
37441
  function isValidDataAccessRecord(record) {
37073
- return isBytes32Hex(record.dataPointId) && isUint256Decimal2(record.version, false) && isAddressHex(record.accessor) && isBytes32Hex(record.recordId) && /^0x[0-9a-fA-F]{130}$/.test(record.signature);
37442
+ return isBytes32Hex(record.dataPointId) && isUint256Decimal3(record.version, false) && isAddressHex2(record.accessor) && isBytes32Hex(record.recordId) && /^0x[0-9a-fA-F]{130}$/.test(record.signature);
37074
37443
  }
37075
37444
  function parseLegacyGrantOperation(params) {
37076
37445
  const { challengeGrantId, challengeOpId, challengeOpType, grantId } = params;
37077
37446
  const opType = challengeOpType ?? GRANT_OP_TYPE;
37078
37447
  if (opType !== GRANT_OP_TYPE) {
37079
- throw new PersonalServerReadError(
37448
+ throw new import_errors12.PersonalServerReadError(
37080
37449
  "Personal Server payment challenge used an unsupported escrow op type",
37081
37450
  402,
37082
37451
  { opType: challengeOpType }
@@ -37084,14 +37453,14 @@ function parseLegacyGrantOperation(params) {
37084
37453
  }
37085
37454
  const opId = challengeOpId ?? challengeGrantId ?? grantId;
37086
37455
  if (!opId || !isBytes32Hex(opId)) {
37087
- throw new PersonalServerReadError(
37456
+ throw new import_errors12.PersonalServerReadError(
37088
37457
  "Personal Server payment challenge used an invalid escrow op id",
37089
37458
  402,
37090
37459
  { opId }
37091
37460
  );
37092
37461
  }
37093
37462
  if (opId.toLowerCase() !== grantId.toLowerCase()) {
37094
- throw new PersonalServerReadError(
37463
+ throw new import_errors12.PersonalServerReadError(
37095
37464
  "Personal Server payment challenge did not match the requested grant",
37096
37465
  402,
37097
37466
  { opId, grantId }
@@ -37121,7 +37490,7 @@ function parseCanonicalDataAccessAccept(value) {
37121
37490
  const accessRecord = parseAccessRecord(accept?.accessRecord);
37122
37491
  const acceptAsset = stringField2(accept, "asset");
37123
37492
  const acceptAmount = stringField2(accept, "amount");
37124
- if (!network || !payerAddress || !isAddressHex(payerAddress) || !opId || !isBytes32Hex(opId) || !asset || !isAddressHex(asset) || !amount || !isUint256Decimal2(amount, true) || !paymentNonce || !isUint256Decimal2(paymentNonce, false) || !accessRecord || !isValidDataAccessRecord(accessRecord) || payerAddress.toLowerCase() !== accessRecord.accessor.toLowerCase() || opId.toLowerCase() !== accessRecord.recordId.toLowerCase() || !acceptAsset || acceptAsset.toLowerCase() !== asset.toLowerCase() || acceptAmount !== amount) {
37493
+ if (!network || !payerAddress || !isAddressHex2(payerAddress) || !opId || !isBytes32Hex(opId) || !asset || !isAddressHex2(asset) || !amount || !isUint256Decimal3(amount, true) || !paymentNonce || !isUint256Decimal3(paymentNonce, false) || !accessRecord || !isValidDataAccessRecord(accessRecord) || payerAddress.toLowerCase() !== accessRecord.accessor.toLowerCase() || opId.toLowerCase() !== accessRecord.recordId.toLowerCase() || !acceptAsset || acceptAsset.toLowerCase() !== asset.toLowerCase() || acceptAmount !== amount) {
37125
37494
  return null;
37126
37495
  }
37127
37496
  return {
@@ -37137,7 +37506,7 @@ function parseCanonicalDataAccessAccept(value) {
37137
37506
  function parseCanonicalDataAccessPayment(params) {
37138
37507
  const { body, grantId, raw } = params;
37139
37508
  if (body.x402Version !== 1 || body.error !== "PAYMENT_REQUIRED") {
37140
- throw new PersonalServerReadError(
37509
+ throw new import_errors12.PersonalServerReadError(
37141
37510
  "Personal Server data-access payment response was not a canonical x402 challenge",
37142
37511
  402
37143
37512
  );
@@ -37176,20 +37545,20 @@ async function parsePersonalServerPaymentRequired(res, grantId) {
37176
37545
  "accepts"
37177
37546
  );
37178
37547
  if (hasAcceptsEnvelope && (body.x402Version !== 1 || body.error !== "PAYMENT_REQUIRED")) {
37179
- throw new PersonalServerReadError(
37548
+ throw new import_errors12.PersonalServerReadError(
37180
37549
  "Personal Server grant payment response was not a canonical x402 challenge",
37181
37550
  402
37182
37551
  );
37183
37552
  }
37184
37553
  const accept = preferredLegacyAccept(body);
37185
37554
  if (hasDataAccessMarker(body) && !accept) {
37186
- throw new PersonalServerReadError(
37555
+ throw new import_errors12.PersonalServerReadError(
37187
37556
  "Personal Server data-access payment challenge was untrusted or incomplete",
37188
37557
  402
37189
37558
  );
37190
37559
  }
37191
37560
  if (hasAcceptsEnvelope && !accept) {
37192
- throw new PersonalServerReadError(
37561
+ throw new import_errors12.PersonalServerReadError(
37193
37562
  "Personal Server grant payment challenge had no compatible escrow offer",
37194
37563
  402
37195
37564
  );
@@ -37206,8 +37575,8 @@ async function parsePersonalServerPaymentRequired(res, grantId) {
37206
37575
  const acceptAmount = stringField2(accept, "amount");
37207
37576
  const accessRecord2 = parseAccessRecord(accept.accessRecord);
37208
37577
  const hasAccessRecord = accept.accessRecord !== void 0;
37209
- if (!network || !payerAddress || !isAddressHex(payerAddress) || !opId || !isBytes32Hex(opId) || !asset || !isAddressHex(asset) || !amount || !isUint256Decimal2(amount, true) || !paymentNonce || !isUint256Decimal2(paymentNonce, false) || !acceptAsset || acceptAsset.toLowerCase() !== asset.toLowerCase() || acceptAmount !== amount || hasAccessRecord && (!accessRecord2 || !isValidDataAccessRecord(accessRecord2) || accessRecord2.accessor.toLowerCase() !== payerAddress.toLowerCase()) || amount === "0" && !accessRecord2) {
37210
- throw new PersonalServerReadError(
37578
+ if (!network || !payerAddress || !isAddressHex2(payerAddress) || !opId || !isBytes32Hex(opId) || !asset || !isAddressHex2(asset) || !amount || !isUint256Decimal3(amount, true) || !paymentNonce || !isUint256Decimal3(paymentNonce, false) || !acceptAsset || acceptAsset.toLowerCase() !== asset.toLowerCase() || acceptAmount !== amount || hasAccessRecord && (!accessRecord2 || !isValidDataAccessRecord(accessRecord2) || accessRecord2.accessor.toLowerCase() !== payerAddress.toLowerCase()) || amount === "0" && !accessRecord2) {
37579
+ throw new import_errors12.PersonalServerReadError(
37211
37580
  "Personal Server grant payment challenge was untrusted or incomplete",
37212
37581
  402
37213
37582
  );
@@ -37323,14 +37692,11 @@ async function parsePSError(response) {
37323
37692
  AccountPersonalServerLiteOwnerBindingError,
37324
37693
  AccountPersonalServerRegistrationError,
37325
37694
  BUILDER_REGISTRATION_TYPES,
37326
- BlockchainError,
37327
37695
  BrowserPlatformAdapter,
37328
- BuilderUnknownError,
37329
37696
  CLAIM_POLL_FLOOR_MS,
37330
37697
  CONTRACTS,
37331
37698
  CallbackStorage,
37332
37699
  ContractFactory,
37333
- ContractNotFoundError,
37334
37700
  DATA_ACCESS_OP_TYPE,
37335
37701
  DATA_REGISTRY_STATUS_ABI,
37336
37702
  DEFAULT_DERIVATIVE_STATUS_POLL_INTERVAL_MS,
@@ -37343,21 +37709,9 @@ async function parsePSError(response) {
37343
37709
  DERIVATIVE_QUESTIONS_PATH,
37344
37710
  DERIVATIVE_STATUS_PATH,
37345
37711
  DataFileEnvelopeSchema,
37346
- DataPointDeletedError,
37347
- DataPointNotFoundError,
37348
37712
  DataPointStatus,
37349
- DataPointVersionConflictError,
37350
- DerivativeComputeUnavailableError,
37351
- DerivativeCycleError,
37352
- DerivativeDerivedScopeRequiredError,
37353
37713
  DerivativeErrorCodeSchema,
37354
- DerivativeQuestionFailedError,
37355
- DerivativeQuestionInvalidError,
37356
- DerivativeQuestionNotFoundError,
37357
- DerivativeQuestionRejectedError,
37358
37714
  DerivativeQuestionSchema,
37359
- DerivativeQuestionTimeoutError,
37360
- DerivativeSourceNotGrantedError,
37361
37715
  DerivativeStatusSchema,
37362
37716
  DropboxStorage,
37363
37717
  ECIESError,
@@ -37365,6 +37719,8 @@ async function parsePSError(response) {
37365
37719
  ENCLAVE_TRUST_ANCHORS,
37366
37720
  ENCLAVE_WALLET_PURPOSE,
37367
37721
  ESCROW_DEPOSIT_ABI,
37722
+ EscrowWithdrawalLifecycleError,
37723
+ EscrowWithdrawalRejectionError,
37368
37724
  ExpiredTokenError,
37369
37725
  FEE_REGISTRY_ABI,
37370
37726
  GENERIC_PAYMENT_TYPES,
@@ -37372,35 +37728,26 @@ async function parsePSError(response) {
37372
37728
  GRANT_REGISTRATION_TYPES,
37373
37729
  GRANT_REVOCATION_TYPES,
37374
37730
  GoogleDriveStorage,
37375
- GrantInvalidError,
37376
37731
  InMemoryTokenStore,
37377
37732
  IngestResponseSchema,
37378
- InvalidConfigurationError,
37379
37733
  InvalidScopeEntryError,
37380
37734
  InvalidSignatureError,
37381
37735
  IpfsStorage,
37382
37736
  JOB_OPERATIONS,
37383
37737
  JOB_PROTOCOL_VERSION,
37738
+ JOB_RESULT_CHUNK_BYTES,
37739
+ JOB_RESULT_FORMAT_VERSION,
37384
37740
  JOB_STATES,
37385
37741
  JobEnvelopeError,
37386
- JobIdTakenError,
37387
- JobNotFoundError,
37388
- JobRejectedError,
37389
- JobRequestTooLargeError,
37390
- JobTimeoutError,
37391
- JobTransportError,
37392
- JobsClientError,
37393
37742
  LINEAGE_FIELD,
37394
37743
  LINEAGE_KEY,
37395
37744
  LineageEntrySchema,
37396
37745
  LineageGraphSchema,
37397
37746
  LineageNodeSchema,
37398
- LineageReadError,
37399
37747
  MASTER_KEY_MESSAGE,
37400
37748
  MASTER_SIGNATURE_DELIVERY_MAX_AGE_SECONDS,
37401
37749
  MASTER_SIGNATURE_DELIVERY_VERSION,
37402
37750
  MAX_ATTEMPTS,
37403
- MAX_INLINE_RESULT_BYTES,
37404
37751
  MAX_JOB_DEADLINE_SECONDS,
37405
37752
  MAX_LEASE_SECONDS,
37406
37753
  MAX_LINEAGE_SOURCES,
@@ -37411,12 +37758,9 @@ async function parsePSError(response) {
37411
37758
  MissingAuthError,
37412
37759
  NATIVE_ASSET_ADDRESS,
37413
37760
  NATIVE_VANA_ASSET,
37414
- NetworkError,
37415
37761
  NodeECIESProvider,
37416
37762
  NodePlatformAdapter,
37417
- NonceError,
37418
37763
  OAuthClient,
37419
- OwnerNotReadyError,
37420
37764
  PERSONAL_SERVER_LITE_OWNER_BINDING_PREFIX,
37421
37765
  PERSONAL_SERVER_LITE_OWNER_BINDING_PURPOSE,
37422
37766
  PERSONAL_SERVER_LITE_OWNER_BINDING_VERSION,
@@ -37425,9 +37769,6 @@ async function parsePSError(response) {
37425
37769
  PKCE_CHALLENGE_PATTERN,
37426
37770
  PKCE_VERIFIER_PATTERN,
37427
37771
  PSError,
37428
- PermissionError,
37429
- PersonalServerError,
37430
- PersonalServerWriteError,
37431
37772
  PinataStorage,
37432
37773
  QUESTION_STATUSES,
37433
37774
  QuestionDeleteResultSchema,
@@ -37438,42 +37779,26 @@ async function parsePSError(response) {
37438
37779
  RECORD_DATA_ACCESS_TYPES,
37439
37780
  REGISTRATION_KIND_FOR_OP,
37440
37781
  RESERVED_WRITE_KEYS,
37441
- ReadOnlyError,
37442
37782
  RedactedLineageNodeSchema,
37443
- RelayerError,
37444
37783
  SCOPE_ACTIONS,
37445
37784
  SEALED_ENVELOPE_VERSION,
37446
37785
  SERVER_REGISTRATION_TYPES,
37447
37786
  ScopeSchema,
37448
- SerializationError,
37449
- ServerUrlMismatchError,
37450
- SignatureError,
37451
37787
  StorageError,
37452
37788
  StorageManager,
37453
37789
  TOMBSTONE_DATA_HASH,
37454
37790
  TOMBSTONE_DATA_HASH_PREIMAGE,
37455
37791
  TOMBSTONE_METADATA_HASH,
37456
37792
  TOMBSTONE_METADATA_HASH_PREIMAGE,
37457
- TransactionPendingError,
37458
37793
  USER_PS_ID_DOMAIN,
37459
- UserRejectedRequestError,
37460
- VanaError,
37461
37794
  VanaStorage,
37795
+ WITHDRAW_AUTHORIZATION_TYPES,
37462
37796
  WRITER_ATTRIBUTION_KEY,
37463
37797
  WRITE_CONTENT_DISPOSITION_HEADER,
37464
37798
  WRITE_FILENAME_HEADER,
37465
37799
  WRITE_METADATA_HEADER,
37466
37800
  WRITE_SESSION_PATH,
37467
37801
  WRITE_SIGNATURE_HEADER,
37468
- WriteConflictError,
37469
- WriteForbiddenError,
37470
- WriteLineageError,
37471
- WriteRejectedError,
37472
- WriteRequestError,
37473
- WriteSessionError,
37474
- WriteSessionExpiredError,
37475
- WriteTransportError,
37476
- WriteUnauthorizedError,
37477
37802
  appRootPreimage,
37478
37803
  askPersonalServer,
37479
37804
  assertDerivedScopeNaming,
@@ -37496,6 +37821,7 @@ async function parsePSError(response) {
37496
37821
  buildPersonalServerRegistrationTypedData,
37497
37822
  buildSetDataPointStatusRequest,
37498
37823
  buildWeb3SignedHeader,
37824
+ buildWithdrawAuthorizationTypedData,
37499
37825
  builderRegistrationDomain,
37500
37826
  canonicalJobRequestBytes,
37501
37827
  chains,
@@ -37578,6 +37904,7 @@ async function parsePSError(response) {
37578
37904
  normalizeBinaryMimeType,
37579
37905
  openJobRequest,
37580
37906
  openJobResult,
37907
+ openJobResultStream,
37581
37908
  openWriteSession,
37582
37909
  parsePSError,
37583
37910
  parsePersonalServerPaymentRequired,
@@ -37603,6 +37930,7 @@ async function parsePSError(response) {
37603
37930
  scopeToPathSegments,
37604
37931
  sealJobRequest,
37605
37932
  sealJobResult,
37933
+ sealJobResultStream,
37606
37934
  serializeECIES,
37607
37935
  serverRegistrationDomain,
37608
37936
  sessionCoversScope,
@@ -37621,7 +37949,9 @@ async function parsePSError(response) {
37621
37949
  verifyWeb3Signed,
37622
37950
  waitForDerivativeStatus,
37623
37951
  waitForQuestion,
37952
+ withdrawAuthorizationDomain,
37624
37953
  writeData,
37625
- writePersonalServerData
37954
+ writePersonalServerData,
37955
+ ...require("./errors.cjs")
37626
37956
  });
37627
37957
  //# sourceMappingURL=index.node.cjs.map