@dignetwork/dig-sdk 0.1.0 → 0.2.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.
@@ -105,6 +105,77 @@ interface ReadResult {
105
105
  /** Did the bytes decrypt+authenticate under this URN's derived key? */
106
106
  decrypted: boolean;
107
107
  }
108
+ /**
109
+ * The on-chain CHIP-0007 metadata of a collection item, as returned by the dig RPC. Hashes are
110
+ * lowercase-hex 32-byte digests (or `null` when absent); URIs are the dig:// / https locations the
111
+ * bytes are served from. Mirrors the on-chain `NftMetadata` (the dig RPC decodes it from the NFT's
112
+ * metadata pointer). All fields optional/nullable so a non-standard metadata updater still parses.
113
+ */
114
+ interface CollectionItemMetadata {
115
+ /** 1-based edition number within the series. */
116
+ edition_number?: number;
117
+ /** Total editions in the series. */
118
+ edition_total?: number;
119
+ /** Primary media URIs (dig:// first, https fallback by convention). */
120
+ data_uris?: string[];
121
+ /** `sha256(media_bytes)`, lowercase hex, or null. */
122
+ data_hash?: string | null;
123
+ /** CHIP-0007 metadata-JSON URIs. */
124
+ metadata_uris?: string[];
125
+ /** `sha256(metadata_json_bytes)`, lowercase hex, or null. */
126
+ metadata_hash?: string | null;
127
+ /** License document URIs. */
128
+ license_uris?: string[];
129
+ /** `sha256(license_bytes)`, lowercase hex, or null. */
130
+ license_hash?: string | null;
131
+ }
132
+ /**
133
+ * One NFT in a collection, resolved to its CURRENT on-chain state by `DigClient.listCollectionItems`
134
+ * (owner-independent: the reported owner is live, walked forward through the singleton lineage, not
135
+ * the mint-time owner). All hashes/ids are lowercase hex.
136
+ */
137
+ interface CollectionItem {
138
+ /** The NFT's stable launcher id (its `nft1…` id encodes this), lowercase hex. */
139
+ launcher_id: string;
140
+ /** The current (unspent) coin id of the NFT singleton, lowercase hex. */
141
+ coin_id: string;
142
+ /** The current assigned owner DID launcher id (lowercase hex), or null when unattributed. */
143
+ owner_did: string | null;
144
+ /** The puzzle hash royalties are paid to in offer trades, lowercase hex. */
145
+ royalty_puzzle_hash: string;
146
+ /** Royalty as hundredths of a percent (300 = 3%). */
147
+ royalty_basis_points: number;
148
+ /** The CURRENT owner (p2) puzzle hash — where the NFT lives now, lowercase hex. */
149
+ owner_puzzle_hash: string;
150
+ /** The decoded on-chain CHIP-0007 metadata, or null when it does not decode. */
151
+ metadata: CollectionItemMetadata | null;
152
+ }
153
+ /** A deterministic, paginated page of collection items, from `DigClient.listCollectionItems`. */
154
+ interface CollectionItemsPage {
155
+ /** This page's items, in the requested (input launcher-id) order. */
156
+ items: CollectionItem[];
157
+ /** The offset this page started at. */
158
+ offset: number;
159
+ /** The page size requested (clamped to the server cap of 200). */
160
+ limit: number;
161
+ /** Total launcher ids in the requested collection set. */
162
+ total: number;
163
+ /** The offset of the next page, or null when this is the last page. */
164
+ next_offset: number | null;
165
+ }
166
+ /** Collection-level facts from `DigClient.getCollection` — derived from the resolved item set. */
167
+ interface CollectionMeta {
168
+ /** The creator DID launcher id the items AGREE on (lowercase hex), or null when mixed/none. */
169
+ did: string | null;
170
+ /** The DID the caller declared, echoed back (lowercase hex), or null. */
171
+ declared_did: string | null;
172
+ /** How many launcher ids were requested. */
173
+ item_count: number;
174
+ /** How many of those resolved to a live on-chain NFT. */
175
+ resolved_count: number;
176
+ /** The royalty (basis points) every item agrees on, or null when mixed. */
177
+ royalty_basis_points: number | null;
178
+ }
108
179
  /** The two root-independent keys a URN maps to (derived client-side, nothing sent to the network). */
109
180
  interface UrnKeys {
110
181
  storeId: string;
@@ -187,6 +258,44 @@ declare class DigClient {
187
258
  root: string;
188
259
  salt?: string | null;
189
260
  }, opts?: ReadOptions): Promise<ReadResult>;
261
+ /**
262
+ * Read a collection's public, owner-independent facts (creator DID, item count, uniform royalty)
263
+ * from the dig RPC (`dig.getCollection`). The collection's item set is its NFT launcher ids — the
264
+ * authoritative, owner-independent anchor the mint produced (a DID-attributed NFT is hinted to its
265
+ * OWNER at mint, not to the creator DID, so launcher ids — not the DID — are the read key). Pass
266
+ * the optional `did` to have it echoed back and recorded as the declared creator.
267
+ *
268
+ * No wallet, no read-crypto wasm — a plain JSON-RPC read. Throws a coded {@link DigSdkError} on a
269
+ * transport/RPC failure (never a "not found": an empty/partly-confirmed set just resolves to fewer
270
+ * items).
271
+ *
272
+ * @example
273
+ * const meta = await dig.getCollection({ launcherIds: ["ab…", "cd…"], did: "ef…" });
274
+ * console.log(meta.resolved_count, meta.royalty_basis_points);
275
+ */
276
+ getCollection(input: {
277
+ launcherIds: string[];
278
+ did?: string | null;
279
+ }, opts?: ReadOptions): Promise<CollectionMeta>;
280
+ /**
281
+ * Read a deterministic, paginated page of a collection's items (`dig.listCollectionItems`), each
282
+ * resolved to its CURRENT on-chain state — current owner, royalty, and CHIP-0007 metadata — by the
283
+ * RPC walking the singleton lineage forward to the live tip (so the owner is never the stale
284
+ * mint-time owner). Items come back in the input launcher-id order. `limit` is clamped to the
285
+ * server cap (200); `offset` defaults to 0.
286
+ *
287
+ * Throws a coded {@link DigSdkError} on a transport/RPC failure.
288
+ *
289
+ * @example
290
+ * let page = await dig.listCollectionItems({ launcherIds, limit: 50 });
291
+ * for (const item of page.items) console.log(item.launcher_id, item.owner_puzzle_hash);
292
+ * // page.next_offset is null on the last page.
293
+ */
294
+ listCollectionItems(input: {
295
+ launcherIds: string[];
296
+ offset?: number;
297
+ limit?: number;
298
+ }, opts?: ReadOptions): Promise<CollectionItemsPage>;
190
299
  private fetchCiphertext;
191
300
  private rpcCall;
192
301
  }
@@ -260,4 +369,4 @@ declare function reconstructUrn(storeId: string, resourceKey: string): string;
260
369
  */
261
370
  declare function reconstructUrnWithRoot(storeId: string, root: string, resourceKey: string): string;
262
371
 
263
- export { DEFAULT_RPC as D, type InjectedChiaProvider as I, type ParsedUrn as P, type ReadOptions as R, type SignResult as S, type UrnKeys as U, type WalletBackend as W, type WalletSession as a, DIG_CLIENT_WASM_SHA256 as b, DigClient as c, type DigClientOptions as d, type DigClientWasm as e, type ReadResult as f, type WasmConfig as g, configureWasm as h, isUrn as i, reconstructUrnWithRoot as j, loadDigClientWasm as l, parseUrn as p, reconstructUrn as r };
372
+ export { type CollectionItem as C, DEFAULT_RPC as D, type InjectedChiaProvider as I, type ParsedUrn as P, type ReadOptions as R, type SignResult as S, type UrnKeys as U, type WalletBackend as W, type WalletSession as a, type CollectionItemMetadata as b, type CollectionItemsPage as c, type CollectionMeta as d, DIG_CLIENT_WASM_SHA256 as e, DigClient as f, type DigClientOptions as g, type DigClientWasm as h, type ReadResult as i, type WasmConfig as j, configureWasm as k, isUrn as l, loadDigClientWasm as m, reconstructUrnWithRoot as n, parseUrn as p, reconstructUrn as r };
@@ -1,6 +1,26 @@
1
1
  'use strict';
2
2
 
3
3
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
4
+ // src/errors.ts
5
+ var DIG_SDK_ERROR_BRAND = "__dignetwork_dig_sdk_error__";
6
+ var DigSdkError = class _DigSdkError extends Error {
7
+ constructor(code, message, context = {}, options = {}) {
8
+ super(message);
9
+ this.name = "DigSdkError";
10
+ this.code = code;
11
+ this.context = context;
12
+ if (options.cause !== void 0) {
13
+ this.cause = options.cause;
14
+ }
15
+ Object.defineProperty(this, DIG_SDK_ERROR_BRAND, { value: true, enumerable: false });
16
+ Object.setPrototypeOf(this, _DigSdkError.prototype);
17
+ }
18
+ /** A JSON-friendly view of the error: `{ code, message, context }`. */
19
+ toJSON() {
20
+ return { code: this.code, message: this.message, context: this.context };
21
+ }
22
+ };
23
+
4
24
  // src/loader.ts
5
25
  var DIG_CLIENT_WASM_SHA256 = "ff486be806f908a2a90780e499a04dbd34e10e3b97be0470cb9ee841a1e49e77";
6
26
  var _config = {};
