@opendatalabs/vana-sdk 3.17.0 → 3.18.1

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 (53) hide show
  1. package/README.md +6 -3
  2. package/dist/direct/personal-server-read.cjs +20 -1
  3. package/dist/direct/personal-server-read.cjs.map +1 -1
  4. package/dist/direct/personal-server-read.js +23 -1
  5. package/dist/direct/personal-server-read.js.map +1 -1
  6. package/dist/errors.cjs +27 -0
  7. package/dist/errors.cjs.map +1 -1
  8. package/dist/errors.d.ts +67 -0
  9. package/dist/errors.js +24 -0
  10. package/dist/errors.js.map +1 -1
  11. package/dist/index.browser.d.ts +2 -1
  12. package/dist/index.browser.js +731 -311
  13. package/dist/index.browser.js.map +4 -4
  14. package/dist/index.node.cjs +743 -313
  15. package/dist/index.node.cjs.map +4 -4
  16. package/dist/index.node.d.ts +2 -1
  17. package/dist/index.node.js +731 -311
  18. package/dist/index.node.js.map +4 -4
  19. package/dist/protocol/data-point-deletion.cjs +220 -0
  20. package/dist/protocol/data-point-deletion.cjs.map +1 -0
  21. package/dist/protocol/data-point-deletion.d.ts +180 -0
  22. package/dist/protocol/data-point-deletion.js +193 -0
  23. package/dist/protocol/data-point-deletion.js.map +1 -0
  24. package/dist/protocol/data-point-deletion.test.d.ts +1 -0
  25. package/dist/protocol/gateway.cjs +145 -32
  26. package/dist/protocol/gateway.cjs.map +1 -1
  27. package/dist/protocol/gateway.d.ts +42 -3
  28. package/dist/protocol/gateway.js +156 -32
  29. package/dist/protocol/gateway.js.map +1 -1
  30. package/dist/protocol/lineage.cjs +9 -4
  31. package/dist/protocol/lineage.cjs.map +1 -1
  32. package/dist/protocol/lineage.d.ts +21 -12
  33. package/dist/protocol/lineage.js +9 -4
  34. package/dist/protocol/lineage.js.map +1 -1
  35. package/dist/protocol/personal-server-data.cjs +20 -1
  36. package/dist/protocol/personal-server-data.cjs.map +1 -1
  37. package/dist/protocol/personal-server-data.js +23 -1
  38. package/dist/protocol/personal-server-data.js.map +1 -1
  39. package/dist/storage/index.cjs.map +1 -1
  40. package/dist/storage/index.d.ts +1 -1
  41. package/dist/storage/index.js.map +1 -1
  42. package/dist/storage/providers/vana-storage.cjs +66 -0
  43. package/dist/storage/providers/vana-storage.cjs.map +1 -1
  44. package/dist/storage/providers/vana-storage.d.ts +26 -0
  45. package/dist/storage/providers/vana-storage.js +66 -0
  46. package/dist/storage/providers/vana-storage.js.map +1 -1
  47. package/dist/utils/response-body.cjs +46 -0
  48. package/dist/utils/response-body.cjs.map +1 -0
  49. package/dist/utils/response-body.d.ts +26 -0
  50. package/dist/utils/response-body.js +20 -0
  51. package/dist/utils/response-body.js.map +1 -0
  52. package/dist/utils/response-body.test.d.ts +1 -0
  53. package/package.json +1 -1