@@ -26,8 +46,10 @@ async function sha256Hex(bytes) {
26
46
  function assertIntegrity(hex) {
27
47
  if (_config.skipIntegrity) return;
28
48
  if (hex !== DIG_CLIENT_WASM_SHA256) {
29
- throw new Error(
30
- `dig-client wasm integrity check failed \u2014 refusing to run unverified crypto (expected ${DIG_CLIENT_WASM_SHA256}, got ${hex}).`
49
+ throw new DigSdkError(
50
+ "WASM_INTEGRITY",
51
+ `dig-client wasm integrity check failed \u2014 refusing to run unverified crypto (expected ${DIG_CLIENT_WASM_SHA256}, got ${hex}).`,
52
+ { expected: DIG_CLIENT_WASM_SHA256, actual: hex }
31
53
  );
32
54
  }
33
55
  }
@@ -52,7 +74,11 @@ async function loadBrowser() {
52
74
  } else {
53
75
  const wasmUrl = _config.wasmUrl ?? new URL("../vendor/dig_client_bg.wasm", (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('dig-client.cjs', document.baseURI).href))).href;
54
76
  const res = await fetch(wasmUrl);
55
- if (!res.ok) throw new Error(`dig-client wasm fetch failed (${res.status})`);
77
+ if (!res.ok)
78
+ throw new DigSdkError("WASM_LOAD_FAILED", `dig-client wasm fetch failed (${res.status})`, {
79
+ httpStatus: res.status,
80
+ wasmUrl
81
+ });
56
82
  bytes = await res.arrayBuffer();
57
83
  }
58
84
  return { glueHref, bytes };
@@ -81,8 +107,10 @@ function parseUrn(raw) {
81
107
  const s = String(raw ?? "").trim();
82
108
  const m = URN_RE.exec(s);
83
109
  if (!m) {
84
- throw new Error(
85
- "Not a valid dig URN (expected urn:dig:chia:<store-id>[:<root>]/<path>[?salt=<hex>])."
110
+ throw new DigSdkError(
111
+ "INVALID_ARGUMENT",
112
+ "Not a valid dig URN (expected urn:dig:chia:<store-id>[:<root>]/<path>[?salt=<hex>]).",
113
+ { value: s, expected: "urn:dig:chia:<store-id>[:<root>]/<path>[?salt=<hex>]" }
86
114
  );
87
115
  }
88
116
  return {
@@ -174,8 +202,10 @@ var DigClient = class {
174
202
  const effSalt = input.salt ?? parsed.salt ?? null;
175
203
  const effRoot = input.root ?? parsed.root ?? null;
176
204
  if (!effRoot) {
177
- throw new Error(
178
- "a confirmed on-chain root is required to read content (pass { root } or use a root-pinned URN)"
205
+ throw new DigSdkError(
206
+ "ROOT_REQUIRED",
207
+ "a confirmed on-chain root is required to read content (pass { root } or use a root-pinned URN)",
208
+ { urn: input.urn }
179
209
  );
180
210
  }
181
211
  return this.readResource(
@@ -187,8 +217,10 @@ var DigClient = class {
187
217
  async readText(input, opts = {}) {
188
218
  const r = await this.read(input, opts);
189
219
  if (!r.decrypted) {
190
- throw new Error(
191
- "resource did not decrypt under this URN \u2014 wrong store/key/salt, or a decoy response"
220
+ throw new DigSdkError(
221
+ "DECRYPT_FAILED",
222
+ "resource did not decrypt under this URN \u2014 wrong store/key/salt, or a decoy response",
223
+ { urn: input.urn }
192
224
  );
193
225
  }
194
226
  return new TextDecoder().decode(r.bytes);
@@ -237,6 +269,62 @@ var DigClient = class {
237
269
  };
238
270
  }
239
271
  }
272
+ /**
273
+ * Read a collection's public, owner-independent facts (creator DID, item count, uniform royalty)
274
+ * from the dig RPC (`dig.getCollection`). The collection's item set is its NFT launcher ids — the
275
+ * authoritative, owner-independent anchor the mint produced (a DID-attributed NFT is hinted to its
276
+ * OWNER at mint, not to the creator DID, so launcher ids — not the DID — are the read key). Pass
277
+ * the optional `did` to have it echoed back and recorded as the declared creator.
278
+ *
279
+ * No wallet, no read-crypto wasm — a plain JSON-RPC read. Throws a coded {@link DigSdkError} on a
280
+ * transport/RPC failure (never a "not found": an empty/partly-confirmed set just resolves to fewer
281
+ * items).
282
+ *
283
+ * @example
284
+ * const meta = await dig.getCollection({ launcherIds: ["ab…", "cd…"], did: "ef…" });
285
+ * console.log(meta.resolved_count, meta.royalty_basis_points);
286
+ */
287
+ async getCollection(input, opts = {}) {
288
+ const rpc = opts.rpc ?? this.rpc;
289
+ const params = { launcher_ids: input.launcherIds };
290
+ if (input.did) params.did = input.did;
291
+ const r = await this.rpcCall(rpc, "dig.getCollection", params);
292
+ if (!r)
293
+ throw new DigSdkError(
294
+ "RPC_MALFORMED_RESPONSE",
295
+ "The content network returned no collection facts for this request.",
296
+ { rpcMethod: "dig.getCollection" }
297
+ );
298
+ return r;
299
+ }
300
+ /**
301
+ * Read a deterministic, paginated page of a collection's items (`dig.listCollectionItems`), each
302
+ * resolved to its CURRENT on-chain state — current owner, royalty, and CHIP-0007 metadata — by the
303
+ * RPC walking the singleton lineage forward to the live tip (so the owner is never the stale
304
+ * mint-time owner). Items come back in the input launcher-id order. `limit` is clamped to the
305
+ * server cap (200); `offset` defaults to 0.
306
+ *
307
+ * Throws a coded {@link DigSdkError} on a transport/RPC failure.
308
+ *
309
+ * @example
310
+ * let page = await dig.listCollectionItems({ launcherIds, limit: 50 });
311
+ * for (const item of page.items) console.log(item.launcher_id, item.owner_puzzle_hash);
312
+ * // page.next_offset is null on the last page.
313
+ */
314
+ async listCollectionItems(input, opts = {}) {
315
+ const rpc = opts.rpc ?? this.rpc;
316
+ const params = { launcher_ids: input.launcherIds };
317
+ if (input.offset !== void 0) params.offset = input.offset;
318
+ if (input.limit !== void 0) params.limit = input.limit;
319
+ const r = await this.rpcCall(rpc, "dig.listCollectionItems", params);
320
+ if (!r)
321
+ throw new DigSdkError(
322
+ "RPC_MALFORMED_RESPONSE",
323
+ "The content network returned no collection items for this request.",
324
+ { rpcMethod: "dig.listCollectionItems" }
325
+ );
326
+ return r;
327
+ }
240
328
  // Stream the FULL ciphertext for a resource from the RPC by retrieval key, reassembling 3-MiB
241
329
  // chunks. A null result is a TRANSPORT failure, never a presence judgment.
242
330
  async fetchCiphertext(storeId, rk, root, rpc) {
@@ -253,7 +341,12 @@ var DigClient = class {
253
341
  offset,
254
342
  length: RPC_CHUNK_BYTES
255
343
  });
256
- if (!r) throw new Error("The content network returned no data for this request.");
344
+ if (!r)
345
+ throw new DigSdkError(
346
+ "RPC_MALFORMED_RESPONSE",
347
+ "The content network returned no data for this request.",
348
+ { rpcMethod: "dig.getContent" }
349
+ );
257
350
  if (total === null) {
258
351
  total = r.total_length >>> 0;
259
352
  buf = new Uint8Array(total);
@@ -270,7 +363,8 @@ var DigClient = class {
270
363
  }
271
364
  return { ciphertext: buf ?? new Uint8Array(0), proof, chunkLens };
272
365
  }
273
- // One JSON-RPC 2.0 call. Throws on transport failure or a JSON-RPC error; returns `result`.
366
+ // One JSON-RPC 2.0 call. Throws a coded DigSdkError on transport failure (RPC_TRANSPORT) or a
367
+ // JSON-RPC/HTTP error (RPC_ERROR, carrying rpcMethod/httpStatus/rpcCode context); returns `result`.
274
368
  async rpcCall(rpc, method, params) {
275
369
  let res;
276
370
  try {
@@ -279,12 +373,26 @@ var DigClient = class {
279
373
  headers: { "content-type": "application/json" },
280
374
  body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params })
281
375
  });
282
- } catch {
283
- throw new Error("Could not reach the content network. Check your connection and try again.");
376
+ } catch (e) {
377
+ throw new DigSdkError(
378
+ "RPC_TRANSPORT",
379
+ "Could not reach the content network. Check your connection and try again.",
380
+ { rpcMethod: method },
381
+ { cause: e }
382
+ );
284
383
  }
285
- if (!res.ok) throw new Error(`dig RPC ${method} failed (${res.status})`);
384
+ if (!res.ok)
385
+ throw new DigSdkError("RPC_ERROR", `dig RPC ${method} failed (${res.status})`, {
386
+ rpcMethod: method,
387
+ httpStatus: res.status
388
+ });
286
389
  const json = await res.json();
287
- if (json && json.error) throw new Error(`dig RPC ${method}: ${json.error.message ?? "error"}`);
390
+ if (json && json.error)
391
+ throw new DigSdkError(
392
+ "RPC_ERROR",
393
+ `dig RPC ${method}: ${json.error.message ?? "error"}`,
394
+ { rpcMethod: method, rpcCode: json.error.code }
395
+ );
288
396
  return json ? json.result ?? null : null;
289
397
  }
290
398
  };
@@ -292,7 +400,11 @@ function decryptResourceChunks(wasm, keyHex, ciphertext, chunkLens) {
292
400
  const lens = chunkLens && chunkLens.length ? chunkLens : [ciphertext.length];
293
401
  const total = lens.reduce((a, n) => a + n, 0);
294
402
  if (total !== ciphertext.length) {
295
- throw new Error("served ciphertext length does not match chunk lengths");
403
+ throw new DigSdkError(
404
+ "RPC_MALFORMED_RESPONSE",
405
+ "served ciphertext length does not match chunk lengths",
406
+ { rpcMethod: "dig.getContent", expected: String(total), actual: String(ciphertext.length) }
407
+ );
296
408
  }
297
409
  if (lens.length === 1) return wasm.decryptChunk(keyHex, ciphertext);
298
410
  const parts = [];
@@ -311,7 +423,8 @@ function decryptResourceChunks(wasm, keyHex, ciphertext, chunkLens) {
311
423
  }
312
424
  function undefinedFetch() {
313
425
  return (() => {
314
- throw new Error(
426
+ throw new DigSdkError(
427
+ "INVALID_ARGUMENT",
315
428
  "No global fetch available. Pass { fetch } to DigClient (Node < 18 needs a fetch polyfill)."
316
429
  );
317
430
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/loader.ts","../src/urn.ts","../src/dig-client.ts"],"names":[],"mappings":";;;;AAmBO,IAAM,sBAAA,GACX;AAuBF,IAAI,UAAsB,EAAC;AAC3B,IAAI,MAAA,GAAwC,IAAA;AAOrC,SAAS,cAAc,MAAA,EAA0B;AACtD,EAAA,OAAA,GAAU,EAAE,GAAG,MAAA,EAAO;AACtB,EAAA,MAAA,GAAS,IAAA;AACX;AAEA,IAAM,SACJ,OAAO,OAAA,KAAY,eACnB,CAAC,CAAE,QAA6C,QAAA,EAAU,IAAA;AAG5D,eAAe,UAAU,KAAA,EAAsC;AAC7D,EAAA,IAAI,MAAA,EAAQ;AACV,IAAA,MAAM,EAAE,UAAA,EAAW,GAAI,MAAM,OAAO,QAAa,CAAA;AACjD,IAAA,MAAM,OACJ,KAAA,YAAiB,WAAA,GACb,IAAI,UAAA,CAAW,KAAK,IACpB,IAAI,UAAA;AAAA,MACD,KAAA,CAA0B,MAAA;AAAA,MAC1B,KAAA,CAA0B,UAAA;AAAA,MAC1B,KAAA,CAA0B;AAAA,KAC7B;AACN,IAAA,OAAO,WAAW,QAAQ,CAAA,CAAE,OAAO,IAAI,CAAA,CAAE,OAAO,KAAK,CAAA;AAAA,EACvD;AACA,EAAA,MAAM,SAAS,MAAM,MAAA,CAAO,MAAA,CAAO,MAAA,CAAO,WAAW,KAAqB,CAAA;AAC1E,EAAA,OA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,IAAI,KAAA;AAAA,MACR;AAAA,KACF;AAAA,EACF,CAAA;AACF","file":"dig-client.cjs","sourcesContent":["// Cross-target loader for the vendored `dig_client` read-crypto WASM.\n//\n// The wasm is the SAME artifact the DIG Browser, extension, companion, and hub all run — vendored\n// under vendor/ with a PROVENANCE note and pinned SRI (see vendor/PROVENANCE.md). We NEVER run it\n// unverified: we obtain the raw bytes, SHA-256 them, compare against the pinned digest, and only\n// then hand the verified bytes to wasm-bindgen's init. A mismatch (tampered / wrong artifact)\n// throws — the reader FAILS CLOSED rather than running unverified crypto.\n//\n// Three runtimes are supported, auto-detected, with an escape hatch (`configureWasm`):\n// • Node / Bun — read vendor/ files from the package directory (fs + node:crypto).\n// • Browser (bundled) — the consumer's bundler can resolve the vendor files; if it can't, the\n// consumer supplies bytes via `configureWasm({ wasmBytes, glueUrl })`.\n// • Browser (no bundler) — `configureWasm` with a URL/bytes you serve yourself.\n//\n// Memoized: the wasm initializes at most once per process/page.\n\nimport type { DigClientWasm } from \"./wasm.js\";\n\n/** SHA-256 (lowercase hex) of vendor/dig_client_bg.wasm — the SRI digest. Fail closed on mismatch. */\nexport const DIG_CLIENT_WASM_SHA256 =\n \"ff486be806f908a2a90780e499a04dbd34e10e3b97be0470cb9ee841a1e49e77\";\n\n/** Optional explicit wasm inputs, for environments where auto-resolution can't find vendor/. */\nexport interface WasmConfig {\n /**\n * The wasm bytes (already loaded). When provided, SRI is still enforced unless `skipIntegrity`.\n * Pass this in CSP-strict browsers where you fetch + verify the bytes yourself.\n */\n wasmBytes?: BufferSource;\n /**\n * URL to the wasm-bindgen glue module (vendor/dig_client.mjs) for browser dynamic import. When\n * omitted in a browser, the loader tries to import the glue relative to this module.\n */\n glueUrl?: string;\n /**\n * URL to fetch the wasm bytes from (browser) when `wasmBytes` is not supplied. The fetched bytes\n * are SRI-verified before init.\n */\n wasmUrl?: string;\n /** Skip the SRI check. Only for tests / trusted custom builds — NOT recommended. */\n skipIntegrity?: boolean;\n}\n\nlet _config: WasmConfig = {};\nlet _ready: Promise<DigClientWasm> | null = null;\n\n/**\n * Override how the read-crypto wasm is located/loaded. Call BEFORE the first `DigClient` read.\n * Mainly for browsers without a bundler that resolves package files, or CSP-strict apps that fetch\n * + verify the wasm bytes themselves and hand them in. Resets any cached instance.\n */\nexport function configureWasm(config: WasmConfig): void {\n _config = { ...config };\n _ready = null;\n}\n\nconst isNode =\n typeof process !== \"undefined\" &&\n !!(process as { versions?: { node?: string } }).versions?.node;\n\n/** SHA-256 a buffer to lowercase hex, using node:crypto or WebCrypto. */\nasync function sha256Hex(bytes: BufferSource): Promise<string> {\n if (isNode) {\n const { createHash } = await import(\"node:crypto\");\n const view =\n bytes instanceof ArrayBuffer\n ? new Uint8Array(bytes)\n : new Uint8Array(\n (bytes as ArrayBufferView).buffer,\n (bytes as ArrayBufferView).byteOffset,\n (bytes as ArrayBufferView).byteLength,\n );\n return createHash(\"sha256\").update(view).digest(\"hex\");\n }\n const digest = await crypto.subtle.digest(\"SHA-256\", bytes as BufferSource);\n return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction assertIntegrity(hex: string): void {\n if (_config.skipIntegrity) return;\n if (hex !== DIG_CLIENT_WASM_SHA256) {\n throw new Error(\n \"dig-client wasm integrity check failed — refusing to run unverified crypto \" +\n `(expected ${DIG_CLIENT_WASM_SHA256}, got ${hex}).`,\n );\n }\n}\n\n// Read the vendored glue URL + wasm bytes for Node from the package's vendor/ directory.\nasync function loadNode(): Promise<{ glueHref: string; bytes: BufferSource }> {\n const { readFile } = await import(\"node:fs/promises\");\n const { fileURLToPath, pathToFileURL } = await import(\"node:url\");\n const path = await import(\"node:path\");\n // This module lives in dist/; vendor/ sits at the package root, one level up.\n const here = path.dirname(fileURLToPath(import.meta.url));\n const vendorDir = path.resolve(here, \"..\", \"vendor\");\n const wasmPath = path.join(vendorDir, \"dig_client_bg.wasm\");\n const gluePath = path.join(vendorDir, \"dig_client.mjs\");\n const buf = await readFile(wasmPath);\n // Copy into a fresh ArrayBuffer-backed view so the type is a plain BufferSource (not the\n // ArrayBufferLike/SharedArrayBuffer union the Node Buffer type widens to).\n const bytes = new Uint8Array(buf.byteLength);\n bytes.set(buf);\n return { glueHref: pathToFileURL(gluePath).href, bytes };\n}\n\n// Resolve the glue URL + wasm bytes for a browser. Prefers explicit config; otherwise resolves\n// the vendored files relative to this module (works when the bundler copies vendor/ alongside).\nasync function loadBrowser(): Promise<{ glueHref: string; bytes: BufferSource }> {\n const glueHref =\n _config.glueUrl ?? new URL(\"../vendor/dig_client.mjs\", import.meta.url).href;\n let bytes: BufferSource;\n if (_config.wasmBytes) {\n bytes = _config.wasmBytes;\n } else {\n const wasmUrl =\n _config.wasmUrl ?? new URL(\"../vendor/dig_client_bg.wasm\", import.meta.url).href;\n const res = await fetch(wasmUrl);\n if (!res.ok) throw new Error(`dig-client wasm fetch failed (${res.status})`);\n bytes = await res.arrayBuffer();\n }\n return { glueHref, bytes };\n}\n\n/**\n * Load, SRI-verify, and instantiate the read-crypto wasm, returning its functions. Memoized — at\n * most one init per process/page. Fails closed on an integrity mismatch.\n */\nexport function loadDigClientWasm(): Promise<DigClientWasm> {\n if (_ready) return _ready;\n _ready = (async () => {\n const { glueHref, bytes } = isNode ? await loadNode() : await loadBrowser();\n assertIntegrity(await sha256Hex(bytes));\n const mod = (await import(/* @vite-ignore */ glueHref)) as {\n default: (input: { module_or_path: BufferSource }) => Promise<unknown>;\n } & Partial<DigClientWasm>;\n // wasm-bindgen default export = async init; accepts raw bytes via { module_or_path }.\n await mod.default({ module_or_path: bytes });\n return mod as unknown as DigClientWasm;\n })().catch((e) => {\n _ready = null; // allow a retry on transient load failure\n throw e;\n });\n return _ready;\n}\n","// DIG URN parsing + canonicalization — PURE, dependency-free, and identical to the parser the\n// hub (apps/web/lib/dig-client.js), the extension, and the companion use. Kept pure (no wasm) so\n// it is trivially unit-testable under `node --test` and usable on any runtime.\n//\n// A DIG URN addresses one resource inside a store:\n//\n// urn:dig:chia:<store_id>[:<root>]/<resource_key>[?salt=<hex>]\n//\n// • <store_id> — 64 hex chars, the singleton launcher id (the store identity).\n// • :<root> — OPTIONAL 64 hex chars, pins a specific on-chain generation. Omit for the\n// canonical, root-INDEPENDENT form. The root is only the trust anchor for\n// inclusion verification; it is NOT a key input (retrieval/decryption keys are\n// root-independent).\n// • <resource_key> — the path within the store (e.g. \"index.html\", \"img/logo.png\"). An empty\n// key resolves to the §8.5 default view \"index.html\".\n// • ?salt=<hex> — OPTIONAL out-of-band secret salt for a PRIVATE store.\n\n/** The parts of a parsed DIG URN. `root`/`salt` are null when absent. */\nexport interface ParsedUrn {\n /** Store identity (64-hex launcher id), lowercased. */\n readonly storeId: string;\n /** Generation root (64-hex), lowercased — or null for the root-independent form. */\n readonly root: string | null;\n /** Resource path within the store (verbatim, not lowercased). */\n readonly resourceKey: string;\n /** Private-store secret salt (hex), lowercased — or null for a public store. */\n readonly salt: string | null;\n}\n\nconst URN_RE =\n /^urn:dig:chia:([0-9a-fA-F]{64})(?::([0-9a-fA-F]{64}))?\\/(.+?)(?:\\?salt=([0-9a-fA-F]+))?$/;\n\n/**\n * Parse a DIG URN into its parts. Throws on a malformed URN.\n *\n * @example\n * parseUrn(\"urn:dig:chia:\" + \"ab\".repeat(32) + \"/index.html\")\n * // → { storeId: \"abab…\", root: null, resourceKey: \"index.html\", salt: null }\n */\nexport function parseUrn(raw: string): ParsedUrn {\n const s = String(raw ?? \"\").trim();\n const m = URN_RE.exec(s);\n if (!m) {\n throw new Error(\n \"Not a valid dig URN (expected urn:dig:chia:<store-id>[:<root>]/<path>[?salt=<hex>]).\",\n );\n }\n return {\n storeId: m[1]!.toLowerCase(),\n root: m[2] ? m[2].toLowerCase() : null,\n resourceKey: m[3]!,\n salt: m[4] ? m[4].toLowerCase() : null,\n };\n}\n\n/** True iff `raw` is a syntactically valid DIG URN. Never throws. */\nexport function isUrn(raw: string): boolean {\n try {\n parseUrn(raw);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Reconstruct the canonical, root-INDEPENDENT URN string for a store + resource key:\n * `urn:dig:chia:<store_id>/<resource_key>`. An empty resource key resolves to the default view\n * `index.html`. This is the form whose SHA-256 is the retrieval key and whose bytes seed the AES\n * key — matching the wasm's `reconstructUrn`.\n */\nexport function reconstructUrn(storeId: string, resourceKey: string): string {\n const key = resourceKey && resourceKey.length > 0 ? resourceKey : \"index.html\";\n return `urn:dig:chia:${storeId.toLowerCase()}/${key}`;\n}\n\n/**\n * Reconstruct a root-PINNED display URN: `urn:dig:chia:<store_id>:<root>/<resource_key>`. Useful\n * for sharing a URN bound to a specific generation; the retrieval/AES keys still use the rootless\n * form (`reconstructUrn`).\n */\nexport function reconstructUrnWithRoot(\n storeId: string,\n root: string,\n resourceKey: string,\n): string {\n const key = resourceKey && resourceKey.length > 0 ? resourceKey : \"index.html\";\n return `urn:dig:chia:${storeId.toLowerCase()}:${root.toLowerCase()}/${key}`;\n}\n","// DigClient — the read side of the SDK. It fetches a resource's served ciphertext from the dig RPC,\n// derives the URN's keys CLIENT-SIDE via the read-crypto wasm, verifies inclusion against an\n// on-chain root, and decrypts — so the serving host stays BLIND (it only ever relays opaque\n// ciphertext + proofs). Genericized from hub.dig.net/apps/web/lib/dig-client.js, with the hub-app\n// coupling removed (no Vite import.meta.env, no window.location origin; the RPC endpoint and the\n// trust root are explicit inputs).\n//\n// HARD BOUNDARY (read sources). Everything read from a .dig — ciphertext, inclusion proofs, the\n// public manifest, metadata — comes ONLY from the dig RPC. The trust ROOT it is verified against\n// comes from the chain (the caller resolves it from coinset.org and passes it in). The host can\n// never become the trust anchor: every content read REQUIRES a caller-supplied root.\n//\n// OBLIVIOUS model. The host returns indistinguishable ciphertext for any retrieval key, so\n// presence is UNKNOWABLE. A read therefore NEVER concludes \"not found\": it returns plaintext when\n// the URN key decrypts the bytes, otherwise the raw ciphertext (a decoy is just opaque bytes). The\n// only thrown error is a transport failure.\n\nimport { loadDigClientWasm } from \"./loader.js\";\nimport type { DigClientWasm } from \"./wasm.js\";\nimport { parseUrn } from \"./urn.js\";\nimport type { ReadOptions, ReadResult, UrnKeys } from \"./types.js\";\n\n/** The default public dig RPC endpoint. */\nexport const DEFAULT_RPC = \"https://rpc.dig.net\";\n\n// The backend caps each dig.getContent chunk at 3 MiB (Lambda/APIGW response ceiling); the client\n// loops chunks until `complete`.\nconst RPC_CHUNK_BYTES = 3 * 1024 * 1024;\n\n/** Options to construct a DigClient. */\nexport interface DigClientOptions {\n /** dig RPC endpoint. Defaults to the public `https://rpc.dig.net`. */\n rpc?: string;\n /** Override `fetch` (e.g. an instrumented one). Defaults to the global `fetch`. */\n fetch?: typeof fetch;\n}\n\ninterface GetContentResult {\n total_length: number;\n offset: number;\n next_offset?: number | null;\n complete?: boolean;\n ciphertext?: string;\n inclusion_proof?: string;\n chunk_lens?: number[];\n}\n\n/** Decode a standard-base64 string (the RPC ciphertext encoding) to bytes — no DOM dependency. */\nfunction b64ToBytes(b64: string): Uint8Array {\n // atob exists in browsers and modern Node; fall back to Buffer in older Node.\n if (typeof atob === \"function\") {\n const bin = atob(b64);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return new Uint8Array((globalThis as any).Buffer.from(b64, \"base64\"));\n}\n\n/**\n * The read-crypto client. Construct once and reuse — the wasm is loaded + SRI-verified lazily on\n * the first read and memoized process/page-wide.\n *\n * @example\n * const dig = new DigClient();\n * const { bytes, decrypted } = await dig.read({\n * urn: \"urn:dig:chia:<storeId>/index.html\",\n * root: \"<onchain-root-hex>\",\n * });\n * if (decrypted) console.log(new TextDecoder().decode(bytes));\n */\nexport class DigClient {\n private readonly rpc: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(options: DigClientOptions = {}) {\n this.rpc = options.rpc ?? DEFAULT_RPC;\n this.fetchImpl =\n options.fetch ??\n (typeof fetch === \"function\" ? fetch.bind(globalThis) : undefinedFetch());\n }\n\n /** Load (and SRI-verify) the read-crypto wasm. Exposed for callers that want the raw functions. */\n async wasm(): Promise<DigClientWasm> {\n return loadDigClientWasm();\n }\n\n /** `retrieval_key = SHA-256(canonical rootless URN)`, lowercase hex. */\n async retrievalKey(storeId: string, resourceKey: string): Promise<string> {\n return (await this.wasm()).retrievalKey(storeId, resourceKey);\n }\n\n /** Derive the per-URN AES-256-GCM-SIV key, lowercase hex. `salt` for a private store. */\n async deriveKey(\n storeId: string,\n resourceKey: string,\n salt?: string | null,\n ): Promise<string> {\n return (await this.wasm()).deriveKey(storeId, resourceKey, salt ?? undefined);\n }\n\n /** Verify served `ciphertext` is included under `root` via the base64 merkle `proof`. */\n async verifyInclusion(\n ciphertext: Uint8Array,\n proof: string,\n root: string,\n ): Promise<boolean> {\n return (await this.wasm()).verifyInclusion(ciphertext, proof, root);\n }\n\n /** Reconstruct the canonical rootless URN whose SHA-256 is the retrieval key. */\n async reconstructUrn(storeId: string, resourceKey: string): Promise<string> {\n return (await this.wasm()).reconstructUrn(storeId, resourceKey);\n }\n\n /**\n * Derive, client-side, the two root-independent keys a URN maps to (retrieval + decryption).\n * Nothing is sent to the network — pure local derivation via the wasm.\n */\n async deriveUrnKeys(input: { urn: string; salt?: string | null }): Promise<UrnKeys> {\n const parsed = parseUrn(input.urn);\n const wasm = await this.wasm();\n const effSalt = input.salt ?? parsed.salt ?? undefined;\n return {\n storeId: parsed.storeId,\n root: parsed.root,\n resourceKey: parsed.resourceKey,\n salt: effSalt ?? null,\n retrievalKey: wasm.retrievalKey(parsed.storeId, parsed.resourceKey),\n decryptionKey: wasm.deriveKey(parsed.storeId, parsed.resourceKey, effSalt),\n };\n }\n\n /**\n * Fetch + verify + decrypt one resource by URN. `root` is the on-chain generation root to verify\n * against (resolved by the caller from the chain); when omitted, the root embedded in the URN is\n * used. Returns the bytes plus advisory `verified`/`decrypted` flags. NEVER throws \"not found\"\n * (presence is unknowable) — it throws only on a transport failure.\n */\n async read(\n input: { urn: string; root?: string | null; salt?: string | null },\n opts: ReadOptions = {},\n ): Promise<ReadResult> {\n const parsed = parseUrn(input.urn);\n const effSalt = input.salt ?? parsed.salt ?? null;\n const effRoot = input.root ?? parsed.root ?? null;\n if (!effRoot) {\n throw new Error(\n \"a confirmed on-chain root is required to read content (pass { root } or use a root-pinned URN)\",\n );\n }\n return this.readResource(\n { storeId: parsed.storeId, resourceKey: parsed.resourceKey, root: effRoot, salt: effSalt },\n opts,\n );\n }\n\n /** As `read`, but decoding the plaintext to a UTF-8 string when it decrypts (else throws). */\n async readText(\n input: { urn: string; root?: string | null; salt?: string | null },\n opts: ReadOptions = {},\n ): Promise<string> {\n const r = await this.read(input, opts);\n if (!r.decrypted) {\n throw new Error(\n \"resource did not decrypt under this URN — wrong store/key/salt, or a decoy response\",\n );\n }\n return new TextDecoder().decode(r.bytes);\n }\n\n /**\n * Read by explicit (storeId, resourceKey, root, salt) rather than a URN string. The oblivious\n * download primitive the URN read is built on.\n */\n async readResource(\n input: { storeId: string; resourceKey: string; root: string; salt?: string | null },\n opts: ReadOptions = {},\n ): Promise<ReadResult> {\n const rpc = opts.rpc ?? this.rpc;\n const wasm = await this.wasm();\n const rk = wasm.retrievalKey(input.storeId, input.resourceKey);\n const { ciphertext, proof, chunkLens } = await this.fetchCiphertext(\n input.storeId,\n rk,\n input.root,\n rpc,\n );\n let verified = false;\n try {\n verified = !!wasm.verifyInclusion(ciphertext, proof, input.root);\n } catch {\n verified = false;\n }\n const keyHex = wasm.deriveKey(input.storeId, input.resourceKey, input.salt ?? undefined);\n try {\n const bytes = decryptResourceChunks(wasm, keyHex, ciphertext, chunkLens);\n return {\n storeId: input.storeId,\n root: input.root,\n resourceKey: input.resourceKey,\n salt: input.salt ?? null,\n bytes,\n verified,\n decrypted: true,\n };\n } catch {\n // Not decryptable with this URN/salt — hand back the raw bytes; never a \"not present\" verdict.\n return {\n storeId: input.storeId,\n root: input.root,\n resourceKey: input.resourceKey,\n salt: input.salt ?? null,\n bytes: ciphertext,\n verified,\n decrypted: false,\n };\n }\n }\n\n // Stream the FULL ciphertext for a resource from the RPC by retrieval key, reassembling 3-MiB\n // chunks. A null result is a TRANSPORT failure, never a presence judgment.\n private async fetchCiphertext(\n storeId: string,\n rk: string,\n root: string,\n rpc: string,\n ): Promise<{ ciphertext: Uint8Array; proof: string; chunkLens: number[] | null }> {\n let offset = 0;\n let total: number | null = null;\n let buf: Uint8Array | null = null;\n let proof = \"\";\n let chunkLens: number[] | null = null;\n for (;;) {\n const r = await this.rpcCall<GetContentResult>(rpc, \"dig.getContent\", {\n store_id: storeId,\n root,\n retrieval_key: rk,\n offset,\n length: RPC_CHUNK_BYTES,\n });\n if (!r) throw new Error(\"The content network returned no data for this request.\");\n if (total === null) {\n total = r.total_length >>> 0;\n buf = new Uint8Array(total);\n }\n if (chunkLens === null && Array.isArray(r.chunk_lens)) {\n chunkLens = r.chunk_lens.map((n) => n >>> 0);\n }\n const chunk = b64ToBytes(r.ciphertext ?? \"\");\n const at = r.offset >>> 0;\n buf!.set(chunk.subarray(0, Math.max(0, Math.min(chunk.length, total - at))), at);\n if (r.inclusion_proof) proof = r.inclusion_proof;\n if (r.complete || r.next_offset == null) break;\n offset = r.next_offset >>> 0;\n }\n return { ciphertext: buf ?? new Uint8Array(0), proof, chunkLens };\n }\n\n // One JSON-RPC 2.0 call. Throws on transport failure or a JSON-RPC error; returns `result`.\n private async rpcCall<T>(rpc: string, method: string, params: unknown): Promise<T | null> {\n let res: Response;\n try {\n res = await this.fetchImpl(rpc, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ jsonrpc: \"2.0\", id: 1, method, params }),\n });\n } catch {\n throw new Error(\"Could not reach the content network. Check your connection and try again.\");\n }\n if (!res.ok) throw new Error(`dig RPC ${method} failed (${res.status})`);\n const json = (await res.json()) as { result?: T; error?: { message?: string } };\n if (json && json.error) throw new Error(`dig RPC ${method}: ${json.error.message ?? \"error\"}`);\n return json ? (json.result ?? null) : null;\n }\n}\n\n// AES-256-GCM-SIV-open a resource's served ciphertext under `keyHex`, splitting the PLAIN-\n// concatenated chunk ciphertexts by `chunkLens` (per-chunk CIPHERTEXT byte lengths) and opening\n// each. Empty/absent chunkLens ⇒ single-chunk resource. Throws if any chunk's tag fails.\nfunction decryptResourceChunks(\n wasm: DigClientWasm,\n keyHex: string,\n ciphertext: Uint8Array,\n chunkLens: number[] | null,\n): Uint8Array {\n const lens = chunkLens && chunkLens.length ? chunkLens : [ciphertext.length];\n const total = lens.reduce((a, n) => a + n, 0);\n if (total !== ciphertext.length) {\n throw new Error(\"served ciphertext length does not match chunk lengths\");\n }\n if (lens.length === 1) return wasm.decryptChunk(keyHex, ciphertext);\n const parts: Uint8Array[] = [];\n let p = 0;\n for (const len of lens) {\n parts.push(wasm.decryptChunk(keyHex, ciphertext.subarray(p, p + len)));\n p += len;\n }\n const out = new Uint8Array(parts.reduce((a, x) => a + x.length, 0));\n let q = 0;\n for (const part of parts) {\n out.set(part, q);\n q += part.length;\n }\n return out;\n}\n\nfunction undefinedFetch(): typeof fetch {\n return (() => {\n throw new Error(\n \"No global fetch available. Pass { fetch } to DigClient (Node < 18 needs a fetch polyfill).\",\n );\n }) as unknown as typeof fetch;\n}\n"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/loader.ts","../src/urn.ts","../src/dig-client.ts"],"names":[],"mappings":";;;;AA6GA,IAAM,mBAAA,GAAsB,8BAAA;AAErB,IAAM,WAAA,GAAN,MAAM,YAAA,SAAoB,KAAA,CAAM;AAAA,EAMrC,WAAA,CACE,MACA,OAAA,EACA,OAAA,GAA8B,EAAC,EAC/B,OAAA,GAA+B,EAAC,EAChC;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AAGf,IAAA,IAAI,OAAA,CAAQ,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// Every failure the SDK surfaces is a `DigSdkError` (an `Error` subclass) carrying a STABLE,\n// documented `.code` (UPPER_SNAKE) plus structured context fields. An agent (or a UI) can branch on\n// `err.code` instead of string-matching the human `.message`, and the catalogue is discoverable from\n// the `.d.ts` via the exported `DIG_SDK_ERROR_CODES` const and the `DigSdkErrorCode` union.\n//\n// The codes are symbolic and never derived from the human message — the message is for humans, the\n// code is for machines. Keep this catalogue and the README \"Error codes\" table in lockstep.\n\n/**\n * The stable error-code catalogue. Each value is an UPPER_SNAKE symbolic string that callers may\n * branch on. Frozen so it can't be mutated at runtime; the README documents each meaning.\n */\nexport const DIG_SDK_ERROR_CODES = Object.freeze({\n // ---- provider / connect (provider/chia-provider.ts, provider/*) ----\n /** WalletConnect was requested/needed but no `walletConnect` options were supplied. */\n WC_OPTIONS_REQUIRED: \"WC_OPTIONS_REQUIRED\",\n /** `mode: \"injected\"` (or the injected leg of `auto`) found no usable `window.chia`. */\n NO_INJECTED_WALLET: \"NO_INJECTED_WALLET\",\n /** The optional `@walletconnect/sign-client` peer dependency is not installed/usable. */\n WC_DEPENDENCY_MISSING: \"WC_DEPENDENCY_MISSING\",\n /** The active wallet session/transport does not grant the requested method. */\n METHOD_NOT_SUPPORTED: \"METHOD_NOT_SUPPORTED\",\n /** A wallet RPC timed out (e.g. Sage did not respond within the per-request timeout). */\n WALLET_TIMEOUT: \"WALLET_TIMEOUT\",\n /** The wallet returned no public keys / no key to sign with. */\n WALLET_NO_KEYS: \"WALLET_NO_KEYS\",\n\n // ---- read-crypto / RPC (dig-client.ts, loader.ts) ----\n /** A content read needs a confirmed on-chain root and none was supplied/derivable. */\n ROOT_REQUIRED: \"ROOT_REQUIRED\",\n /** The resource did not decrypt+authenticate under this URN (wrong key/salt, or a decoy). */\n DECRYPT_FAILED: \"DECRYPT_FAILED\",\n /** The dig RPC could not be reached (network/transport failure). */\n RPC_TRANSPORT: \"RPC_TRANSPORT\",\n /** The dig RPC responded with an HTTP error or a JSON-RPC `error` object. */\n RPC_ERROR: \"RPC_ERROR\",\n /** The dig RPC returned a malformed / inconsistent payload (e.g. chunk-length mismatch). */\n RPC_MALFORMED_RESPONSE: \"RPC_MALFORMED_RESPONSE\",\n /** The vendored read-crypto wasm failed its SRI integrity check — fail closed. */\n WASM_INTEGRITY: \"WASM_INTEGRITY\",\n /** The read-crypto wasm could not be loaded (fetch/resolve failure). */\n WASM_LOAD_FAILED: \"WASM_LOAD_FAILED\",\n\n // ---- paywall / spends (paywall.ts) ----\n /** The canonical chip35 wasm builder for this operation is unavailable (never hand-rolled). */\n SPEND_BUILDER_UNAVAILABLE: \"SPEND_BUILDER_UNAVAILABLE\",\n /** No secure random source was available to generate a payment nonce. */\n NO_SECURE_RANDOM: \"NO_SECURE_RANDOM\",\n\n // ---- deploy / adapters (adapters/run.ts, adapters/deploy.ts) ----\n /** The `digstore` binary could not be spawned (not installed / not on PATH). */\n DIGSTORE_NOT_FOUND: \"DIGSTORE_NOT_FOUND\",\n /** `digstore deploy` exited non-zero. */\n DEPLOY_FAILED: \"DEPLOY_FAILED\",\n /** `digstore deploy --json` output could not be parsed into a capsule result. */\n DEPLOY_OUTPUT_UNPARSEABLE: \"DEPLOY_OUTPUT_UNPARSEABLE\",\n\n // ---- argument validation (shared) ----\n /** An argument was malformed (e.g. a non-hex string, a bad URN, mutually-exclusive options). */\n INVALID_ARGUMENT: \"INVALID_ARGUMENT\",\n} as const);\n\n/** The union of every stable SDK error code. Branch on `err.code` against these. */\nexport type DigSdkErrorCode = (typeof DIG_SDK_ERROR_CODES)[keyof typeof DIG_SDK_ERROR_CODES];\n\n/** Structured, code-specific context attached to a {@link DigSdkError}. All fields optional. */\nexport interface DigSdkErrorContext {\n /** The dig RPC method involved (RPC_* errors). */\n rpcMethod?: string;\n /** The HTTP status returned (RPC_ERROR on a non-2xx). */\n httpStatus?: number;\n /** The JSON-RPC error code returned by the server (RPC_ERROR). */\n rpcCode?: number;\n /** The `digstore` process exit code (DEPLOY_FAILED). */\n exitCode?: number | null;\n /** The wallet method that was unsupported (METHOD_NOT_SUPPORTED). */\n method?: string;\n /** The connection mode in play (provider errors). */\n mode?: string;\n /** The offending value (INVALID_ARGUMENT — e.g. the bad hex / URN). */\n value?: string;\n /** The expected vs actual SRI digest (WASM_INTEGRITY). */\n expected?: string;\n actual?: string;\n /** Any further structured detail; kept open so codes can carry extra fields. */\n [key: string]: unknown;\n}\n\n/**\n * The SDK's typed error. Always thrown (never a bare `Error`) so consumers can branch on `.code`.\n *\n * @example\n * try {\n * await dig.read({ urn });\n * } catch (e) {\n * if (e instanceof DigSdkError && e.code === \"ROOT_REQUIRED\") promptForRoot();\n * else throw e;\n * }\n */\n/**\n * A brand stamped on every {@link DigSdkError}. The SDK ships several independently-bundled entry\n * points (index, adapters, vite, next, dig-client), each of which inlines its own copy of this\n * module — so two `DigSdkError`s can have DIFFERENT class identities across bundles and a plain\n * `instanceof` would miss one. {@link isDigSdkError} brand-checks instead, so a coded error thrown\n * from `@dignetwork/dig-sdk/adapters` is still recognized by `isDigSdkError` imported from the main\n * entry. Non-enumerable so it never shows up in `toJSON()` / spreads.\n */\nconst DIG_SDK_ERROR_BRAND = \"__dignetwork_dig_sdk_error__\";\n\nexport class DigSdkError extends Error {\n /** The stable machine code (UPPER_SNAKE). Branch on this, not the message. */\n readonly code: DigSdkErrorCode;\n /** Structured, code-specific context (rpcMethod, httpStatus, exitCode, …). */\n readonly context: DigSdkErrorContext;\n\n constructor(\n code: DigSdkErrorCode,\n message: string,\n context: DigSdkErrorContext = {},\n options: { cause?: unknown } = {},\n ) {\n super(message);\n this.name = \"DigSdkError\";\n this.code = code;\n this.context = context;\n // Set `cause` directly (rather than via the ES2022 Error options arg) so the lib target stays\n // ES2020 while still preserving the underlying error for diagnostics.\n if (options.cause !== undefined) {\n (this as { cause?: unknown }).cause = options.cause;\n }\n // Brand the instance (non-enumerable) so isDigSdkError recognizes it across bundle boundaries.\n Object.defineProperty(this, DIG_SDK_ERROR_BRAND, { value: true, enumerable: false });\n // Preserve a correct prototype chain when compiled to ES5-ish targets / across realms.\n Object.setPrototypeOf(this, DigSdkError.prototype);\n }\n\n /** A JSON-friendly view of the error: `{ code, message, context }`. */\n toJSON(): { code: DigSdkErrorCode; message: string; context: DigSdkErrorContext } {\n return { code: this.code, message: this.message, context: this.context };\n }\n}\n\n/**\n * True iff `e` is a {@link DigSdkError} (optionally with a specific `code`). Uses a non-enumerable\n * BRAND rather than `instanceof` so it recognizes coded errors thrown from any of the SDK's\n * separately-bundled entry points (the main entry and `/adapters` inline distinct class identities).\n */\nexport function isDigSdkError(e: unknown, code?: DigSdkErrorCode): e is DigSdkError {\n const branded =\n e instanceof DigSdkError ||\n (typeof e === \"object\" && e !== null && (e as Record<string, unknown>)[DIG_SDK_ERROR_BRAND] === true);\n return branded && (code === undefined || (e as DigSdkError).code === code);\n}\n","// Cross-target loader for the vendored `dig_client` read-crypto WASM.\n//\n// The wasm is the SAME artifact the DIG Browser, extension, companion, and hub all run — vendored\n// under vendor/ with a PROVENANCE note and pinned SRI (see vendor/PROVENANCE.md). We NEVER run it\n// unverified: we obtain the raw bytes, SHA-256 them, compare against the pinned digest, and only\n// then hand the verified bytes to wasm-bindgen's init. A mismatch (tampered / wrong artifact)\n// throws — the reader FAILS CLOSED rather than running unverified crypto.\n//\n// Three runtimes are supported, auto-detected, with an escape hatch (`configureWasm`):\n// • Node / Bun — read vendor/ files from the package directory (fs + node:crypto).\n// • Browser (bundled) — the consumer's bundler can resolve the vendor files; if it can't, the\n// consumer supplies bytes via `configureWasm({ wasmBytes, glueUrl })`.\n// • Browser (no bundler) — `configureWasm` with a URL/bytes you serve yourself.\n//\n// Memoized: the wasm initializes at most once per process/page.\n\nimport type { DigClientWasm } from \"./wasm.js\";\nimport { DigSdkError } from \"./errors.js\";\n\n/** SHA-256 (lowercase hex) of vendor/dig_client_bg.wasm — the SRI digest. Fail closed on mismatch. */\nexport const DIG_CLIENT_WASM_SHA256 =\n \"ff486be806f908a2a90780e499a04dbd34e10e3b97be0470cb9ee841a1e49e77\";\n\n/** Optional explicit wasm inputs, for environments where auto-resolution can't find vendor/. */\nexport interface WasmConfig {\n /**\n * The wasm bytes (already loaded). When provided, SRI is still enforced unless `skipIntegrity`.\n * Pass this in CSP-strict browsers where you fetch + verify the bytes yourself.\n */\n wasmBytes?: BufferSource;\n /**\n * URL to the wasm-bindgen glue module (vendor/dig_client.mjs) for browser dynamic import. When\n * omitted in a browser, the loader tries to import the glue relative to this module.\n */\n glueUrl?: string;\n /**\n * URL to fetch the wasm bytes from (browser) when `wasmBytes` is not supplied. The fetched bytes\n * are SRI-verified before init.\n */\n wasmUrl?: string;\n /** Skip the SRI check. Only for tests / trusted custom builds — NOT recommended. */\n skipIntegrity?: boolean;\n}\n\nlet _config: WasmConfig = {};\nlet _ready: Promise<DigClientWasm> | null = null;\n\n/**\n * Override how the read-crypto wasm is located/loaded. Call BEFORE the first `DigClient` read.\n * Mainly for browsers without a bundler that resolves package files, or CSP-strict apps that fetch\n * + verify the wasm bytes themselves and hand them in. Resets any cached instance.\n */\nexport function configureWasm(config: WasmConfig): void {\n _config = { ...config };\n _ready = null;\n}\n\nconst isNode =\n typeof process !== \"undefined\" &&\n !!(process as { versions?: { node?: string } }).versions?.node;\n\n/** SHA-256 a buffer to lowercase hex, using node:crypto or WebCrypto. */\nasync function sha256Hex(bytes: BufferSource): Promise<string> {\n if (isNode) {\n const { createHash } = await import(\"node:crypto\");\n const view =\n bytes instanceof ArrayBuffer\n ? new Uint8Array(bytes)\n : new Uint8Array(\n (bytes as ArrayBufferView).buffer,\n (bytes as ArrayBufferView).byteOffset,\n (bytes as ArrayBufferView).byteLength,\n );\n return createHash(\"sha256\").update(view).digest(\"hex\");\n }\n const digest = await crypto.subtle.digest(\"SHA-256\", bytes as BufferSource);\n return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction assertIntegrity(hex: string): void {\n if (_config.skipIntegrity) return;\n if (hex !== DIG_CLIENT_WASM_SHA256) {\n throw new DigSdkError(\n \"WASM_INTEGRITY\",\n \"dig-client wasm integrity check failed — refusing to run unverified crypto \" +\n `(expected ${DIG_CLIENT_WASM_SHA256}, got ${hex}).`,\n { expected: DIG_CLIENT_WASM_SHA256, actual: hex },\n );\n }\n}\n\n// Read the vendored glue URL + wasm bytes for Node from the package's vendor/ directory.\nasync function loadNode(): Promise<{ glueHref: string; bytes: BufferSource }> {\n const { readFile } = await import(\"node:fs/promises\");\n const { fileURLToPath, pathToFileURL } = await import(\"node:url\");\n const path = await import(\"node:path\");\n // This module lives in dist/; vendor/ sits at the package root, one level up.\n const here = path.dirname(fileURLToPath(import.meta.url));\n const vendorDir = path.resolve(here, \"..\", \"vendor\");\n const wasmPath = path.join(vendorDir, \"dig_client_bg.wasm\");\n const gluePath = path.join(vendorDir, \"dig_client.mjs\");\n const buf = await readFile(wasmPath);\n // Copy into a fresh ArrayBuffer-backed view so the type is a plain BufferSource (not the\n // ArrayBufferLike/SharedArrayBuffer union the Node Buffer type widens to).\n const bytes = new Uint8Array(buf.byteLength);\n bytes.set(buf);\n return { glueHref: pathToFileURL(gluePath).href, bytes };\n}\n\n// Resolve the glue URL + wasm bytes for a browser. Prefers explicit config; otherwise resolves\n// the vendored files relative to this module (works when the bundler copies vendor/ alongside).\nasync function loadBrowser(): Promise<{ glueHref: string; bytes: BufferSource }> {\n const glueHref =\n _config.glueUrl ?? new URL(\"../vendor/dig_client.mjs\", import.meta.url).href;\n let bytes: BufferSource;\n if (_config.wasmBytes) {\n bytes = _config.wasmBytes;\n } else {\n const wasmUrl =\n _config.wasmUrl ?? new URL(\"../vendor/dig_client_bg.wasm\", import.meta.url).href;\n const res = await fetch(wasmUrl);\n if (!res.ok)\n throw new DigSdkError(\"WASM_LOAD_FAILED\", `dig-client wasm fetch failed (${res.status})`, {\n httpStatus: res.status,\n wasmUrl,\n });\n bytes = await res.arrayBuffer();\n }\n return { glueHref, bytes };\n}\n\n/**\n * Load, SRI-verify, and instantiate the read-crypto wasm, returning its functions. Memoized — at\n * most one init per process/page. Fails closed on an integrity mismatch.\n */\nexport function loadDigClientWasm(): Promise<DigClientWasm> {\n if (_ready) return _ready;\n _ready = (async () => {\n const { glueHref, bytes } = isNode ? await loadNode() : await loadBrowser();\n assertIntegrity(await sha256Hex(bytes));\n const mod = (await import(/* @vite-ignore */ glueHref)) as {\n default: (input: { module_or_path: BufferSource }) => Promise<unknown>;\n } & Partial<DigClientWasm>;\n // wasm-bindgen default export = async init; accepts raw bytes via { module_or_path }.\n await mod.default({ module_or_path: bytes });\n return mod as unknown as DigClientWasm;\n })().catch((e) => {\n _ready = null; // allow a retry on transient load failure\n throw e;\n });\n return _ready;\n}\n","// DIG URN parsing + canonicalization — PURE, dependency-free, and identical to the parser the\n// hub (apps/web/lib/dig-client.js), the extension, and the companion use. Kept pure (no wasm) so\n// it is trivially unit-testable under `node --test` and usable on any runtime.\n//\n// A DIG URN addresses one resource inside a store:\n//\n// urn:dig:chia:<store_id>[:<root>]/<resource_key>[?salt=<hex>]\n//\n// • <store_id> — 64 hex chars, the singleton launcher id (the store identity).\n// • :<root> — OPTIONAL 64 hex chars, pins a specific on-chain generation. Omit for the\n// canonical, root-INDEPENDENT form. The root is only the trust anchor for\n// inclusion verification; it is NOT a key input (retrieval/decryption keys are\n// root-independent).\n// • <resource_key> — the path within the store (e.g. \"index.html\", \"img/logo.png\"). An empty\n// key resolves to the §8.5 default view \"index.html\".\n// • ?salt=<hex> — OPTIONAL out-of-band secret salt for a PRIVATE store.\n\nimport { DigSdkError } from \"./errors.js\";\n\n/** The parts of a parsed DIG URN. `root`/`salt` are null when absent. */\nexport interface ParsedUrn {\n /** Store identity (64-hex launcher id), lowercased. */\n readonly storeId: string;\n /** Generation root (64-hex), lowercased — or null for the root-independent form. */\n readonly root: string | null;\n /** Resource path within the store (verbatim, not lowercased). */\n readonly resourceKey: string;\n /** Private-store secret salt (hex), lowercased — or null for a public store. */\n readonly salt: string | null;\n}\n\nconst URN_RE =\n /^urn:dig:chia:([0-9a-fA-F]{64})(?::([0-9a-fA-F]{64}))?\\/(.+?)(?:\\?salt=([0-9a-fA-F]+))?$/;\n\n/**\n * Parse a DIG URN into its parts. Throws on a malformed URN.\n *\n * @example\n * parseUrn(\"urn:dig:chia:\" + \"ab\".repeat(32) + \"/index.html\")\n * // → { storeId: \"abab…\", root: null, resourceKey: \"index.html\", salt: null }\n */\nexport function parseUrn(raw: string): ParsedUrn {\n const s = String(raw ?? \"\").trim();\n const m = URN_RE.exec(s);\n if (!m) {\n throw new DigSdkError(\n \"INVALID_ARGUMENT\",\n \"Not a valid dig URN (expected urn:dig:chia:<store-id>[:<root>]/<path>[?salt=<hex>]).\",\n { value: s, expected: \"urn:dig:chia:<store-id>[:<root>]/<path>[?salt=<hex>]\" },\n );\n }\n return {\n storeId: m[1]!.toLowerCase(),\n root: m[2] ? m[2].toLowerCase() : null,\n resourceKey: m[3]!,\n salt: m[4] ? m[4].toLowerCase() : null,\n };\n}\n\n/** True iff `raw` is a syntactically valid DIG URN. Never throws. */\nexport function isUrn(raw: string): boolean {\n try {\n parseUrn(raw);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Reconstruct the canonical, root-INDEPENDENT URN string for a store + resource key:\n * `urn:dig:chia:<store_id>/<resource_key>`. An empty resource key resolves to the default view\n * `index.html`. This is the form whose SHA-256 is the retrieval key and whose bytes seed the AES\n * key — matching the wasm's `reconstructUrn`.\n */\nexport function reconstructUrn(storeId: string, resourceKey: string): string {\n const key = resourceKey && resourceKey.length > 0 ? resourceKey : \"index.html\";\n return `urn:dig:chia:${storeId.toLowerCase()}/${key}`;\n}\n\n/**\n * Reconstruct a root-PINNED display URN: `urn:dig:chia:<store_id>:<root>/<resource_key>`. Useful\n * for sharing a URN bound to a specific generation; the retrieval/AES keys still use the rootless\n * form (`reconstructUrn`).\n */\nexport function reconstructUrnWithRoot(\n storeId: string,\n root: string,\n resourceKey: string,\n): string {\n const key = resourceKey && resourceKey.length > 0 ? resourceKey : \"index.html\";\n return `urn:dig:chia:${storeId.toLowerCase()}:${root.toLowerCase()}/${key}`;\n}\n","// DigClient — the read side of the SDK. It fetches a resource's served ciphertext from the dig RPC,\n// derives the URN's keys CLIENT-SIDE via the read-crypto wasm, verifies inclusion against an\n// on-chain root, and decrypts — so the serving host stays BLIND (it only ever relays opaque\n// ciphertext + proofs). Genericized from hub.dig.net/apps/web/lib/dig-client.js, with the hub-app\n// coupling removed (no Vite import.meta.env, no window.location origin; the RPC endpoint and the\n// trust root are explicit inputs).\n//\n// HARD BOUNDARY (read sources). Everything read from a .dig — ciphertext, inclusion proofs, the\n// public manifest, metadata — comes ONLY from the dig RPC. The trust ROOT it is verified against\n// comes from the chain (the caller resolves it from coinset.org and passes it in). The host can\n// never become the trust anchor: every content read REQUIRES a caller-supplied root.\n//\n// OBLIVIOUS model. The host returns indistinguishable ciphertext for any retrieval key, so\n// presence is UNKNOWABLE. A read therefore NEVER concludes \"not found\": it returns plaintext when\n// the URN key decrypts the bytes, otherwise the raw ciphertext (a decoy is just opaque bytes). The\n// only thrown error is a transport failure.\n\nimport { loadDigClientWasm } from \"./loader.js\";\nimport type { DigClientWasm } from \"./wasm.js\";\nimport { parseUrn } from \"./urn.js\";\nimport type {\n CollectionItemsPage,\n CollectionMeta,\n ReadOptions,\n ReadResult,\n UrnKeys,\n} from \"./types.js\";\nimport { DigSdkError } from \"./errors.js\";\n\n/** The default public dig RPC endpoint. */\nexport const DEFAULT_RPC = \"https://rpc.dig.net\";\n\n// The backend caps each dig.getContent chunk at 3 MiB (Lambda/APIGW response ceiling); the client\n// loops chunks until `complete`.\nconst RPC_CHUNK_BYTES = 3 * 1024 * 1024;\n\n/** Options to construct a DigClient. */\nexport interface DigClientOptions {\n /** dig RPC endpoint. Defaults to the public `https://rpc.dig.net`. */\n rpc?: string;\n /** Override `fetch` (e.g. an instrumented one). Defaults to the global `fetch`. */\n fetch?: typeof fetch;\n}\n\ninterface GetContentResult {\n total_length: number;\n offset: number;\n next_offset?: number | null;\n complete?: boolean;\n ciphertext?: string;\n inclusion_proof?: string;\n chunk_lens?: number[];\n}\n\n/** Decode a standard-base64 string (the RPC ciphertext encoding) to bytes — no DOM dependency. */\nfunction b64ToBytes(b64: string): Uint8Array {\n // atob exists in browsers and modern Node; fall back to Buffer in older Node.\n if (typeof atob === \"function\") {\n const bin = atob(b64);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return new Uint8Array((globalThis as any).Buffer.from(b64, \"base64\"));\n}\n\n/**\n * The read-crypto client. Construct once and reuse — the wasm is loaded + SRI-verified lazily on\n * the first read and memoized process/page-wide.\n *\n * @example\n * const dig = new DigClient();\n * const { bytes, decrypted } = await dig.read({\n * urn: \"urn:dig:chia:<storeId>/index.html\",\n * root: \"<onchain-root-hex>\",\n * });\n * if (decrypted) console.log(new TextDecoder().decode(bytes));\n */\nexport class DigClient {\n private readonly rpc: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(options: DigClientOptions = {}) {\n this.rpc = options.rpc ?? DEFAULT_RPC;\n this.fetchImpl =\n options.fetch ??\n (typeof fetch === \"function\" ? fetch.bind(globalThis) : undefinedFetch());\n }\n\n /** Load (and SRI-verify) the read-crypto wasm. Exposed for callers that want the raw functions. */\n async wasm(): Promise<DigClientWasm> {\n return loadDigClientWasm();\n }\n\n /** `retrieval_key = SHA-256(canonical rootless URN)`, lowercase hex. */\n async retrievalKey(storeId: string, resourceKey: string): Promise<string> {\n return (await this.wasm()).retrievalKey(storeId, resourceKey);\n }\n\n /** Derive the per-URN AES-256-GCM-SIV key, lowercase hex. `salt` for a private store. */\n async deriveKey(\n storeId: string,\n resourceKey: string,\n salt?: string | null,\n ): Promise<string> {\n return (await this.wasm()).deriveKey(storeId, resourceKey, salt ?? undefined);\n }\n\n /** Verify served `ciphertext` is included under `root` via the base64 merkle `proof`. */\n async verifyInclusion(\n ciphertext: Uint8Array,\n proof: string,\n root: string,\n ): Promise<boolean> {\n return (await this.wasm()).verifyInclusion(ciphertext, proof, root);\n }\n\n /** Reconstruct the canonical rootless URN whose SHA-256 is the retrieval key. */\n async reconstructUrn(storeId: string, resourceKey: string): Promise<string> {\n return (await this.wasm()).reconstructUrn(storeId, resourceKey);\n }\n\n /**\n * Derive, client-side, the two root-independent keys a URN maps to (retrieval + decryption).\n * Nothing is sent to the network — pure local derivation via the wasm.\n */\n async deriveUrnKeys(input: { urn: string; salt?: string | null }): Promise<UrnKeys> {\n const parsed = parseUrn(input.urn);\n const wasm = await this.wasm();\n const effSalt = input.salt ?? parsed.salt ?? undefined;\n return {\n storeId: parsed.storeId,\n root: parsed.root,\n resourceKey: parsed.resourceKey,\n salt: effSalt ?? null,\n retrievalKey: wasm.retrievalKey(parsed.storeId, parsed.resourceKey),\n decryptionKey: wasm.deriveKey(parsed.storeId, parsed.resourceKey, effSalt),\n };\n }\n\n /**\n * Fetch + verify + decrypt one resource by URN. `root` is the on-chain generation root to verify\n * against (resolved by the caller from the chain); when omitted, the root embedded in the URN is\n * used. Returns the bytes plus advisory `verified`/`decrypted` flags. NEVER throws \"not found\"\n * (presence is unknowable) — it throws only on a transport failure.\n */\n async read(\n input: { urn: string; root?: string | null; salt?: string | null },\n opts: ReadOptions = {},\n ): Promise<ReadResult> {\n const parsed = parseUrn(input.urn);\n const effSalt = input.salt ?? parsed.salt ?? null;\n const effRoot = input.root ?? parsed.root ?? null;\n if (!effRoot) {\n throw new DigSdkError(\n \"ROOT_REQUIRED\",\n \"a confirmed on-chain root is required to read content (pass { root } or use a root-pinned URN)\",\n { urn: input.urn },\n );\n }\n return this.readResource(\n { storeId: parsed.storeId, resourceKey: parsed.resourceKey, root: effRoot, salt: effSalt },\n opts,\n );\n }\n\n /** As `read`, but decoding the plaintext to a UTF-8 string when it decrypts (else throws). */\n async readText(\n input: { urn: string; root?: string | null; salt?: string | null },\n opts: ReadOptions = {},\n ): Promise<string> {\n const r = await this.read(input, opts);\n if (!r.decrypted) {\n throw new DigSdkError(\n \"DECRYPT_FAILED\",\n \"resource did not decrypt under this URN — wrong store/key/salt, or a decoy response\",\n { urn: input.urn },\n );\n }\n return new TextDecoder().decode(r.bytes);\n }\n\n /**\n * Read by explicit (storeId, resourceKey, root, salt) rather than a URN string. The oblivious\n * download primitive the URN read is built on.\n */\n async readResource(\n input: { storeId: string; resourceKey: string; root: string; salt?: string | null },\n opts: ReadOptions = {},\n ): Promise<ReadResult> {\n const rpc = opts.rpc ?? this.rpc;\n const wasm = await this.wasm();\n const rk = wasm.retrievalKey(input.storeId, input.resourceKey);\n const { ciphertext, proof, chunkLens } = await this.fetchCiphertext(\n input.storeId,\n rk,\n input.root,\n rpc,\n );\n let verified = false;\n try {\n verified = !!wasm.verifyInclusion(ciphertext, proof, input.root);\n } catch {\n verified = false;\n }\n const keyHex = wasm.deriveKey(input.storeId, input.resourceKey, input.salt ?? undefined);\n try {\n const bytes = decryptResourceChunks(wasm, keyHex, ciphertext, chunkLens);\n return {\n storeId: input.storeId,\n root: input.root,\n resourceKey: input.resourceKey,\n salt: input.salt ?? null,\n bytes,\n verified,\n decrypted: true,\n };\n } catch {\n // Not decryptable with this URN/salt — hand back the raw bytes; never a \"not present\" verdict.\n return {\n storeId: input.storeId,\n root: input.root,\n resourceKey: input.resourceKey,\n salt: input.salt ?? null,\n bytes: ciphertext,\n verified,\n decrypted: false,\n };\n }\n }\n\n /**\n * Read a collection's public, owner-independent facts (creator DID, item count, uniform royalty)\n * from the dig RPC (`dig.getCollection`). The collection's item set is its NFT launcher ids — the\n * authoritative, owner-independent anchor the mint produced (a DID-attributed NFT is hinted to its\n * OWNER at mint, not to the creator DID, so launcher ids — not the DID — are the read key). Pass\n * the optional `did` to have it echoed back and recorded as the declared creator.\n *\n * No wallet, no read-crypto wasm — a plain JSON-RPC read. Throws a coded {@link DigSdkError} on a\n * transport/RPC failure (never a \"not found\": an empty/partly-confirmed set just resolves to fewer\n * items).\n *\n * @example\n * const meta = await dig.getCollection({ launcherIds: [\"ab…\", \"cd…\"], did: \"ef…\" });\n * console.log(meta.resolved_count, meta.royalty_basis_points);\n */\n async getCollection(\n input: { launcherIds: string[]; did?: string | null },\n opts: ReadOptions = {},\n ): Promise<CollectionMeta> {\n const rpc = opts.rpc ?? this.rpc;\n const params: Record<string, unknown> = { launcher_ids: input.launcherIds };\n if (input.did) params.did = input.did;\n const r = await this.rpcCall<CollectionMeta>(rpc, \"dig.getCollection\", params);\n if (!r)\n throw new DigSdkError(\n \"RPC_MALFORMED_RESPONSE\",\n \"The content network returned no collection facts for this request.\",\n { rpcMethod: \"dig.getCollection\" },\n );\n return r;\n }\n\n /**\n * Read a deterministic, paginated page of a collection's items (`dig.listCollectionItems`), each\n * resolved to its CURRENT on-chain state — current owner, royalty, and CHIP-0007 metadata — by the\n * RPC walking the singleton lineage forward to the live tip (so the owner is never the stale\n * mint-time owner). Items come back in the input launcher-id order. `limit` is clamped to the\n * server cap (200); `offset` defaults to 0.\n *\n * Throws a coded {@link DigSdkError} on a transport/RPC failure.\n *\n * @example\n * let page = await dig.listCollectionItems({ launcherIds, limit: 50 });\n * for (const item of page.items) console.log(item.launcher_id, item.owner_puzzle_hash);\n * // page.next_offset is null on the last page.\n */\n async listCollectionItems(\n input: { launcherIds: string[]; offset?: number; limit?: number },\n opts: ReadOptions = {},\n ): Promise<CollectionItemsPage> {\n const rpc = opts.rpc ?? this.rpc;\n const params: Record<string, unknown> = { launcher_ids: input.launcherIds };\n if (input.offset !== undefined) params.offset = input.offset;\n if (input.limit !== undefined) params.limit = input.limit;\n const r = await this.rpcCall<CollectionItemsPage>(rpc, \"dig.listCollectionItems\", params);\n if (!r)\n throw new DigSdkError(\n \"RPC_MALFORMED_RESPONSE\",\n \"The content network returned no collection items for this request.\",\n { rpcMethod: \"dig.listCollectionItems\" },\n );\n return r;\n }\n\n // Stream the FULL ciphertext for a resource from the RPC by retrieval key, reassembling 3-MiB\n // chunks. A null result is a TRANSPORT failure, never a presence judgment.\n private async fetchCiphertext(\n storeId: string,\n rk: string,\n root: string,\n rpc: string,\n ): Promise<{ ciphertext: Uint8Array; proof: string; chunkLens: number[] | null }> {\n let offset = 0;\n let total: number | null = null;\n let buf: Uint8Array | null = null;\n let proof = \"\";\n let chunkLens: number[] | null = null;\n for (;;) {\n const r = await this.rpcCall<GetContentResult>(rpc, \"dig.getContent\", {\n store_id: storeId,\n root,\n retrieval_key: rk,\n offset,\n length: RPC_CHUNK_BYTES,\n });\n if (!r)\n throw new DigSdkError(\n \"RPC_MALFORMED_RESPONSE\",\n \"The content network returned no data for this request.\",\n { rpcMethod: \"dig.getContent\" },\n );\n if (total === null) {\n total = r.total_length >>> 0;\n buf = new Uint8Array(total);\n }\n if (chunkLens === null && Array.isArray(r.chunk_lens)) {\n chunkLens = r.chunk_lens.map((n) => n >>> 0);\n }\n const chunk = b64ToBytes(r.ciphertext ?? \"\");\n const at = r.offset >>> 0;\n buf!.set(chunk.subarray(0, Math.max(0, Math.min(chunk.length, total - at))), at);\n if (r.inclusion_proof) proof = r.inclusion_proof;\n if (r.complete || r.next_offset == null) break;\n offset = r.next_offset >>> 0;\n }\n return { ciphertext: buf ?? new Uint8Array(0), proof, chunkLens };\n }\n\n // One JSON-RPC 2.0 call. Throws a coded DigSdkError on transport failure (RPC_TRANSPORT) or a\n // JSON-RPC/HTTP error (RPC_ERROR, carrying rpcMethod/httpStatus/rpcCode context); returns `result`.\n private async rpcCall<T>(rpc: string, method: string, params: unknown): Promise<T | null> {\n let res: Response;\n try {\n res = await this.fetchImpl(rpc, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ jsonrpc: \"2.0\", id: 1, method, params }),\n });\n } catch (e) {\n throw new DigSdkError(\n \"RPC_TRANSPORT\",\n \"Could not reach the content network. Check your connection and try again.\",\n { rpcMethod: method },\n { cause: e },\n );\n }\n if (!res.ok)\n throw new DigSdkError(\"RPC_ERROR\", `dig RPC ${method} failed (${res.status})`, {\n rpcMethod: method,\n httpStatus: res.status,\n });\n const json = (await res.json()) as {\n result?: T;\n error?: { message?: string; code?: number };\n };\n if (json && json.error)\n throw new DigSdkError(\n \"RPC_ERROR\",\n `dig RPC ${method}: ${json.error.message ?? \"error\"}`,\n { rpcMethod: method, rpcCode: json.error.code },\n );\n return json ? (json.result ?? null) : null;\n }\n}\n\n// AES-256-GCM-SIV-open a resource's served ciphertext under `keyHex`, splitting the PLAIN-\n// concatenated chunk ciphertexts by `chunkLens` (per-chunk CIPHERTEXT byte lengths) and opening\n// each. Empty/absent chunkLens ⇒ single-chunk resource. Throws if any chunk's tag fails.\nfunction decryptResourceChunks(\n wasm: DigClientWasm,\n keyHex: string,\n ciphertext: Uint8Array,\n chunkLens: number[] | null,\n): Uint8Array {\n const lens = chunkLens && chunkLens.length ? chunkLens : [ciphertext.length];\n const total = lens.reduce((a, n) => a + n, 0);\n if (total !== ciphertext.length) {\n throw new DigSdkError(\n \"RPC_MALFORMED_RESPONSE\",\n \"served ciphertext length does not match chunk lengths\",\n { rpcMethod: \"dig.getContent\", expected: String(total), actual: String(ciphertext.length) },\n );\n }\n if (lens.length === 1) return wasm.decryptChunk(keyHex, ciphertext);\n const parts: Uint8Array[] = [];\n let p = 0;\n for (const len of lens) {\n parts.push(wasm.decryptChunk(keyHex, ciphertext.subarray(p, p + len)));\n p += len;\n }\n const out = new Uint8Array(parts.reduce((a, x) => a + x.length, 0));\n let q = 0;\n for (const part of parts) {\n out.set(part, q);\n q += part.length;\n }\n return out;\n}\n\nfunction undefinedFetch(): typeof fetch {\n return (() => {\n throw new DigSdkError(\n \"INVALID_ARGUMENT\",\n \"No global fetch available. Pass { fetch } to DigClient (Node < 18 needs a fetch polyfill).\",\n );\n }) as unknown as typeof fetch;\n}\n"]}
@@ -1 +1 @@
1
- export { D as DEFAULT_RPC, b as DIG_CLIENT_WASM_SHA256, c as DigClient, d as DigClientOptions, e as DigClientWasm, P as ParsedUrn, R as ReadOptions, f as ReadResult, U as UrnKeys, g as WasmConfig, h as configureWasm, i as isUrn, l as loadDigClientWasm, p as parseUrn, r as reconstructUrn, j as reconstructUrnWithRoot } from './dig-client-entry-BIzuZ7Rs.cjs';
1
+ export { D as DEFAULT_RPC, e as DIG_CLIENT_WASM_SHA256, f as DigClient, g as DigClientOptions, h as DigClientWasm, P as ParsedUrn, R as ReadOptions, i as ReadResult, U as UrnKeys, j as WasmConfig, k as configureWasm, l as isUrn, m as loadDigClientWasm, p as parseUrn, r as reconstructUrn, n as reconstructUrnWithRoot } from './dig-client-entry-ChYxUvBn.cjs';
@@ -1 +1 @@
1
- export { D as DEFAULT_RPC, b as DIG_CLIENT_WASM_SHA256, c as DigClient, d as DigClientOptions, e as DigClientWasm, P as ParsedUrn, R as ReadOptions, f as ReadResult, U as UrnKeys, g as WasmConfig, h as configureWasm, i as isUrn, l as loadDigClientWasm, p as parseUrn, r as reconstructUrn, j as reconstructUrnWithRoot } from './dig-client-entry-BIzuZ7Rs.js';
1
+ export { D as DEFAULT_RPC, e as DIG_CLIENT_WASM_SHA256, f as DigClient, g as DigClientOptions, h as DigClientWasm, P as ParsedUrn, R as ReadOptions, i as ReadResult, U as UrnKeys, j as WasmConfig, k as configureWasm, l as isUrn, m as loadDigClientWasm, p as parseUrn, r as reconstructUrn, n as reconstructUrnWithRoot } from './dig-client-entry-ChYxUvBn.js';