@@ -1187,7 +1187,10 @@ __export(index_node_exports, {
1187
1187
  DATA_ACCESS_OP_TYPE: () => DATA_ACCESS_OP_TYPE,
1188
1188
  DATA_REGISTRY_STATUS_ABI: () => DATA_REGISTRY_STATUS_ABI,
1189
1189
  DataFileEnvelopeSchema: () => DataFileEnvelopeSchema,
1190
+ DataPointDeletedError: () => DataPointDeletedError,
1191
+ DataPointNotFoundError: () => DataPointNotFoundError,
1190
1192
  DataPointStatus: () => DataPointStatus,
1193
+ DataPointVersionConflictError: () => DataPointVersionConflictError,
1191
1194
  DropboxStorage: () => DropboxStorage,
1192
1195
  ECIESError: () => ECIESError,
1193
1196
  ESCROW_DEPOSIT_ABI: () => ESCROW_DEPOSIT_ABI2,
@@ -1247,6 +1250,10 @@ __export(index_node_exports, {
1247
1250
  SignatureError: () => SignatureError,
1248
1251
  StorageError: () => StorageError,
1249
1252
  StorageManager: () => StorageManager,
1253
+ TOMBSTONE_DATA_HASH: () => TOMBSTONE_DATA_HASH,
1254
+ TOMBSTONE_DATA_HASH_PREIMAGE: () => TOMBSTONE_DATA_HASH_PREIMAGE,
1255
+ TOMBSTONE_METADATA_HASH: () => TOMBSTONE_METADATA_HASH,
1256
+ TOMBSTONE_METADATA_HASH_PREIMAGE: () => TOMBSTONE_METADATA_HASH_PREIMAGE,
1250
1257
  TransactionPendingError: () => TransactionPendingError,
1251
1258
  UserRejectedRequestError: () => UserRejectedRequestError,
1252
1259
  VanaError: () => VanaError,
@@ -1271,6 +1278,8 @@ __export(index_node_exports, {
1271
1278
  authorizeEscrowPayment: () => authorizeEscrowPayment,
1272
1279
  authorizeGrantPayment: () => authorizeGrantPayment,
1273
1280
  binaryWriteSignedBytes: () => binaryWriteSignedBytes,
1281
+ buildDataPointDeletionSignature: () => buildDataPointDeletionSignature,
1282
+ buildDataPointDeletionTypedData: () => buildDataPointDeletionTypedData,
1274
1283
  buildDepositNativeRequest: () => buildDepositNativeRequest,
1275
1284
  buildDepositTokenRequest: () => buildDepositTokenRequest,
1276
1285
  buildEscrowPaymentHeader: () => buildEscrowPaymentHeader,
@@ -1288,6 +1297,7 @@ __export(index_node_exports, {
1288
1297
  clearContractCache: () => clearContractCache,
1289
1298
  computeBodyHash: () => computeBodyHash,
1290
1299
  computePkceChallenge: () => computePkceChallenge,
1300
+ computeTombstoneHash: () => computeTombstoneHash,
1291
1301
  contractCacheForTesting: () => contractCacheForTesting,
1292
1302
  createBrowserPlatformAdapter: () => createBrowserPlatformAdapter,
1293
1303
  createDataFileEnvelope: () => createDataFileEnvelope,
@@ -1299,11 +1309,13 @@ __export(index_node_exports, {
1299
1309
  createPlatformAdapterFor: () => createPlatformAdapterFor,
1300
1310
  createPlatformAdapterSafe: () => createPlatformAdapterSafe,
1301
1311
  createVanaStorageProvider: () => createVanaStorageProvider,
1312
+ createViemDataPointDeletionSigner: () => createViemDataPointDeletionSigner,
1302
1313
  createViemPersonalServerLiteOwnerBindingSigner: () => createViemPersonalServerLiteOwnerBindingSigner,
1303
1314
  createViemPersonalServerRegistrationSigner: () => createViemPersonalServerRegistrationSigner,
1304
1315
  dataRegistryContractAddress: () => dataRegistryContractAddress,
1305
1316
  dataRegistryDomain: () => dataRegistryDomain,
1306
1317
  decryptWithPassword: () => decryptWithPassword,
1318
+ deleteDataPoint: () => deleteDataPoint,
1307
1319
  deriveDataPointId: () => deriveDataPointId,
1308
1320
  deriveMasterKey: () => deriveMasterKey,
1309
1321
  deriveScopeKey: () => deriveScopeKey,
@@ -1339,10 +1351,12 @@ __export(index_node_exports, {
1339
1351
  grantRevocationDomain: () => grantRevocationDomain,
1340
1352
  hasAction: () => hasAction,
1341
1353
  isDataPointId: () => isDataPointId,
1354
+ isDataPointTombstone: () => isDataPointTombstone,
1342
1355
  isDataPortabilityGatewayConfig: () => isDataPortabilityGatewayConfig,
1343
1356
  isECIESEncrypted: () => isECIESEncrypted,
1344
1357
  isPlatformSupported: () => isPlatformSupported,
1345
1358
  isRedactedLineageNode: () => isRedactedLineageNode,
1359
+ isTombstoneHashes: () => isTombstoneHashes,
1346
1360
  mainnetServices: () => mainnetServices,
1347
1361
  moksha: () => moksha,
1348
1362
  mokshaServices: () => mokshaServices,
@@ -1377,6 +1391,7 @@ __export(index_node_exports, {
1377
1391
  signPersonalServerRegistrationWithAccount: () => signPersonalServerRegistrationWithAccount,
1378
1392
  toDirectFeeBreakdown: () => toDirectFeeBreakdown,
1379
1393
  toDirectPaymentReceipt: () => toDirectPaymentReceipt,
1394
+ tombstoneDeletedAt: () => tombstoneDeletedAt,
1380
1395
  tryGrantPermissions: () => tryGrantPermissions,
1381
1396
  vanaMainnet: () => vanaMainnet2,
1382
1397
  verifyGrantRegistration: () => verifyGrantRegistration,
@@ -1598,6 +1613,27 @@ var LineageReadError = class extends VanaError {
1598
1613
  errorCode;
1599
1614
  details;
1600
1615
  };
1616
+ var DataPointDeletedError = class extends VanaError {
1617
+ constructor(message, details = {}) {
1618
+ super(message, "DATA_POINT_DELETED");
1619
+ this.details = details;
1620
+ }
1621
+ details;
1622
+ };
1623
+ var DataPointNotFoundError = class extends VanaError {
1624
+ constructor(message, details = {}) {
1625
+ super(message, "DATA_POINT_NOT_FOUND");
1626
+ this.details = details;
1627
+ }
1628
+ details;
1629
+ };
1630
+ var DataPointVersionConflictError = class extends VanaError {
1631
+ constructor(message, details = {}) {
1632
+ super(message, "DATA_POINT_VERSION_CONFLICT");
1633
+ this.details = details;
1634
+ }
1635
+ details;
1636
+ };
1601
1637
 
1602
1638
  // src/contracts/contractController.ts
1603
1639
  var import_viem3 = require("viem");
@@ -29354,6 +29390,22 @@ function getProtocolNetworkChainId(network) {
29354
29390
  return PROTOCOL_NETWORK_CHAIN_IDS[network];
29355
29391
  }
29356
29392
 
29393
+ // src/utils/response-body.ts
29394
+ function isPlainObject(value) {
29395
+ return typeof value === "object" && value !== null && !Array.isArray(value);
29396
+ }
29397
+ async function readJsonValue(res) {
29398
+ try {
29399
+ return await res.json();
29400
+ } catch {
29401
+ return null;
29402
+ }
29403
+ }
29404
+ async function readJsonObject(res) {
29405
+ const value = await readJsonValue(res);
29406
+ return isPlainObject(value) ? value : {};
29407
+ }
29408
+
29357
29409
  // src/storage/providers/vana-storage.ts
29358
29410
  var DEFAULT_ENDPOINT = "https://storage.vana.org";
29359
29411
  var LEGACY_BLOB_PATH_PREFIX = "/v1/blobs";
@@ -29525,6 +29577,65 @@ var VanaStorage = class {
29525
29577
  }
29526
29578
  return true;
29527
29579
  }
29580
+ /**
29581
+ * Delete every version's blob under `(owner, scope)` --
29582
+ * `DELETE {prefix}/{owner}/{scope}` on vana-storage, signed with the same
29583
+ * Web3Signed header as uploads (aud = endpoint origin, empty bodyHash).
29584
+ * The worker accepts the owner's own signature or a personal server the
29585
+ * owner registered with the gateway.
29586
+ *
29587
+ * @param ownerAddress - Must equal the provider's configured owner; a
29588
+ * mismatch throws before anything is signed so this wallet can never be
29589
+ * induced to sign a delete for another namespace.
29590
+ * @param scope - The scope segment, e.g. `"instagram.profile"`.
29591
+ */
29592
+ async deleteScope(ownerAddress, scope) {
29593
+ if (ownerAddress.toLowerCase() !== this.ownerAddress) {
29594
+ throw new StorageError(
29595
+ `deleteScope owner '${ownerAddress}' does not match the configured owner '${this.ownerAddress}'`,
29596
+ "INVALID_OWNER",
29597
+ "vana-storage"
29598
+ );
29599
+ }
29600
+ if (scope.length === 0 || scope.includes("/") || isTraversalSegment(scope)) {
29601
+ throw new StorageError(
29602
+ `scope must be a single non-empty path segment, got '${scope}'`,
29603
+ "INVALID_SCOPE",
29604
+ "vana-storage"
29605
+ );
29606
+ }
29607
+ const path = `${this.blobPathPrefix}/${this.ownerAddress}/${encodeURIComponent(scope)}`;
29608
+ const header = await this.signRequest("DELETE", path);
29609
+ let response;
29610
+ try {
29611
+ response = await this.fetchImpl(`${this.endpoint}${path}`, {
29612
+ method: "DELETE",
29613
+ headers: { authorization: header }
29614
+ });
29615
+ } catch (cause) {
29616
+ throw new StorageError(
29617
+ `vana-storage scope delete network error: ${describe(cause)}`,
29618
+ "DELETE_ERROR",
29619
+ "vana-storage",
29620
+ { cause: cause instanceof Error ? cause : void 0 }
29621
+ );
29622
+ }
29623
+ if (!response.ok) {
29624
+ const responseText = await safeText(response);
29625
+ throw new StorageError(
29626
+ `vana-storage scope delete failed: ${response.status} ${response.statusText} - ${responseText}`,
29627
+ "DELETE_FAILED",
29628
+ "vana-storage"
29629
+ );
29630
+ }
29631
+ const body = await readJsonObject(response);
29632
+ return {
29633
+ deleted: typeof body["deleted"] === "boolean" ? body["deleted"] : true,
29634
+ scope: typeof body["scope"] === "string" ? body["scope"] : scope,
29635
+ count: nonNegativeInteger(body["count"]) ?? 0,
29636
+ totalBytes: nonNegativeInteger(body["totalBytes"]) ?? 0
29637
+ };
29638
+ }
29528
29639
  getConfig() {
29529
29640
  return {
29530
29641
  name: "vana-storage",
@@ -29653,6 +29764,12 @@ function encodeRelativePath(filename) {
29653
29764
  }
29654
29765
  return parts.map((p) => encodeURIComponent(p)).join("/");
29655
29766
  }
29767
+ function isTraversalSegment(segment) {
29768
+ return segment === "." || segment === "..";
29769
+ }
29770
+ function nonNegativeInteger(value) {
29771
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
29772
+ }
29656
29773
  function describe(value) {
29657
29774
  if (value instanceof Error) return value.message;
29658
29775
  return String(value);
@@ -33756,270 +33873,12 @@ function buildMarkDataPointUnavailableRequest(config, input) {
33756
33873
  });
33757
33874
  }
33758
33875
 
33759
- // src/protocol/data-file.ts
33760
- var import_zod = require("zod");
33761
- var DataFileEnvelopeSchema = import_zod.z.object({
33762
- $schema: import_zod.z.string().url().optional(),
33763
- version: import_zod.z.literal("1.0"),
33764
- scope: import_zod.z.string(),
33765
- schemaId: import_zod.z.string().optional(),
33766
- collectedAt: import_zod.z.string().datetime(),
33767
- data: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown())
33768
- });
33769
- function createDataFileEnvelope(scope, collectedAt, data, schemaUrl, schemaId) {
33770
- return {
33771
- ...schemaUrl !== void 0 && { $schema: schemaUrl },
33772
- ...schemaId !== void 0 && { schemaId },
33773
- version: "1.0",
33774
- scope,
33775
- collectedAt,
33776
- data
33777
- };
33778
- }
33779
- var IngestResponseSchema = import_zod.z.object({
33780
- scope: import_zod.z.string(),
33781
- collectedAt: import_zod.z.string().datetime(),
33782
- status: import_zod.z.enum(["stored", "syncing"])
33783
- });
33784
-
33785
- // src/protocol/personal-server-data.ts
33786
- function personalServerDataReadPath(scope) {
33787
- return `/v1/data/${encodeURIComponent(scope)}`;
33788
- }
33789
- async function buildPersonalServerDataReadRequest(params) {
33790
- const path = personalServerDataReadPath(params.scope);
33791
- const baseUrl = params.personalServerUrl.replace(/\/+$/, "");
33792
- const audience = params.audience ?? baseUrl;
33793
- const headers = new Headers(params.headers);
33794
- headers.set(
33795
- "Authorization",
33796
- await buildWeb3SignedHeader({
33797
- aud: audience,
33798
- grantId: params.grantId,
33799
- method: "GET",
33800
- signMessage: params.signMessage,
33801
- uri: path
33802
- })
33803
- );
33804
- return new Request(`${baseUrl}${path}`, {
33805
- headers,
33806
- method: "GET"
33807
- });
33808
- }
33809
- async function readPersonalServerData(params) {
33810
- const fetchFn = params.fetch ?? globalThis.fetch;
33811
- if (fetchFn === void 0) {
33812
- throw new Error("No fetch implementation available");
33813
- }
33814
- const request = await buildPersonalServerDataReadRequest(params);
33815
- const response = await fetchFn(request);
33816
- if (!response.ok) {
33817
- throw new Error(
33818
- `Personal Server data read failed: ${response.status} ${response.statusText}`
33819
- );
33820
- }
33821
- return DataFileEnvelopeSchema.parse(await response.json());
33822
- }
33823
-
33824
- // src/protocol/scopes.ts
33825
- var import_zod2 = require("zod");
33826
- var SOURCE_RE = /^[a-z0-9][a-z0-9_]*$/;
33827
- var TAIL_SEGMENT_RE = /^[a-zA-Z0-9][a-zA-Z0-9_]*$/;
33828
- var ScopeSchema = import_zod2.z.string().refine(
33829
- (scope) => {
33830
- const parts = scope.split(".");
33831
- if (parts.length < 2 || parts.length > 3) return false;
33832
- const [source, ...tail] = parts;
33833
- return SOURCE_RE.test(source) && tail.every((part) => TAIL_SEGMENT_RE.test(part));
33834
- },
33835
- {
33836
- message: "Scope must be {source}.{category}[.{subcategory}]; source lowercase, tail may keep the historical camelCase form (e.g. spotify.savedTracks)"
33837
- }
33838
- );
33839
- function parseScope(scope) {
33840
- const validated = ScopeSchema.parse(scope);
33841
- const parts = validated.split(".");
33842
- return {
33843
- source: parts[0],
33844
- category: parts[1],
33845
- subcategory: parts[2],
33846
- raw: validated
33847
- };
33848
- }
33849
- function scopeToPathSegments(scope) {
33850
- const parsed = parseScope(scope);
33851
- const segments = [parsed.source, parsed.category];
33852
- if (parsed.subcategory) {
33853
- segments.push(parsed.subcategory);
33854
- }
33855
- return segments;
33856
- }
33857
- function scopeMatchesPattern(requestedScope, grantPattern) {
33858
- if (grantPattern === "*") return true;
33859
- if (grantPattern.endsWith(".*")) {
33860
- const prefix = grantPattern.slice(0, -1);
33861
- return requestedScope.startsWith(prefix);
33862
- }
33863
- return requestedScope === grantPattern;
33864
- }
33865
- function scopeCoveredByGrant(requestedScope, grantedScopes) {
33866
- return grantedScopes.some(
33867
- (pattern) => scopeMatchesPattern(requestedScope, pattern)
33868
- );
33869
- }
33870
-
33871
- // src/protocol/scope-actions.ts
33872
- var SCOPE_ACTIONS = ["read", "write"];
33873
- var InvalidScopeEntryError = class extends Error {
33874
- /** The offending entry, verbatim (unknown because it may not be a string). */
33875
- entry;
33876
- constructor(entry, reason) {
33877
- super(`Invalid scope entry ${describeValue(entry)}: ${reason}`);
33878
- this.name = "InvalidScopeEntryError";
33879
- this.entry = entry;
33880
- }
33881
- };
33882
- var OPERATION_SEPARATOR = ":";
33883
- function describeValue(value) {
33884
- if (typeof value === "string") return JSON.stringify(value);
33885
- if (value === null) return "null";
33886
- return `[${typeof value}]`;
33887
- }
33888
- var OPERATION_BY_PREFIX = {
33889
- write: "write"
33890
- };
33891
- function assertScopePart(entry, scope) {
33892
- if (scope.length === 0) {
33893
- throw new InvalidScopeEntryError(entry, "scope part is empty");
33894
- }
33895
- if (scope.includes(OPERATION_SEPARATOR)) {
33896
- throw new InvalidScopeEntryError(
33897
- entry,
33898
- `scope part must not contain "${OPERATION_SEPARATOR}"`
33899
- );
33900
- }
33901
- }
33902
- function parseScopeEntry(entry) {
33903
- const raw = entry;
33904
- if (typeof raw !== "string") {
33905
- throw new InvalidScopeEntryError(raw, "entry must be a string");
33906
- }
33907
- const separatorIndex = entry.indexOf(OPERATION_SEPARATOR);
33908
- if (separatorIndex === -1) {
33909
- assertScopePart(entry, entry);
33910
- return { scope: entry, action: "read" };
33911
- }
33912
- const prefix = entry.slice(0, separatorIndex);
33913
- const scope = entry.slice(separatorIndex + 1);
33914
- const action = Object.hasOwn(OPERATION_BY_PREFIX, prefix) ? OPERATION_BY_PREFIX[prefix] : void 0;
33915
- if (action === void 0) {
33916
- throw new InvalidScopeEntryError(
33917
- entry,
33918
- `unknown operation "${prefix}" (known: ${Object.keys(OPERATION_BY_PREFIX).join(", ")}; read has no prefix)`
33919
- );
33920
- }
33921
- assertScopePart(entry, scope);
33922
- return { scope, action };
33923
- }
33924
- function formatScopeEntry(parsed) {
33925
- const { scope, action } = parsed;
33926
- assertScopePart(scope, scope);
33927
- if (action === "read") return scope;
33928
- const prefix = Object.entries(OPERATION_BY_PREFIX).find(
33929
- ([, candidate]) => candidate === action
33930
- )?.[0];
33931
- if (prefix === void 0) {
33932
- throw new InvalidScopeEntryError(
33933
- scope,
33934
- `unknown action ${describeValue(action)} (known: ${SCOPE_ACTIONS.join(", ")})`
33935
- );
33936
- }
33937
- return `${prefix}${OPERATION_SEPARATOR}${scope}`;
33938
- }
33939
- function compareScopes(a, b) {
33940
- if (a < b) return -1;
33941
- if (a > b) return 1;
33942
- return 0;
33943
- }
33944
- function sortActions(actions) {
33945
- const present = new Set(actions);
33946
- return SCOPE_ACTIONS.filter((action) => present.has(action));
33947
- }
33948
- function grantPermissions(scopes) {
33949
- const byScope = /* @__PURE__ */ new Map();
33950
- for (const entry of scopes) {
33951
- const { scope, action } = parseScopeEntry(entry);
33952
- let actions = byScope.get(scope);
33953
- if (actions === void 0) {
33954
- actions = /* @__PURE__ */ new Set();
33955
- byScope.set(scope, actions);
33956
- }
33957
- actions.add(action);
33958
- }
33959
- return [...byScope.keys()].sort(compareScopes).map((scope) => ({
33960
- scope,
33961
- actions: sortActions(byScope.get(scope) ?? [])
33962
- }));
33963
- }
33964
- function permissionsToScopes(permissions) {
33965
- const byScope = /* @__PURE__ */ new Map();
33966
- for (const { scope, actions } of permissions) {
33967
- let merged = byScope.get(scope);
33968
- if (merged === void 0) {
33969
- merged = /* @__PURE__ */ new Set();
33970
- byScope.set(scope, merged);
33971
- }
33972
- for (const action of actions) {
33973
- if (!SCOPE_ACTIONS.includes(action)) {
33974
- throw new InvalidScopeEntryError(
33975
- scope,
33976
- `unknown action ${describeValue(action)} (known: ${SCOPE_ACTIONS.join(", ")})`
33977
- );
33978
- }
33979
- merged.add(action);
33980
- }
33981
- }
33982
- const entries = [];
33983
- for (const scope of [...byScope.keys()].sort(compareScopes)) {
33984
- for (const action of sortActions(byScope.get(scope) ?? [])) {
33985
- entries.push(formatScopeEntry({ scope, action }));
33986
- }
33987
- }
33988
- return entries;
33989
- }
33990
- function hasAction(scopes, scope, action) {
33991
- if (scope.includes(OPERATION_SEPARATOR)) return false;
33992
- for (const entry of scopes) {
33993
- let parsed;
33994
- try {
33995
- parsed = parseScopeEntry(entry);
33996
- } catch (error) {
33997
- if (error instanceof InvalidScopeEntryError) continue;
33998
- throw error;
33999
- }
34000
- if (parsed.action === action && scopeMatchesPattern(scope, parsed.scope)) {
34001
- return true;
34002
- }
34003
- }
34004
- return false;
34005
- }
34006
- function tryGrantPermissions(scopes) {
34007
- try {
34008
- return grantPermissions(scopes);
34009
- } catch (error) {
34010
- if (error instanceof InvalidScopeEntryError) return void 0;
34011
- throw error;
34012
- }
34013
- }
34014
-
34015
- // src/protocol/personal-server-write.ts
34016
- var import_sha25 = require("@noble/hashes/sha2");
33876
+ // src/protocol/data-point-deletion.ts
34017
33877
  var import_viem22 = require("viem");
34018
- var import_zod4 = require("zod");
34019
33878
 
34020
33879
  // src/protocol/lineage.ts
34021
33880
  var import_viem21 = require("viem");
34022
- var import_zod3 = require("zod");
33881
+ var import_zod = require("zod");
34023
33882
 
34024
33883
  // src/protocol/personal-server-error-body.ts
34025
33884
  function isRecord2(value) {
@@ -34111,10 +33970,10 @@ function deriveDataPointId(ownerAddress, scope) {
34111
33970
  )
34112
33971
  );
34113
33972
  }
34114
- var DataPointIdSchema = import_zod3.z.string().regex(DATA_POINT_ID_PATTERN).transform((value) => value.toLowerCase());
33973
+ var DataPointIdSchema = import_zod.z.string().regex(DATA_POINT_ID_PATTERN).transform((value) => value.toLowerCase());
34115
33974
  var VERSION_PATTERN = /^[1-9]\d*$/;
34116
33975
  var NODE_VERSION_PATTERN = /^(0|[1-9]\d*)$/;
34117
- var VersionSchema = import_zod3.z.union([import_zod3.z.string(), import_zod3.z.number()]).transform(String).refine((value) => NODE_VERSION_PATTERN.test(value), {
33976
+ var VersionSchema = import_zod.z.union([import_zod.z.string(), import_zod.z.number()]).transform(String).refine((value) => NODE_VERSION_PATTERN.test(value), {
34118
33977
  message: "version must be a decimal integer"
34119
33978
  });
34120
33979
  var ViewVersionSchema = VersionSchema.refine(
@@ -34138,44 +33997,49 @@ function assertDerivedScopeNaming(derivedScope, sourceScopes) {
34138
33997
  }
34139
33998
  }
34140
33999
  }
34141
- var LineageNodeSchema = import_zod3.z.object({
34000
+ var LineageNodeSchema = import_zod.z.object({
34142
34001
  dataPointId: DataPointIdSchema,
34143
- scope: import_zod3.z.string(),
34002
+ scope: import_zod.z.string(),
34144
34003
  /**
34145
34004
  * The node's current version, decimal string; `"0"` for a source that no
34146
34005
  * longer resolves to a registered data point.
34147
34006
  */
34148
34007
  version: VersionSchema,
34149
34008
  /** The node's tombstone time, or `null` when live. */
34150
- deletedAt: import_zod3.z.string().nullable()
34009
+ deletedAt: import_zod.z.string().nullable(),
34010
+ /**
34011
+ * Never present on a visible node. Declared so a node that carries
34012
+ * `redacted: true` next to an id, scope and version cannot slip through
34013
+ * this branch of {@link LineageEntrySchema} with the key stripped.
34014
+ */
34015
+ redacted: import_zod.z.never().optional()
34151
34016
  });
34152
- var RedactedLineageNodeSchema = import_zod3.z.object({
34153
- dataPointId: DataPointIdSchema,
34154
- redacted: import_zod3.z.literal(true)
34017
+ var RedactedLineageNodeSchema = import_zod.z.strictObject({
34018
+ redacted: import_zod.z.literal(true)
34155
34019
  });
34156
- var LineageEntrySchema = import_zod3.z.union([
34020
+ var LineageEntrySchema = import_zod.z.union([
34157
34021
  RedactedLineageNodeSchema,
34158
34022
  LineageNodeSchema
34159
34023
  ]);
34160
- var LineageGraphSchema = import_zod3.z.object({
34024
+ var LineageGraphSchema = import_zod.z.object({
34161
34025
  dataPointId: DataPointIdSchema,
34162
34026
  /** The data point owner; every node in the view belongs to it. */
34163
- ownerAddress: import_zod3.z.string().optional(),
34164
- scope: import_zod3.z.string(),
34027
+ ownerAddress: import_zod.z.string().optional(),
34028
+ scope: import_zod.z.string(),
34165
34029
  /**
34166
34030
  * The derived record's version whose lineage is shown: the requested one,
34167
34031
  * else the current one, else (current is a tombstone) the last version
34168
34032
  * that carried lineage.
34169
34033
  */
34170
34034
  version: ViewVersionSchema,
34171
- deletedAt: import_zod3.z.string().nullable(),
34172
- sources: import_zod3.z.array(LineageEntrySchema),
34173
- derivatives: import_zod3.z.array(LineageEntrySchema),
34035
+ deletedAt: import_zod.z.string().nullable(),
34036
+ sources: import_zod.z.array(LineageEntrySchema),
34037
+ derivatives: import_zod.z.array(LineageEntrySchema),
34174
34038
  /** `true` when `derivatives` was cut at the server's cap (1000). */
34175
- derivativesTruncated: import_zod3.z.boolean().optional()
34039
+ derivativesTruncated: import_zod.z.boolean().optional()
34176
34040
  });
34177
34041
  function isRedactedLineageNode(entry) {
34178
- return "redacted" in entry && entry.redacted === true;
34042
+ return "redacted" in entry && entry.redacted === true && Object.keys(entry).length === 1;
34179
34043
  }
34180
34044
  function personalServerLineagePath(scope, version) {
34181
34045
  return `/v1/data/${encodeURIComponent(scope)}/lineage${version === void 0 ? "" : `/${String(version)}`}`;
@@ -34317,7 +34181,449 @@ function getLineage(params) {
34317
34181
  return "personalServerUrl" in params ? getPersonalServerLineage(params) : getGatewayLineage(params);
34318
34182
  }
34319
34183
 
34184
+ // src/protocol/data-point-deletion.ts
34185
+ var TOMBSTONE_DATA_HASH_PREIMAGE = "vana.data-point.tombstone.v1";
34186
+ var TOMBSTONE_METADATA_HASH_PREIMAGE = "vana.data-point.tombstone.metadata.v1";
34187
+ var TOMBSTONE_DATA_HASH = "0x30c45ee72fe56d1927701316925ab7ceacd3b6f9267061735d59396f075c6222";
34188
+ var TOMBSTONE_METADATA_HASH = "0xc5255a141acd6a2ae55971b62c0a85977c2511989dc114ad2abc2b7644f57d90";
34189
+ function computeTombstoneHash(preimage) {
34190
+ return (0, import_viem22.keccak256)((0, import_viem22.stringToBytes)(preimage));
34191
+ }
34192
+ function isTombstoneHashes(dataHash, metadataHash) {
34193
+ return typeof dataHash === "string" && typeof metadataHash === "string" && dataHash.toLowerCase() === TOMBSTONE_DATA_HASH && metadataHash.toLowerCase() === TOMBSTONE_METADATA_HASH;
34194
+ }
34195
+ function isDataPointTombstone(value) {
34196
+ if (!isPlainObject(value)) return false;
34197
+ if (typeof value["deletedAt"] === "string") return true;
34198
+ return isTombstoneHashes(
34199
+ typeof value["dataHash"] === "string" ? value["dataHash"] : void 0,
34200
+ typeof value["metadataHash"] === "string" ? value["metadataHash"] : void 0
34201
+ );
34202
+ }
34203
+ function tombstoneDeletedAt(value) {
34204
+ if (!isPlainObject(value)) return null;
34205
+ const deletedAt = value["deletedAt"];
34206
+ return typeof deletedAt === "string" ? deletedAt : null;
34207
+ }
34208
+ function assertAddress4(value, name) {
34209
+ if (!(0, import_viem22.isAddress)(value)) {
34210
+ throw new Error(`${name} must be a valid EVM address`);
34211
+ }
34212
+ }
34213
+ function assertUint256(value, name) {
34214
+ if (value < 0n || value > import_viem22.maxUint256) {
34215
+ throw new Error(`${name} must fit in uint256, got ${value}`);
34216
+ }
34217
+ }
34218
+ function getAccountAddress3(account) {
34219
+ if (!account) return void 0;
34220
+ return typeof account === "string" ? account : account.address;
34221
+ }
34222
+ function isDataPointDeletionSigner(source) {
34223
+ return "address" in source && typeof source.signTypedData === "function";
34224
+ }
34225
+ function createViemDataPointDeletionSigner(source, options = {}) {
34226
+ if (isDataPointDeletionSigner(source)) {
34227
+ return source;
34228
+ }
34229
+ const accountAddress2 = getAccountAddress3(options.account) ?? getAccountAddress3(source.account);
34230
+ if (accountAddress2) {
34231
+ return {
34232
+ address: accountAddress2,
34233
+ signTypedData: (typedData) => source.signTypedData({
34234
+ ...typedData,
34235
+ account: options.account ?? source.account ?? accountAddress2
34236
+ })
34237
+ };
34238
+ }
34239
+ throw new Error(
34240
+ "Viem wallet client requires an account option or account property"
34241
+ );
34242
+ }
34243
+ function buildDataPointDeletionTypedData(input) {
34244
+ assertAddress4(input.ownerAddress, "ownerAddress");
34245
+ if (input.scope.length === 0) {
34246
+ throw new Error("scope must be a non-empty string");
34247
+ }
34248
+ if (input.expectedVersion <= 0n) {
34249
+ throw new Error("expectedVersion must be a positive version number");
34250
+ }
34251
+ assertUint256(input.expectedVersion, "expectedVersion");
34252
+ return {
34253
+ domain: dataRegistryDomain(input.config),
34254
+ types: ADD_DATA_TYPES,
34255
+ primaryType: "AddData",
34256
+ message: {
34257
+ ownerAddress: input.ownerAddress,
34258
+ scope: input.scope,
34259
+ dataHash: TOMBSTONE_DATA_HASH,
34260
+ metadataHash: TOMBSTONE_METADATA_HASH,
34261
+ expectedVersion: input.expectedVersion
34262
+ }
34263
+ };
34264
+ }
34265
+ async function buildDataPointDeletionSignature(input) {
34266
+ const typedData = buildDataPointDeletionTypedData({
34267
+ ownerAddress: input.signer.address,
34268
+ scope: input.scope,
34269
+ expectedVersion: input.expectedVersion,
34270
+ config: input.config
34271
+ });
34272
+ const signature = await input.signer.signTypedData(typedData);
34273
+ return {
34274
+ signature,
34275
+ signerAddress: input.signer.address,
34276
+ typedData
34277
+ };
34278
+ }
34279
+ function toError(value) {
34280
+ return value instanceof Error ? value : new Error(String(value));
34281
+ }
34282
+ function parseExpectedVersion(value) {
34283
+ if (typeof value !== "string" || !/^\d+$/.test(value)) {
34284
+ throw new Error(
34285
+ `Gateway returned a malformed expectedVersion: ${JSON.stringify(value)}`
34286
+ );
34287
+ }
34288
+ const parsed = BigInt(value);
34289
+ assertUint256(parsed, "Gateway expectedVersion");
34290
+ return parsed;
34291
+ }
34292
+ async function deleteDataPoint(input) {
34293
+ const ownerAddress = input.signer.address;
34294
+ const dataPointId = deriveDataPointId(ownerAddress, input.scope);
34295
+ let currentVersion = input.currentVersion;
34296
+ if (currentVersion === void 0) {
34297
+ const record = await input.gateway.getDataPoint(dataPointId);
34298
+ if (record === null) {
34299
+ throw new DataPointNotFoundError(
34300
+ `No data point registered for scope '${input.scope}' owned by ${ownerAddress}`,
34301
+ { dataPointId, scope: input.scope, ownerAddress }
34302
+ );
34303
+ }
34304
+ if (isDataPointTombstone(record)) {
34305
+ throw new DataPointDeletedError(
34306
+ `Data point ${dataPointId} (scope '${input.scope}') is already deleted`,
34307
+ {
34308
+ dataPointId,
34309
+ scope: input.scope,
34310
+ ownerAddress,
34311
+ deletedAt: tombstoneDeletedAt(record)
34312
+ }
34313
+ );
34314
+ }
34315
+ currentVersion = parseExpectedVersion(record.expectedVersion);
34316
+ }
34317
+ if (currentVersion < 0n || currentVersion >= import_viem22.maxUint256) {
34318
+ throw new Error(
34319
+ `currentVersion ${currentVersion} cannot be incremented to a uint256 tombstone version`
34320
+ );
34321
+ }
34322
+ const tombstoneVersion = currentVersion + 1n;
34323
+ const signed = await buildDataPointDeletionSignature({
34324
+ signer: input.signer,
34325
+ scope: input.scope,
34326
+ expectedVersion: tombstoneVersion,
34327
+ config: input.config
34328
+ });
34329
+ const tombstone = await input.gateway.deleteDataPoint({
34330
+ ownerAddress,
34331
+ scope: input.scope,
34332
+ expectedVersion: tombstoneVersion.toString(),
34333
+ signature: signed.signature
34334
+ });
34335
+ const base = {
34336
+ dataPointId,
34337
+ ownerAddress,
34338
+ scope: input.scope,
34339
+ version: tombstoneVersion.toString(),
34340
+ signature: signed.signature,
34341
+ tombstone
34342
+ };
34343
+ try {
34344
+ const storage = await input.storage.deleteScope(ownerAddress, input.scope);
34345
+ return { ...base, status: "deleted", storage };
34346
+ } catch (cause) {
34347
+ return { ...base, status: "partial", storageError: toError(cause) };
34348
+ }
34349
+ }
34350
+
34351
+ // src/protocol/data-file.ts
34352
+ var import_zod2 = require("zod");
34353
+ var DataFileEnvelopeSchema = import_zod2.z.object({
34354
+ $schema: import_zod2.z.string().url().optional(),
34355
+ version: import_zod2.z.literal("1.0"),
34356
+ scope: import_zod2.z.string(),
34357
+ schemaId: import_zod2.z.string().optional(),
34358
+ collectedAt: import_zod2.z.string().datetime(),
34359
+ data: import_zod2.z.record(import_zod2.z.string(), import_zod2.z.unknown())
34360
+ });
34361
+ function createDataFileEnvelope(scope, collectedAt, data, schemaUrl, schemaId) {
34362
+ return {
34363
+ ...schemaUrl !== void 0 && { $schema: schemaUrl },
34364
+ ...schemaId !== void 0 && { schemaId },
34365
+ version: "1.0",
34366
+ scope,
34367
+ collectedAt,
34368
+ data
34369
+ };
34370
+ }
34371
+ var IngestResponseSchema = import_zod2.z.object({
34372
+ scope: import_zod2.z.string(),
34373
+ collectedAt: import_zod2.z.string().datetime(),
34374
+ status: import_zod2.z.enum(["stored", "syncing"])
34375
+ });
34376
+
34377
+ // src/protocol/personal-server-data.ts
34378
+ function personalServerDataReadPath(scope) {
34379
+ return `/v1/data/${encodeURIComponent(scope)}`;
34380
+ }
34381
+ async function buildPersonalServerDataReadRequest(params) {
34382
+ const path = personalServerDataReadPath(params.scope);
34383
+ const baseUrl = params.personalServerUrl.replace(/\/+$/, "");
34384
+ const audience = params.audience ?? baseUrl;
34385
+ const headers = new Headers(params.headers);
34386
+ headers.set(
34387
+ "Authorization",
34388
+ await buildWeb3SignedHeader({
34389
+ aud: audience,
34390
+ grantId: params.grantId,
34391
+ method: "GET",
34392
+ signMessage: params.signMessage,
34393
+ uri: path
34394
+ })
34395
+ );
34396
+ return new Request(`${baseUrl}${path}`, {
34397
+ headers,
34398
+ method: "GET"
34399
+ });
34400
+ }
34401
+ async function readPersonalServerData(params) {
34402
+ const fetchFn = params.fetch ?? globalThis.fetch;
34403
+ if (fetchFn === void 0) {
34404
+ throw new Error("No fetch implementation available");
34405
+ }
34406
+ const request = await buildPersonalServerDataReadRequest(params);
34407
+ const response = await fetchFn(request);
34408
+ if (response.status === 410) {
34409
+ throw new DataPointDeletedError(
34410
+ `Personal Server scope '${params.scope}' has been deleted`,
34411
+ {
34412
+ scope: params.scope,
34413
+ deletedAt: tombstoneDeletedAt(await readJsonValue(response))
34414
+ }
34415
+ );
34416
+ }
34417
+ if (!response.ok) {
34418
+ throw new Error(
34419
+ `Personal Server data read failed: ${response.status} ${response.statusText}`
34420
+ );
34421
+ }
34422
+ const body = await response.json();
34423
+ if (isDataPointTombstone(body)) {
34424
+ throw new DataPointDeletedError(
34425
+ `Personal Server scope '${params.scope}' has been deleted`,
34426
+ { scope: params.scope, deletedAt: tombstoneDeletedAt(body) }
34427
+ );
34428
+ }
34429
+ return DataFileEnvelopeSchema.parse(body);
34430
+ }
34431
+
34432
+ // src/protocol/scopes.ts
34433
+ var import_zod3 = require("zod");
34434
+ var SOURCE_RE = /^[a-z0-9][a-z0-9_]*$/;
34435
+ var TAIL_SEGMENT_RE = /^[a-zA-Z0-9][a-zA-Z0-9_]*$/;
34436
+ var ScopeSchema = import_zod3.z.string().refine(
34437
+ (scope) => {
34438
+ const parts = scope.split(".");
34439
+ if (parts.length < 2 || parts.length > 3) return false;
34440
+ const [source, ...tail] = parts;
34441
+ return SOURCE_RE.test(source) && tail.every((part) => TAIL_SEGMENT_RE.test(part));
34442
+ },
34443
+ {
34444
+ message: "Scope must be {source}.{category}[.{subcategory}]; source lowercase, tail may keep the historical camelCase form (e.g. spotify.savedTracks)"
34445
+ }
34446
+ );
34447
+ function parseScope(scope) {
34448
+ const validated = ScopeSchema.parse(scope);
34449
+ const parts = validated.split(".");
34450
+ return {
34451
+ source: parts[0],
34452
+ category: parts[1],
34453
+ subcategory: parts[2],
34454
+ raw: validated
34455
+ };
34456
+ }
34457
+ function scopeToPathSegments(scope) {
34458
+ const parsed = parseScope(scope);
34459
+ const segments = [parsed.source, parsed.category];
34460
+ if (parsed.subcategory) {
34461
+ segments.push(parsed.subcategory);
34462
+ }
34463
+ return segments;
34464
+ }
34465
+ function scopeMatchesPattern(requestedScope, grantPattern) {
34466
+ if (grantPattern === "*") return true;
34467
+ if (grantPattern.endsWith(".*")) {
34468
+ const prefix = grantPattern.slice(0, -1);
34469
+ return requestedScope.startsWith(prefix);
34470
+ }
34471
+ return requestedScope === grantPattern;
34472
+ }
34473
+ function scopeCoveredByGrant(requestedScope, grantedScopes) {
34474
+ return grantedScopes.some(
34475
+ (pattern) => scopeMatchesPattern(requestedScope, pattern)
34476
+ );
34477
+ }
34478
+
34479
+ // src/protocol/scope-actions.ts
34480
+ var SCOPE_ACTIONS = ["read", "write"];
34481
+ var InvalidScopeEntryError = class extends Error {
34482
+ /** The offending entry, verbatim (unknown because it may not be a string). */
34483
+ entry;
34484
+ constructor(entry, reason) {
34485
+ super(`Invalid scope entry ${describeValue(entry)}: ${reason}`);
34486
+ this.name = "InvalidScopeEntryError";
34487
+ this.entry = entry;
34488
+ }
34489
+ };
34490
+ var OPERATION_SEPARATOR = ":";
34491
+ function describeValue(value) {
34492
+ if (typeof value === "string") return JSON.stringify(value);
34493
+ if (value === null) return "null";
34494
+ return `[${typeof value}]`;
34495
+ }
34496
+ var OPERATION_BY_PREFIX = {
34497
+ write: "write"
34498
+ };
34499
+ function assertScopePart(entry, scope) {
34500
+ if (scope.length === 0) {
34501
+ throw new InvalidScopeEntryError(entry, "scope part is empty");
34502
+ }
34503
+ if (scope.includes(OPERATION_SEPARATOR)) {
34504
+ throw new InvalidScopeEntryError(
34505
+ entry,
34506
+ `scope part must not contain "${OPERATION_SEPARATOR}"`
34507
+ );
34508
+ }
34509
+ }
34510
+ function parseScopeEntry(entry) {
34511
+ const raw = entry;
34512
+ if (typeof raw !== "string") {
34513
+ throw new InvalidScopeEntryError(raw, "entry must be a string");
34514
+ }
34515
+ const separatorIndex = entry.indexOf(OPERATION_SEPARATOR);
34516
+ if (separatorIndex === -1) {
34517
+ assertScopePart(entry, entry);
34518
+ return { scope: entry, action: "read" };
34519
+ }
34520
+ const prefix = entry.slice(0, separatorIndex);
34521
+ const scope = entry.slice(separatorIndex + 1);
34522
+ const action = Object.hasOwn(OPERATION_BY_PREFIX, prefix) ? OPERATION_BY_PREFIX[prefix] : void 0;
34523
+ if (action === void 0) {
34524
+ throw new InvalidScopeEntryError(
34525
+ entry,
34526
+ `unknown operation "${prefix}" (known: ${Object.keys(OPERATION_BY_PREFIX).join(", ")}; read has no prefix)`
34527
+ );
34528
+ }
34529
+ assertScopePart(entry, scope);
34530
+ return { scope, action };
34531
+ }
34532
+ function formatScopeEntry(parsed) {
34533
+ const { scope, action } = parsed;
34534
+ assertScopePart(scope, scope);
34535
+ if (action === "read") return scope;
34536
+ const prefix = Object.entries(OPERATION_BY_PREFIX).find(
34537
+ ([, candidate]) => candidate === action
34538
+ )?.[0];
34539
+ if (prefix === void 0) {
34540
+ throw new InvalidScopeEntryError(
34541
+ scope,
34542
+ `unknown action ${describeValue(action)} (known: ${SCOPE_ACTIONS.join(", ")})`
34543
+ );
34544
+ }
34545
+ return `${prefix}${OPERATION_SEPARATOR}${scope}`;
34546
+ }
34547
+ function compareScopes(a, b) {
34548
+ if (a < b) return -1;
34549
+ if (a > b) return 1;
34550
+ return 0;
34551
+ }
34552
+ function sortActions(actions) {
34553
+ const present = new Set(actions);
34554
+ return SCOPE_ACTIONS.filter((action) => present.has(action));
34555
+ }
34556
+ function grantPermissions(scopes) {
34557
+ const byScope = /* @__PURE__ */ new Map();
34558
+ for (const entry of scopes) {
34559
+ const { scope, action } = parseScopeEntry(entry);
34560
+ let actions = byScope.get(scope);
34561
+ if (actions === void 0) {
34562
+ actions = /* @__PURE__ */ new Set();
34563
+ byScope.set(scope, actions);
34564
+ }
34565
+ actions.add(action);
34566
+ }
34567
+ return [...byScope.keys()].sort(compareScopes).map((scope) => ({
34568
+ scope,
34569
+ actions: sortActions(byScope.get(scope) ?? [])
34570
+ }));
34571
+ }
34572
+ function permissionsToScopes(permissions) {
34573
+ const byScope = /* @__PURE__ */ new Map();
34574
+ for (const { scope, actions } of permissions) {
34575
+ let merged = byScope.get(scope);
34576
+ if (merged === void 0) {
34577
+ merged = /* @__PURE__ */ new Set();
34578
+ byScope.set(scope, merged);
34579
+ }
34580
+ for (const action of actions) {
34581
+ if (!SCOPE_ACTIONS.includes(action)) {
34582
+ throw new InvalidScopeEntryError(
34583
+ scope,
34584
+ `unknown action ${describeValue(action)} (known: ${SCOPE_ACTIONS.join(", ")})`
34585
+ );
34586
+ }
34587
+ merged.add(action);
34588
+ }
34589
+ }
34590
+ const entries = [];
34591
+ for (const scope of [...byScope.keys()].sort(compareScopes)) {
34592
+ for (const action of sortActions(byScope.get(scope) ?? [])) {
34593
+ entries.push(formatScopeEntry({ scope, action }));
34594
+ }
34595
+ }
34596
+ return entries;
34597
+ }
34598
+ function hasAction(scopes, scope, action) {
34599
+ if (scope.includes(OPERATION_SEPARATOR)) return false;
34600
+ for (const entry of scopes) {
34601
+ let parsed;
34602
+ try {
34603
+ parsed = parseScopeEntry(entry);
34604
+ } catch (error) {
34605
+ if (error instanceof InvalidScopeEntryError) continue;
34606
+ throw error;
34607
+ }
34608
+ if (parsed.action === action && scopeMatchesPattern(scope, parsed.scope)) {
34609
+ return true;
34610
+ }
34611
+ }
34612
+ return false;
34613
+ }
34614
+ function tryGrantPermissions(scopes) {
34615
+ try {
34616
+ return grantPermissions(scopes);
34617
+ } catch (error) {
34618
+ if (error instanceof InvalidScopeEntryError) return void 0;
34619
+ throw error;
34620
+ }
34621
+ }
34622
+
34320
34623
  // src/protocol/personal-server-write.ts
34624
+ var import_sha25 = require("@noble/hashes/sha2");
34625
+ var import_viem23 = require("viem");
34626
+ var import_zod4 = require("zod");
34321
34627
  var WRITE_SESSION_PATH = "/v1/write/session";
34322
34628
  var WRITE_SIGNATURE_HEADER = "X-Vana-Write-Signature";
34323
34629
  var WRITE_METADATA_HEADER = "X-Vana-Metadata";
@@ -34405,7 +34711,7 @@ function nextProofIat(proofKey) {
34405
34711
  return sleep2(waitSec * 1e3).then(() => iat);
34406
34712
  }
34407
34713
  function proofKeyFor(parts) {
34408
- return (0, import_viem22.bytesToHex)(
34714
+ return (0, import_viem23.bytesToHex)(
34409
34715
  (0, import_sha25.sha256)(
34410
34716
  new TextEncoder().encode(
34411
34717
  JSON.stringify([
@@ -34413,7 +34719,7 @@ function proofKeyFor(parts) {
34413
34719
  parts.method,
34414
34720
  parts.uri,
34415
34721
  parts.grantId,
34416
- parts.signedBytes ? (0, import_viem22.bytesToHex)((0, import_sha25.sha256)(parts.signedBytes)) : ""
34722
+ parts.signedBytes ? (0, import_viem23.bytesToHex)((0, import_sha25.sha256)(parts.signedBytes)) : ""
34417
34723
  ])
34418
34724
  )
34419
34725
  )
@@ -34572,7 +34878,7 @@ function binaryWriteSignedBytes(input) {
34572
34878
  mimeType: normalizeBinaryMimeType(input.contentType),
34573
34879
  ...input.filename ? { filename: input.filename } : {},
34574
34880
  sizeBytes: input.bytes.length,
34575
- contentHash: (0, import_viem22.bytesToHex)((0, import_sha25.sha256)(input.bytes)),
34881
+ contentHash: (0, import_viem23.bytesToHex)((0, import_sha25.sha256)(input.bytes)),
34576
34882
  encoding: "base64",
34577
34883
  content: toBase64(input.bytes),
34578
34884
  ...metadata !== void 0 ? { metadata } : {}
@@ -34620,7 +34926,7 @@ function normalizeLineage(lineage, derivedScope) {
34620
34926
  for (const entry of lineage) {
34621
34927
  let id;
34622
34928
  if (isLineagePair(entry)) {
34623
- if (!(0, import_viem22.isAddress)(entry.ownerAddress, { strict: false })) {
34929
+ if (!(0, import_viem23.isAddress)(entry.ownerAddress, { strict: false })) {
34624
34930
  throw new WriteRequestError(
34625
34931
  "lineage source ownerAddress must be an EVM address",
34626
34932
  { ownerAddress: entry.ownerAddress }
@@ -34882,14 +35188,44 @@ function withGrantPermissions(grant) {
34882
35188
  }
34883
35189
  function createGatewayClient(baseUrl) {
34884
35190
  const base = baseUrl.replace(/\/+$/, "");
35191
+ function malformedBody(res) {
35192
+ return new Error(
35193
+ `Gateway error: ${res.status} malformed response body (expected a JSON envelope)`
35194
+ );
35195
+ }
35196
+ async function readEnvelope(res) {
35197
+ const envelope = await readJsonValue(res);
35198
+ if (!isPlainObject(envelope) || !("data" in envelope)) {
35199
+ throw malformedBody(res);
35200
+ }
35201
+ return envelope;
35202
+ }
34885
35203
  async function unwrapEnvelope(res) {
34886
- const envelope = await res.json();
34887
- return envelope.data;
35204
+ return (await readEnvelope(res)).data;
34888
35205
  }
34889
35206
  function getMutationId(body, key) {
35207
+ if (!isPlainObject(body)) return void 0;
34890
35208
  const value = body[key] ?? body["id"];
34891
35209
  return typeof value === "string" ? value : void 0;
34892
35210
  }
35211
+ async function readBody(res) {
35212
+ const raw = await readJsonObject(res);
35213
+ const data = raw["data"];
35214
+ if (isPlainObject(data) && "proof" in raw) {
35215
+ return data;
35216
+ }
35217
+ return raw;
35218
+ }
35219
+ function stringOrUndefined(value) {
35220
+ return typeof value === "string" ? value : void 0;
35221
+ }
35222
+ async function deletedError(res, details) {
35223
+ const body = await readBody(res);
35224
+ return new DataPointDeletedError(
35225
+ `Data point ${details.dataPointId ?? details.scope ?? ""} has been deleted`,
35226
+ { ...details, deletedAt: tombstoneDeletedAt(body) }
35227
+ );
35228
+ }
34893
35229
  return {
34894
35230
  async isRegisteredBuilder(address) {
34895
35231
  const builder = await this.getBuilder(address);
@@ -34946,13 +35282,29 @@ function createGatewayClient(baseUrl) {
34946
35282
  }
34947
35283
  return await res.json();
34948
35284
  },
34949
- async getDataPoint(dataPointId) {
34950
- const res = await fetch(`${base}/v1/data/${dataPointId}`);
35285
+ async getDataPoint(dataPointId, options) {
35286
+ const query = options?.includeDeleted ? "?includeDeleted=true" : "";
35287
+ const res = await fetch(`${base}/v1/data/${dataPointId}${query}`);
34951
35288
  if (res.status === 404) return null;
35289
+ if (res.status === 410) {
35290
+ throw await deletedError(res, { dataPointId });
35291
+ }
34952
35292
  if (!res.ok) {
34953
35293
  throw new Error(`Gateway error: ${res.status} ${res.statusText}`);
34954
35294
  }
34955
- return unwrapEnvelope(res);
35295
+ const record = await unwrapEnvelope(res);
35296
+ if (!options?.includeDeleted && isDataPointTombstone(record)) {
35297
+ throw new DataPointDeletedError(
35298
+ `Data point ${dataPointId} has been deleted`,
35299
+ {
35300
+ dataPointId,
35301
+ scope: record.scope,
35302
+ ownerAddress: record.ownerAddress,
35303
+ deletedAt: tombstoneDeletedAt(record)
35304
+ }
35305
+ );
35306
+ }
35307
+ return record;
34956
35308
  },
34957
35309
  async listDataPointsByOwner(owner, cursor, options) {
34958
35310
  const params = new URLSearchParams({ user: owner });
@@ -34965,14 +35317,24 @@ function createGatewayClient(baseUrl) {
34965
35317
  if (options?.limit !== void 0) {
34966
35318
  params.set("limit", String(options.limit));
34967
35319
  }
35320
+ if (options?.includeDeleted) {
35321
+ params.set("includeDeleted", "true");
35322
+ }
34968
35323
  const res = await fetch(`${base}/v1/data?${params.toString()}`);
34969
35324
  if (!res.ok) {
34970
35325
  throw new Error(`Gateway error: ${res.status} ${res.statusText}`);
34971
35326
  }
34972
- const envelope = await res.json();
34973
- const nextCursor = envelope.pagination?.hasMore === false ? null : envelope.pagination?.nextCursor ?? null;
35327
+ const envelope = await readEnvelope(res);
35328
+ if (!isPlainObject(envelope.data) || !Array.isArray(envelope.data["dataPoints"])) {
35329
+ throw malformedBody(res);
35330
+ }
35331
+ const rows = envelope.data["dataPoints"];
35332
+ const pagination = isPlainObject(envelope["pagination"]) ? envelope["pagination"] : void 0;
35333
+ const rawCursor = pagination?.["nextCursor"];
35334
+ const nextCursor = pagination?.["hasMore"] === false || typeof rawCursor !== "string" ? null : rawCursor;
35335
+ const dataPoints = options?.includeDeleted ? rows : rows.filter((row) => !isDataPointTombstone(row));
34974
35336
  return {
34975
- dataPoints: envelope.data.dataPoints,
35337
+ dataPoints,
34976
35338
  cursor: nextCursor
34977
35339
  };
34978
35340
  },
@@ -34999,7 +35361,7 @@ function createGatewayClient(baseUrl) {
34999
35361
  })
35000
35362
  });
35001
35363
  if (res.status === 409) {
35002
- const body2 = await res.json().catch(() => ({}));
35364
+ const body2 = await readJsonObject(res);
35003
35365
  return {
35004
35366
  serverId: getMutationId(body2, "serverId"),
35005
35367
  alreadyRegistered: true
@@ -35008,7 +35370,7 @@ function createGatewayClient(baseUrl) {
35008
35370
  if (!res.ok) {
35009
35371
  throw new Error(`Gateway error: ${res.status} ${res.statusText}`);
35010
35372
  }
35011
- const body = await res.json().catch(() => ({}));
35373
+ const body = await readJsonObject(res);
35012
35374
  return {
35013
35375
  serverId: getMutationId(body, "serverId"),
35014
35376
  alreadyRegistered: false
@@ -35029,19 +35391,16 @@ function createGatewayClient(baseUrl) {
35029
35391
  })
35030
35392
  });
35031
35393
  if (res.status === 409) {
35032
- const body2 = await res.json().catch(() => ({}));
35394
+ const body2 = await readJsonObject(res);
35033
35395
  return {
35034
- builderId: getMutationId(
35035
- body2,
35036
- "builderId"
35037
- ),
35396
+ builderId: getMutationId(body2, "builderId"),
35038
35397
  alreadyRegistered: true
35039
35398
  };
35040
35399
  }
35041
35400
  if (!res.ok) {
35042
35401
  throw new Error(`Gateway error: ${res.status} ${res.statusText}`);
35043
35402
  }
35044
- const body = await res.json().catch(() => ({}));
35403
+ const body = await readJsonObject(res);
35045
35404
  return {
35046
35405
  builderId: getMutationId(body, "builderId"),
35047
35406
  alreadyRegistered: false
@@ -35063,17 +35422,77 @@ function createGatewayClient(baseUrl) {
35063
35422
  })
35064
35423
  });
35065
35424
  if (!res.ok) {
35066
- const body2 = await res.json().catch(() => ({}));
35067
- const detail = body2.error ?? res.statusText;
35425
+ const body2 = await readJsonObject(res);
35426
+ const detail = stringOrUndefined(body2["error"]) ?? res.statusText;
35068
35427
  throw new Error(`Gateway error: ${res.status} ${detail}`);
35069
35428
  }
35070
- const body = await res.json().catch(() => ({}));
35429
+ const body = await readJsonObject(res);
35071
35430
  return {
35072
- dataPointId: getMutationId(
35073
- body,
35074
- "dataPointId"
35075
- ),
35076
- expectedVersion: body.expectedVersion
35431
+ dataPointId: getMutationId(body, "dataPointId"),
35432
+ expectedVersion: stringOrUndefined(body["expectedVersion"])
35433
+ };
35434
+ },
35435
+ async deleteDataPoint(params) {
35436
+ const dataPointId = deriveDataPointId(
35437
+ params.ownerAddress,
35438
+ params.scope
35439
+ );
35440
+ const details = {
35441
+ dataPointId,
35442
+ scope: params.scope,
35443
+ ownerAddress: params.ownerAddress
35444
+ };
35445
+ const res = await fetch(`${base}/v1/data/${dataPointId}`, {
35446
+ method: "DELETE",
35447
+ headers: {
35448
+ "Content-Type": "application/json",
35449
+ Authorization: `Web3Signed ${params.signature}`
35450
+ },
35451
+ body: JSON.stringify({
35452
+ ownerAddress: params.ownerAddress,
35453
+ scope: params.scope,
35454
+ expectedVersion: params.expectedVersion,
35455
+ signature: params.signature
35456
+ })
35457
+ });
35458
+ if (res.status === 404) {
35459
+ throw new DataPointNotFoundError(
35460
+ `Data point ${dataPointId} (scope '${params.scope}') is not registered`,
35461
+ details
35462
+ );
35463
+ }
35464
+ if (res.status === 409) {
35465
+ const body2 = await readBody(res);
35466
+ const currentExpectedVersion = stringOrUndefined(
35467
+ body2["currentExpectedVersion"]
35468
+ );
35469
+ const detail = stringOrUndefined(body2["error"]) ?? res.statusText;
35470
+ throw new DataPointVersionConflictError(
35471
+ `Gateway error: 409 ${detail}`,
35472
+ {
35473
+ ...details,
35474
+ expectedVersion: params.expectedVersion,
35475
+ currentExpectedVersion
35476
+ }
35477
+ );
35478
+ }
35479
+ if (res.status === 410) {
35480
+ throw await deletedError(res, details);
35481
+ }
35482
+ if (!res.ok) {
35483
+ const body2 = await readBody(res);
35484
+ const detail = stringOrUndefined(body2["error"]) ?? res.statusText;
35485
+ throw new Error(`Gateway error: ${res.status} ${detail}`);
35486
+ }
35487
+ const body = await readBody(res);
35488
+ return {
35489
+ dataPointId: getMutationId(body, "dataPointId") ?? dataPointId,
35490
+ ownerAddress: stringOrUndefined(body["ownerAddress"]),
35491
+ scope: stringOrUndefined(body["scope"]),
35492
+ dataHash: stringOrUndefined(body["dataHash"]),
35493
+ metadataHash: stringOrUndefined(body["metadataHash"]),
35494
+ expectedVersion: stringOrUndefined(body["expectedVersion"]),
35495
+ deletedAt: tombstoneDeletedAt(body)
35077
35496
  };
35078
35497
  },
35079
35498
  async createGrant(params) {
@@ -35092,18 +35511,14 @@ function createGatewayClient(baseUrl) {
35092
35511
  })
35093
35512
  });
35094
35513
  if (res.status === 409) {
35095
- const body2 = await res.json().catch(() => ({}));
35096
- return {
35097
- grantId: getMutationId(body2, "grantId")
35098
- };
35514
+ const body2 = await readJsonObject(res);
35515
+ return { grantId: getMutationId(body2, "grantId") };
35099
35516
  }
35100
35517
  if (!res.ok) {
35101
35518
  throw new Error(`Gateway error: ${res.status} ${res.statusText}`);
35102
35519
  }
35103
- const body = await res.json();
35104
- return {
35105
- grantId: getMutationId(body, "grantId")
35106
- };
35520
+ const body = await readJsonObject(res);
35521
+ return { grantId: getMutationId(body, "grantId") };
35107
35522
  },
35108
35523
  async revokeGrant(params) {
35109
35524
  const res = await fetch(`${base}/v1/grants/${params.grantId}`, {
@@ -35842,7 +36257,10 @@ async function parsePSError(response) {
35842
36257
  DATA_ACCESS_OP_TYPE,
35843
36258
  DATA_REGISTRY_STATUS_ABI,
35844
36259
  DataFileEnvelopeSchema,
36260
+ DataPointDeletedError,
36261
+ DataPointNotFoundError,
35845
36262
  DataPointStatus,
36263
+ DataPointVersionConflictError,
35846
36264
  DropboxStorage,
35847
36265
  ECIESError,
35848
36266
  ESCROW_DEPOSIT_ABI,
@@ -35902,6 +36320,10 @@ async function parsePSError(response) {
35902
36320
  SignatureError,
35903
36321
  StorageError,
35904
36322
  StorageManager,
36323
+ TOMBSTONE_DATA_HASH,
36324
+ TOMBSTONE_DATA_HASH_PREIMAGE,
36325
+ TOMBSTONE_METADATA_HASH,
36326
+ TOMBSTONE_METADATA_HASH_PREIMAGE,
35905
36327
  TransactionPendingError,
35906
36328
  UserRejectedRequestError,
35907
36329
  VanaError,
@@ -35926,6 +36348,8 @@ async function parsePSError(response) {
35926
36348
  authorizeEscrowPayment,
35927
36349
  authorizeGrantPayment,
35928
36350
  binaryWriteSignedBytes,
36351
+ buildDataPointDeletionSignature,
36352
+ buildDataPointDeletionTypedData,
35929
36353
  buildDepositNativeRequest,
35930
36354
  buildDepositTokenRequest,
35931
36355
  buildEscrowPaymentHeader,
@@ -35943,6 +36367,7 @@ async function parsePSError(response) {
35943
36367
  clearContractCache,
35944
36368
  computeBodyHash,
35945
36369
  computePkceChallenge,
36370
+ computeTombstoneHash,
35946
36371
  contractCacheForTesting,
35947
36372
  createBrowserPlatformAdapter,
35948
36373
  createDataFileEnvelope,
@@ -35954,11 +36379,13 @@ async function parsePSError(response) {
35954
36379
  createPlatformAdapterFor,
35955
36380
  createPlatformAdapterSafe,
35956
36381
  createVanaStorageProvider,
36382
+ createViemDataPointDeletionSigner,
35957
36383
  createViemPersonalServerLiteOwnerBindingSigner,
35958
36384
  createViemPersonalServerRegistrationSigner,
35959
36385
  dataRegistryContractAddress,
35960
36386
  dataRegistryDomain,
35961
36387
  decryptWithPassword,
36388
+ deleteDataPoint,
35962
36389
  deriveDataPointId,
35963
36390
  deriveMasterKey,
35964
36391
  deriveScopeKey,
@@ -35994,10 +36421,12 @@ async function parsePSError(response) {
35994
36421
  grantRevocationDomain,
35995
36422
  hasAction,
35996
36423
  isDataPointId,
36424
+ isDataPointTombstone,
35997
36425
  isDataPortabilityGatewayConfig,
35998
36426
  isECIESEncrypted,
35999
36427
  isPlatformSupported,
36000
36428
  isRedactedLineageNode,
36429
+ isTombstoneHashes,
36001
36430
  mainnetServices,
36002
36431
  moksha,
36003
36432
  mokshaServices,
@@ -36032,6 +36461,7 @@ async function parsePSError(response) {
36032
36461
  signPersonalServerRegistrationWithAccount,
36033
36462
  toDirectFeeBreakdown,
36034
36463
  toDirectPaymentReceipt,
36464
+ tombstoneDeletedAt,
36035
36465
  tryGrantPermissions,
36036
36466
  vanaMainnet,
36037
36467
  verifyGrantRegistration,