@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.
package/dist/adapters.js CHANGED
@@ -105,6 +105,24 @@ function resolveDeployConfig(input) {
105
105
  salt: envVal(env, "DIGSTORE_STORE_SALT")
106
106
  };
107
107
  }
108
+ var DIG_SDK_ERROR_BRAND = "__dignetwork_dig_sdk_error__";
109
+ var DigSdkError = class _DigSdkError extends Error {
110
+ constructor(code, message, context = {}, options = {}) {
111
+ super(message);
112
+ this.name = "DigSdkError";
113
+ this.code = code;
114
+ this.context = context;
115
+ if (options.cause !== void 0) {
116
+ this.cause = options.cause;
117
+ }
118
+ Object.defineProperty(this, DIG_SDK_ERROR_BRAND, { value: true, enumerable: false });
119
+ Object.setPrototypeOf(this, _DigSdkError.prototype);
120
+ }
121
+ /** A JSON-friendly view of the error: `{ code, message, context }`. */
122
+ toJSON() {
123
+ return { code: this.code, message: this.message, context: this.context };
124
+ }
125
+ };
108
126
 
109
127
  // src/adapters/deploy.ts
110
128
  function buildDeployArgs(cfg, opts = {}) {
@@ -128,9 +146,11 @@ var CAPSULE_RE = /^([0-9a-f]{64}):([0-9a-f]{64})$/i;
128
146
  function parseDeployResult(stdout) {
129
147
  const lines = stdout.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.startsWith("{") && l.endsWith("}"));
130
148
  if (lines.length === 0) {
131
- throw new Error(
149
+ throw new DigSdkError(
150
+ "DEPLOY_OUTPUT_UNPARSEABLE",
132
151
  `could not parse digstore deploy output (no JSON object found). Output was:
133
- ${stdout.slice(0, 500)}`
152
+ ${stdout.slice(0, 500)}`,
153
+ { stdout: stdout.slice(0, 500) }
134
154
  );
135
155
  }
136
156
  let obj;
@@ -152,28 +172,40 @@ ${stdout.slice(0, 500)}`
152
172
  }
153
173
  if (!obj) {
154
174
  if (fallback) {
155
- throw new Error(
175
+ throw new DigSdkError(
176
+ "DEPLOY_OUTPUT_UNPARSEABLE",
156
177
  `digstore deploy did not report a capsule (deploy may have failed). Output:
157
- ${JSON.stringify(fallback)}`
178
+ ${JSON.stringify(fallback)}`,
179
+ { output: fallback }
158
180
  );
159
181
  }
160
- throw new Error(`could not parse digstore deploy output as JSON:
161
- ${stdout.slice(0, 500)}`);
182
+ throw new DigSdkError(
183
+ "DEPLOY_OUTPUT_UNPARSEABLE",
184
+ `could not parse digstore deploy output as JSON:
185
+ ${stdout.slice(0, 500)}`,
186
+ { stdout: stdout.slice(0, 500) }
187
+ );
162
188
  }
163
189
  const capsule = obj.capsule;
164
190
  const m = CAPSULE_RE.exec(capsule);
165
191
  if (!m || m[1] === void 0 || m[2] === void 0) {
166
- throw new Error(`digstore deploy reported a malformed capsule "${capsule}" (expected storeId:root)`);
192
+ throw new DigSdkError(
193
+ "INVALID_ARGUMENT",
194
+ `digstore deploy reported a malformed capsule "${capsule}" (expected storeId:root)`,
195
+ { value: capsule, expected: "storeId:root" }
196
+ );
167
197
  }
168
198
  const storeId = m[1].toLowerCase();
169
199
  const root = (typeof obj.root === "string" ? obj.root : m[2]).toLowerCase();
200
+ const chiaUrl = typeof obj.content_address === "string" ? obj.content_address : `chia://${storeId}:${root}/`;
170
201
  return {
171
202
  capsule,
172
203
  storeId,
173
204
  root,
174
- // dig:// names the store on the network (resolves to its latest published version).
175
- digUrl: `dig://${storeId}`,
176
- // Mirrors digstore deploy.rs::hub_url — the public DIGHub view of an owned store.
205
+ chiaUrl,
206
+ // Deprecated alias: same chia:// content-open value (back-compat for consumers reading digUrl).
207
+ digUrl: chiaUrl,
208
+ // Mirrors digstore deploy.rs::hub_url — the public DIGHUb view of an owned store.
177
209
  hubUrl: `https://hub.dig.net/stores/${storeId}`,
178
210
  pushed: typeof obj.pushed === "boolean" ? obj.pushed : void 0
179
211
  };
@@ -283,20 +315,29 @@ async function runDeploy(options = {}) {
283
315
  });
284
316
  child.on("error", (e) => {
285
317
  reject(
286
- new Error(
287
- `could not run "${bin}" \u2014 is digstore installed and on PATH? (${e.message})`
318
+ new DigSdkError(
319
+ "DIGSTORE_NOT_FOUND",
320
+ `could not run "${bin}" \u2014 is digstore installed and on PATH? (${e.message})`,
321
+ { bin },
322
+ { cause: e }
288
323
  )
289
324
  );
290
325
  });
291
326
  child.on("close", (code) => {
292
327
  if (code === 0) resolve(out);
293
- else reject(new Error(`digstore deploy failed (exit ${code}).
294
- ${err || out}`));
328
+ else
329
+ reject(
330
+ new DigSdkError("DEPLOY_FAILED", `digstore deploy failed (exit ${code}).
331
+ ${err || out}`, {
332
+ exitCode: code,
333
+ stderr: err.slice(0, 2e3)
334
+ })
335
+ );
295
336
  });
296
337
  });
297
338
  const result = parseDeployResult(stdout);
298
339
  log(`\u2713 deployed capsule ${result.capsule}`);
299
- log(` dig:// ${result.digUrl}`);
340
+ log(` open ${result.chiaUrl}`);
300
341
  log(` view ${result.hubUrl}`);
301
342
  return result;
302
343
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/adapters/dig-toml.ts","../src/adapters/config.ts","../src/adapters/deploy.ts","../src/provider/injected.ts","../src/adapters/dev-shim.ts","../src/adapters/run.ts"],"names":[],"mappings":";AA0BA,IAAM,OAAA,GAA+C;AAAA,EACnD,QAAA,EAAU,SAAA;AAAA,EACV,UAAA,EAAY,SAAA;AAAA,EACZ,UAAA,EAAY,WAAA;AAAA,EACZ,YAAA,EAAc,WAAA;AAAA,EACd,aAAA,EAAe,cAAA;AAAA,EACf,eAAA,EAAiB,cAAA;AAAA,EACjB,OAAA,EAAS,SAAA;AAAA,EACT,OAAA,EAAS,SAAA;AAAA,EACT,MAAA,EAAQ,QAAA;AAAA,EACR,YAAA,EAAc,aAAA;AAAA,EACd,cAAA,EAAgB;AAClB,CAAA;AAGA,IAAM,WAAA,GAAc,MAAA,CAAO,IAAA,CAAK,OAAO,CAAA,CAAE,IAAA;AAAA,EAAK,CAAC,CAAA,KAC7C,CAAA,CAAE,QAAA,CAAS,GAAG,IAAI,CAAA,GAAI;AACxB,CA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Q,CAAC,CAAA,KAAc;AACrC,MAAA,GAAA,IAAO,EAAE,QAAA,EAAS;AAAA,IACpB,CAAC,CAAA;AACD,IAAA,KAAA,CAAM,MAAA,CAAO,EAAA,CAAG,MAAA,EAAQ,CAAC,CAAA,KAAc;AACrC,MAAA,GAAA,IAAO,EAAE,QAAA,EAAS;AAAA,IACpB,CAAC,CAAA;AACD,IAAA,KAAA,CAAM,EAAA,CAAG,OAAA,EAAS,CAAC,CAAA,KAAa;AAC9B,MAAA,MAAA;AAAA,QACE,IAAI,KAAA;AAAA,UACF,CAAA,eAAA,EAAkB,GAAG,CAAA,6CAAA,EAA2C,CAAA,CAAE,OAAO,CAAA,CAAA;AAAA;AAC3E,OACF;AAAA,IACF,CAAC,CAAA;AACD,IAAA,KAAA,CAAM,EAAA,CAAG,OAAA,EAAS,CAAC,IAAA,KAAwB;AACzC,MAAA,IAAI,IAAA,KAAS,CAAA,EAAG,OAAA,CAAQ,GAAG,CAAA;AAAA,WACtB,MAAA,CAAO,IAAI,KAAA,CAAM,CAAA,6BAAA,EAAgC,IAAI,CAAA;AAAA,EAAO,GAAA,IAAO,GAAG,CAAA,CAAE,CAAC,CAAA;AAAA,IAChF,CAAC,CAAA;AAAA,EACH,CAAC,CAAA;AAED,EAAA,MAAM,MAAA,GAAS,kBAAkB,MAAM,CAAA;AACvC,EAAA,GAAA,CAAI,CAAA,wBAAA,EAAsB,MAAA,CAAO,OAAO,CAAA,CAAE,CAAA;AAC1C,EAAA,GAAA,CAAI,CAAA,UAAA,EAAa,MAAA,CAAO,MAAM,CAAA,CAAE,CAAA;AAChC,EAAA,GAAA,CAAI,CAAA,UAAA,EAAa,MAAA,CAAO,MAAM,CAAA,CAAE,CAAA;AAChC,EAAA,OAAO,MAAA;AACT","file":"adapters.js","sourcesContent":["// Minimal `dig.toml` reader for the framework adapters.\n//\n// `digstore deploy` reads its config from a project's `dig.toml` (digstore-cli/src/dig_toml.rs).\n// The adapters need the SAME few top-level keys so a project's `dig.toml` is the single source of\n// truth across the CLI and the plugins. Rather than pull in a TOML parser dependency for ~7 flat\n// `key = \"value\"` lines, we parse just those keys ourselves. We accept BOTH the canonical\n// kebab-case key and the snake_case alias, exactly like digstore's `#[serde(rename/alias)]`.\n//\n// Anything beyond these keys (tables, arrays, nested values) is intentionally ignored — the\n// adapters only forward the deploy-relevant scalars to `digstore deploy`, which re-reads the full\n// file authoritatively.\n\n/** The deploy-relevant subset of `dig.toml`, in the adapters' camelCase shape. */\nexport interface DigTomlConfig {\n storeId?: string;\n outputDir?: string;\n buildCommand?: string;\n message?: string;\n network?: string;\n remote?: string;\n waitTimeout?: number;\n}\n\n// Map each canonical/alias TOML key onto the camelCase field. kebab-case is canonical (it is what\n// `digstore new` writes); snake_case is the tolerated alias. When both appear, the canonical\n// kebab-case key wins (it is applied last).\nconst KEY_MAP: Record<string, keyof DigTomlConfig> = {\n store_id: \"storeId\",\n \"store-id\": \"storeId\",\n output_dir: \"outputDir\",\n \"output-dir\": \"outputDir\",\n build_command: \"buildCommand\",\n \"build-command\": \"buildCommand\",\n message: \"message\",\n network: \"network\",\n remote: \"remote\",\n wait_timeout: \"waitTimeout\",\n \"wait-timeout\": \"waitTimeout\",\n};\n\n// Apply snake_case first then kebab-case so the canonical kebab form overrides the alias.\nconst APPLY_ORDER = Object.keys(KEY_MAP).sort((a) =>\n a.includes(\"-\") ? 1 : -1,\n);\n\n/** Strip a `# comment` that is not inside a quoted value. */\nfunction stripComment(line: string): string {\n let inSingle = false;\n let inDouble = false;\n for (let i = 0; i < line.length; i++) {\n const ch = line[i];\n if (ch === \"'\" && !inDouble) inSingle = !inSingle;\n else if (ch === '\"' && !inSingle) inDouble = !inDouble;\n else if (ch === \"#\" && !inSingle && !inDouble) return line.slice(0, i);\n }\n return line;\n}\n\n/** Unquote a TOML scalar: `\"x\"` / `'x'` → `x`; a bare token is returned trimmed. */\nfunction unquote(raw: string): string {\n const v = raw.trim();\n if (\n (v.startsWith('\"') && v.endsWith('\"') && v.length >= 2) ||\n (v.startsWith(\"'\") && v.endsWith(\"'\") && v.length >= 2)\n ) {\n return v.slice(1, -1);\n }\n return v;\n}\n\n/**\n * Parse the deploy-relevant keys out of a `dig.toml` string. Unknown keys, tables, and nested\n * structures are ignored. Returns only the keys actually present (so it composes cleanly under the\n * precedence rules in resolveDeployConfig).\n */\nexport function parseDigToml(text: string): DigTomlConfig {\n // Collect raw (canonical-or-alias) string values keyed by the TOML key as written.\n const raw: Record<string, string> = {};\n for (const lineRaw of text.split(/\\r?\\n/)) {\n const line = stripComment(lineRaw).trim();\n if (!line || line.startsWith(\"[\")) continue; // skip blanks + table headers\n const eq = line.indexOf(\"=\");\n if (eq <= 0) continue;\n const key = line.slice(0, eq).trim();\n if (!(key in KEY_MAP)) continue;\n raw[key] = unquote(line.slice(eq + 1));\n }\n\n const out: DigTomlConfig = {};\n for (const key of APPLY_ORDER) {\n const value = raw[key];\n const field = KEY_MAP[key];\n if (value === undefined || field === undefined) continue;\n if (field === \"waitTimeout\") {\n const n = Number.parseInt(value, 10);\n if (Number.isFinite(n)) out.waitTimeout = n;\n } else {\n out[field] = value;\n }\n }\n return out;\n}\n","// Deploy-config resolution for the framework adapters.\n//\n// The final config a deploy runs with is composed from three layers, highest precedence first:\n// 1. plugin options — what the developer wrote in vite.config / the Next adapter call\n// 2. environment vars — what CI injects (DIGSTORE_*), incl. the SECRETS (deploy key, salt)\n// 3. dig.toml — the project's checked-in defaults\n// 4. built-in defaults — outputDir=\"dist\", network=\"mainnet\" (mirrors deploy.rs::resolve_config)\n//\n// This mirrors `digstore deploy`'s own resolution order (flag/env > dig.toml > default) so the\n// adapters never disagree with the CLI about what a project deploys. SECRETS are resolved ONLY from\n// env — never from options or dig.toml — so they can't end up checked into a repo or a config file.\n\nimport type { DigTomlConfig } from \"./dig-toml.js\";\n\n/** Per-call options a developer passes to the Vite plugin / Next adapter. */\nexport interface AdapterOptions {\n /** On-chain store id (64-hex) to advance. Usually set in dig.toml instead. */\n storeId?: string;\n /** Built-output directory to publish. Defaults to the framework's output (or \"dist\"). */\n outputDir?: string;\n /** Shell build command for `digstore` to run. Omit when the adapter builds itself. */\n buildCommand?: string;\n /** Commit message for the new capsule. */\n message?: string;\n /** Chain network. Defaults to \"mainnet\". */\n network?: string;\n /** The `origin` remote to publish to (e.g. `dig://<storeId>`). */\n remote?: string;\n /** Seconds to wait for on-chain confirmation. */\n waitTimeout?: number;\n}\n\n/** The fully resolved config a deploy runs with. Secrets are present only if env supplied them. */\nexport interface ResolvedDeployConfig {\n storeId?: string;\n outputDir: string;\n buildCommand?: string;\n message?: string;\n network: string;\n remote?: string;\n waitTimeout?: number;\n /** Publisher deploy key (64-hex). From env only. */\n deployKey?: string;\n /** Private-store secret salt (64-hex). From env only. */\n salt?: string;\n}\n\n/** Inputs to resolution — kept explicit so it is a pure function (no process.env read inside). */\nexport interface ResolveInput {\n options: AdapterOptions;\n digToml: DigTomlConfig;\n env: Record<string, string | undefined>;\n}\n\n/** A non-empty, trimmed env value, or undefined. Empty/whitespace env vars count as unset. */\nfunction envVal(env: Record<string, string | undefined>, key: string): string | undefined {\n const v = env[key];\n if (v == null) return undefined;\n const t = v.trim();\n return t === \"\" ? undefined : t;\n}\n\n/** First defined of the candidates (treating \"\" the caller already filtered as undefined). */\nfunction pick<T>(...candidates: (T | undefined)[]): T | undefined {\n for (const c of candidates) if (c !== undefined) return c;\n return undefined;\n}\n\n/**\n * Resolve the final deploy config. Precedence per field: options > env (DIGSTORE_*) > dig.toml >\n * default. Secrets (deployKey, salt) are taken from env ONLY.\n */\nexport function resolveDeployConfig(input: ResolveInput): ResolvedDeployConfig {\n const { options, digToml, env } = input;\n\n const storeId = pick(\n options.storeId,\n envVal(env, \"DIGSTORE_STORE_ID\"),\n digToml.storeId,\n );\n const outputDir =\n pick(options.outputDir, envVal(env, \"DIGSTORE_OUTPUT_DIR\"), digToml.outputDir) ?? \"dist\";\n const buildCommand = pick(\n options.buildCommand,\n envVal(env, \"DIGSTORE_BUILD_COMMAND\"),\n digToml.buildCommand,\n );\n const message = pick(options.message, envVal(env, \"DIGSTORE_MESSAGE\"), digToml.message);\n const network =\n pick(options.network, envVal(env, \"DIGSTORE_NETWORK\"), digToml.network) ?? \"mainnet\";\n const remote = pick(options.remote, envVal(env, \"DIGSTORE_REMOTE\"), digToml.remote);\n\n const waitFromEnv = envVal(env, \"DIGSTORE_WAIT_TIMEOUT\");\n const waitTimeout = pick(\n options.waitTimeout,\n waitFromEnv != null ? Number.parseInt(waitFromEnv, 10) : undefined,\n digToml.waitTimeout,\n );\n\n return {\n storeId,\n outputDir,\n buildCommand,\n message,\n network,\n remote,\n waitTimeout: Number.isFinite(waitTimeout) ? waitTimeout : undefined,\n // SECRETS — env only.\n deployKey: envVal(env, \"DIGSTORE_DEPLOY_KEY\"),\n salt: envVal(env, \"DIGSTORE_STORE_SALT\"),\n };\n}\n","// The pure glue around `digstore deploy --json`: build the child argv + env, and parse the result.\n//\n// The adapters SHELL OUT to the installed `digstore` binary (the canonical deployer — it advances\n// the on-chain root, stages the build dir, and pushes the new capsule to DIGHub). They never\n// re-implement deploy. These helpers are the deterministic, side-effect-free pieces:\n//\n// • buildDeployArgs — resolved config → argv (always `deploy --json`, only set flags).\n// • buildDeployEnv — resolved config → the env overlay carrying the SECRETS to the child, so the\n// deploy key / salt are NEVER on the argv (process-table leak), matching\n// digstore-cli's own guidance (deploy.rs).\n// • parseDeployResult— `digstore deploy --json` stdout → { capsule, storeId, root, digUrl, hubUrl,\n// pushed }, deriving the URLs exactly as digstore does (capsule = storeId:root;\n// hub view = https://hub.dig.net/stores/<id>; dig:// names the store).\n\nimport type { ResolvedDeployConfig } from \"./config.js\";\n\n/** Knobs for argv construction. */\nexport interface DeployArgsOptions {\n /**\n * The adapter already ran the framework build, so don't hand `--build-command` to digstore (it\n * would rebuild). The output dir is staged as-is.\n */\n skipBuild?: boolean;\n}\n\n/**\n * Build the argv for `digstore <argv>` from a resolved config. Always `deploy --json`. Only flags\n * whose values are set are emitted. SECRETS (deployKey, salt) are intentionally excluded — they go\n * through the env (buildDeployEnv) so they never appear in the process table.\n */\nexport function buildDeployArgs(\n cfg: ResolvedDeployConfig,\n opts: DeployArgsOptions = {},\n): string[] {\n const argv: string[] = [\"deploy\", \"--json\"];\n if (cfg.storeId) argv.push(\"--store-id\", cfg.storeId);\n if (cfg.outputDir) argv.push(\"--output-dir\", cfg.outputDir);\n if (!opts.skipBuild && cfg.buildCommand) argv.push(\"--build-command\", cfg.buildCommand);\n if (cfg.message) argv.push(\"--message\", cfg.message);\n if (cfg.network) argv.push(\"--network\", cfg.network);\n if (cfg.remote) argv.push(\"--remote\", cfg.remote);\n if (cfg.waitTimeout != null) argv.push(\"--wait-timeout\", String(cfg.waitTimeout));\n return argv;\n}\n\n/**\n * The env overlay to merge onto the child process env: the SECRETS, passed out-of-band so they are\n * never visible on the command line. Returns only the keys that have a value.\n */\nexport function buildDeployEnv(cfg: ResolvedDeployConfig): Record<string, string> {\n const env: Record<string, string> = {};\n if (cfg.deployKey) env.DIGSTORE_DEPLOY_KEY = cfg.deployKey;\n if (cfg.salt) env.DIGSTORE_STORE_SALT = cfg.salt;\n return env;\n}\n\n/** The friendly, parsed outcome of a deploy. */\nexport interface DeployResult {\n /** `storeId:rootHash` — the capsule identity (the ecosystem-vocabulary id the user shares). */\n capsule: string;\n /** Store identity (64-hex). */\n storeId: string;\n /** The new on-chain root (64-hex). */\n root: string;\n /** The dig:// URL naming this store (resolves through the network to the latest version). */\n digUrl: string;\n /** The human \"view it\" URL on DIGHub (the same one `digstore deploy` prints). */\n hubUrl: string;\n /** Whether the capsule was pushed to DIGHub (when the JSON reported it). */\n pushed?: boolean;\n}\n\nconst CAPSULE_RE = /^([0-9a-f]{64}):([0-9a-f]{64})$/i;\n\n/**\n * Parse `digstore deploy --json` stdout into a DeployResult. digstore emits a single JSON object\n * (with at least `capsule` and `root`); we also tolerate extra JSON log lines by scanning lines\n * bottom-up for the first object that carries a `capsule`. Throws a clear error if none is found or\n * the output isn't JSON at all.\n */\nexport function parseDeployResult(stdout: string): DeployResult {\n const lines = stdout\n .split(/\\r?\\n/)\n .map((l) => l.trim())\n .filter((l) => l.startsWith(\"{\") && l.endsWith(\"}\"));\n\n if (lines.length === 0) {\n throw new Error(\n `could not parse digstore deploy output (no JSON object found). Output was:\\n${stdout.slice(0, 500)}`,\n );\n }\n\n // Prefer the LAST JSON object that has a capsule (deploy emits one final result object). Keep the\n // first parseable object as a fallback so the error message can show what digstore DID return.\n let obj: Record<string, unknown> | undefined;\n let fallback: Record<string, unknown> | undefined;\n for (let i = lines.length - 1; i >= 0; i--) {\n const line = lines[i];\n if (line === undefined) continue;\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(line) as Record<string, unknown>;\n } catch {\n continue; // not JSON — skip this line\n }\n if (typeof parsed.capsule === \"string\") {\n obj = parsed;\n break;\n }\n if (!fallback) fallback = parsed;\n }\n\n if (!obj) {\n if (fallback) {\n throw new Error(\n `digstore deploy did not report a capsule (deploy may have failed). Output:\\n${JSON.stringify(fallback)}`,\n );\n }\n throw new Error(`could not parse digstore deploy output as JSON:\\n${stdout.slice(0, 500)}`);\n }\n\n const capsule = obj.capsule as string;\n const m = CAPSULE_RE.exec(capsule);\n if (!m || m[1] === undefined || m[2] === undefined) {\n throw new Error(`digstore deploy reported a malformed capsule \"${capsule}\" (expected storeId:root)`);\n }\n const storeId = m[1].toLowerCase();\n const root = (typeof obj.root === \"string\" ? obj.root : m[2]).toLowerCase();\n\n return {\n capsule,\n storeId,\n root,\n // dig:// names the store on the network (resolves to its latest published version).\n digUrl: `dig://${storeId}`,\n // Mirrors digstore deploy.rs::hub_url — the public DIGHub view of an owned store.\n hubUrl: `https://hub.dig.net/stores/${storeId}`,\n pushed: typeof obj.pushed === \"boolean\" ? obj.pushed : undefined,\n };\n}\n","// Injected-provider transport — the DIG Browser's in-process wallet (and compatible CHIP-0002\n// extensions), exposed on every page as `window.chia`. When present the SDK PREFERS it over\n// WalletConnect: no QR, no relay, no pairing. The native provider returns the SAME response shapes\n// Sage returns over WalletConnect, so the normalizers in provider/methods.ts are unchanged — only\n// the TRANSPORT differs. Genericized from hub.dig.net/apps/web/lib/injected-wallet.js.\n//\n// Detection: we key on the explicit, unspoofable `isDIG` marker the DIG Browser provider sets, not\n// merely the presence of `window.chia` (a different Chia provider could also define that).\n\nimport type { InjectedChiaProvider, WalletBackend } from \"../types.js\";\nimport { WALLET_METHODS, DEFAULT_CHAIN } from \"../methods.js\";\nimport type { WalletTransport } from \"./transport.js\";\n\n/** The injected provider on the current global, or undefined when not running in a DIG Browser. */\nexport function getInjectedProvider(): InjectedChiaProvider | undefined {\n const g = globalThis as { chia?: InjectedChiaProvider };\n return typeof g !== \"undefined\" ? g.chia : undefined;\n}\n\n/**\n * True iff an injected DIG wallet is available. Detects on the unspoofable `isDIG` marker. Pass\n * `{ anyChia: true }` to accept any `window.chia` that implements `request` (e.g. a non-DIG\n * CHIP-0002 extension).\n */\nexport function isInjectedAvailable(opts: { anyChia?: boolean } = {}): boolean {\n const p = getInjectedProvider();\n if (!p) return false;\n if (opts.anyChia) return typeof p.request === \"function\";\n return !!p.isDIG;\n}\n\n/** Sentinel topic for the injected backend (it has no per-session relay topic). */\nexport const INJECTED_TOPIC = \"injected\";\n\n/** A WalletTransport backed by the injected window.chia provider. */\nexport class InjectedTransport implements WalletTransport {\n readonly backend: WalletBackend = \"injected\";\n readonly topic = INJECTED_TOPIC;\n readonly chain: string;\n private readonly provider: InjectedChiaProvider;\n\n constructor(provider: InjectedChiaProvider, chain: string = DEFAULT_CHAIN) {\n this.provider = provider;\n this.chain = chain;\n }\n\n /** Connect: ask the native wallet to approve this origin. Blocks until approved/rejected. */\n async connect(eager = false): Promise<void> {\n if (typeof this.provider.connect === \"function\") {\n await this.provider.connect(eager);\n }\n // A provider without connect() (older build) is tolerated — request() will gate per-method.\n }\n\n // The native wallet implements the full canonical set (it returns Sage-shaped responses), so\n // support is a static allowlist — no per-session negotiation as with WalletConnect.\n supports(method: string): boolean {\n return (WALLET_METHODS as readonly string[]).includes(method);\n }\n\n async request(method: string, params: unknown): Promise<unknown> {\n if (!this.supports(method)) {\n throw new Error(`The DIG Browser wallet does not support \"${method}\".`);\n }\n return this.provider.request({ method, params });\n }\n\n async disconnect(): Promise<void> {\n // The injected wallet has no per-session teardown; per-origin consent is managed in the wallet.\n }\n}\n","// The `window.chia` DEV shim the adapters inject during `dev`.\n//\n// In production a dapp's wallet is the REAL injected provider — the DIG Browser's in-process wallet\n// (or a CHIP-0002 extension) — which the SDK's ChiaProvider detects on `window.chia` via the\n// `isDIG` marker (see src/provider/injected.ts). During local `vite dev` / `next dev` there is no\n// such wallet, so calling `ChiaProvider.connect({ mode: \"injected\" })` would fail and the developer\n// couldn't exercise the wallet path at all.\n//\n// This shim installs a MINIMAL, clearly-labelled stub that satisfies the SAME injected-provider\n// contract the SDK detects (`isDIG`, `request({method,params})`, `connect()`), so the wallet code\n// path runs end-to-end in dev. It is a STUB, not a wallet: it returns a configurable mock address\n// and otherwise throws on methods that would need real signing, so a developer is never misled into\n// thinking a signature is real. It is generated as a self-contained, eval-free `<script>` body\n// (CSP-safe) that GUARDS on an existing `window.chia`, so a real wallet always wins.\n//\n// The shim's method names + response envelope mirror src/provider/injected.ts and\n// src/provider/methods.ts (the native provider returns `{ data }`), so the SAME normalizers run in\n// dev as in production — only the values are mocked.\n\nimport { INJECTED_TOPIC } from \"../provider/injected.js\";\n\n/** A literal substring stamped into the shim so it is unmistakably a dev stub (asserted in tests). */\nexport const DEV_SHIM_MARKER = \"dig-sdk:dev-wallet-shim\";\n\n/** Options for the generated dev shim. */\nexport interface DevShimOptions {\n /** Mock receive address the shim returns from `getAddress`. A clearly-fake default is used. */\n address?: string;\n}\n\n/** A clearly-fake default dev address (so it is obvious in the UI this is not a real wallet). */\nconst DEFAULT_DEV_ADDRESS = \"xch1dev0000000000000000000000000000000000000000000000000000devshim\";\n\n/** JSON-encode a string for safe inlining into a script literal. */\nfunction lit(s: string): string {\n return JSON.stringify(s);\n}\n\n/**\n * Generate the dev-shim `<script>` body (no surrounding `<script>` tags). Inline it into the dev\n * server's served HTML. It is an IIFE that installs `window.chia` ONLY if one is not already\n * present, so the DIG Browser / a real extension always takes precedence. Eval-free and\n * dependency-free — safe under a strict CSP.\n */\nexport function devShimScript(options: DevShimOptions = {}): string {\n const address = options.address ?? DEFAULT_DEV_ADDRESS;\n // The shim mirrors the injected-provider contract the SDK detects. `request` resolves a small set\n // of read methods with mock data and rejects signing methods (a dev stub must not fake a\n // signature). Method names are the bare CHIP-0002 names the SDK normalizes.\n return [\n `/* ${DEV_SHIM_MARKER} — DEV ONLY. A stub wallet for local development; NOT a real wallet. */`,\n `(function () {`,\n ` \"use strict\";`,\n ` if (typeof window === \"undefined\") return;`,\n ` // A real injected wallet (DIG Browser / extension) always wins — never clobber it.`,\n ` if (window.chia) return;`,\n ` var DEV_ADDRESS = ${lit(address)};`,\n ` var TOPIC = ${lit(INJECTED_TOPIC)};`,\n ` function ok(data) { return Promise.resolve({ data: data }); }`,\n ` function nope(method) {`,\n ` return Promise.reject(new Error(`,\n ` \"[\" + ${lit(DEV_SHIM_MARKER)} + \"] '\" + method + \"' needs a real wallet; the dev shim does not sign. \" +`,\n ` \"Open in the DIG Browser or connect a wallet to sign for real.\"));`,\n ` }`,\n ` window.chia = {`,\n ` isDIG: true, // detected by the SDK's injected-provider check`,\n ` isDevShim: true, // so the app can tell it is the dev stub`,\n ` topic: TOPIC,`,\n ` connect: function () { return Promise.resolve(true); },`,\n ` request: function (args) {`,\n ` var method = args && args.method ? String(args.method) : \"\";`,\n ` switch (method) {`,\n ` case \"chip0002_connect\": return ok(true);`,\n ` case \"chip0002_getPublicKeys\": return ok([]);`,\n ` case \"getAddress\":`,\n ` case \"chia_getAddress\": return ok(DEV_ADDRESS);`,\n ` default:`,\n ` // Signing / spend methods must not be faked.`,\n ` return nope(method);`,\n ` }`,\n ` },`,\n ` on: function () {},`,\n ` off: function () {},`,\n ` };`,\n ` if (window.console && window.console.info) {`,\n ` window.console.info(\"[\" + ${lit(DEV_SHIM_MARKER)} + \"] installed a DEV window.chia (mock address \" + DEV_ADDRESS + \").\");`,\n ` }`,\n `})();`,\n ].join(\"\\n\");\n}\n","// The shared, Node-only deploy runner both framework adapters call on their `publish` step.\n//\n// It composes the pure pieces (load dig.toml → resolve config → build argv + env), spawns the\n// installed `digstore` binary with `deploy --json`, and parses the result into a friendly\n// DeployResult ({ capsule, digUrl, hubUrl }). It is intentionally thin: ALL deploy logic lives in\n// `digstore deploy` (the canonical deployer — advances the on-chain root, stages, pushes the\n// capsule); this only marshals config in and the result out.\n//\n// Node-only: it uses node:child_process / node:fs. The framework entrypoints import it lazily on\n// the publish path so importing the plugin in a browser/config context never pulls Node APIs.\n\nimport { resolveDeployConfig, type AdapterOptions } from \"./config.js\";\nimport { parseDigToml, type DigTomlConfig } from \"./dig-toml.js\";\nimport {\n buildDeployArgs,\n buildDeployEnv,\n parseDeployResult,\n type DeployArgsOptions,\n type DeployResult,\n} from \"./deploy.js\";\n\n/** Options for {@link runDeploy}. */\nexport interface RunDeployOptions extends AdapterOptions, DeployArgsOptions {\n /** Project root that holds `dig.toml` and the build output. Defaults to `process.cwd()`. */\n cwd?: string;\n /** The `digstore` executable. Defaults to `\"digstore\"` (must be on PATH). */\n digstoreBin?: string;\n /** Sink for human-readable progress. Defaults to `console.log`. */\n logger?: (line: string) => void;\n}\n\n/** Read `dig.toml` from `cwd` (returns {} when absent). */\nasync function readDigToml(cwd: string): Promise<DigTomlConfig> {\n const { readFile } = await import(\"node:fs/promises\");\n const path = await import(\"node:path\");\n try {\n const text = await readFile(path.join(cwd, \"dig.toml\"), \"utf8\");\n return parseDigToml(text);\n } catch {\n return {}; // no dig.toml — rely on options + env\n }\n}\n\n/**\n * Resolve config, run `digstore deploy --json`, and parse the capsule. Spawns `digstore` with the\n * SECRETS injected through the child env (never the argv). Rejects with digstore's stderr on\n * non-zero exit. Returns the parsed {@link DeployResult}.\n */\nexport async function runDeploy(options: RunDeployOptions = {}): Promise<DeployResult> {\n const cwd = options.cwd ?? process.cwd();\n const bin = options.digstoreBin ?? \"digstore\";\n const log = options.logger ?? ((l: string) => console.log(l));\n\n const digToml = await readDigToml(cwd);\n const cfg = resolveDeployConfig({\n options: {\n storeId: options.storeId,\n outputDir: options.outputDir,\n buildCommand: options.buildCommand,\n message: options.message,\n network: options.network,\n remote: options.remote,\n waitTimeout: options.waitTimeout,\n },\n digToml,\n env: process.env,\n });\n\n const argv = buildDeployArgs(cfg, { skipBuild: options.skipBuild });\n const childEnv = { ...process.env, ...buildDeployEnv(cfg) };\n\n log(`▶ digstore ${argv.filter((a) => a !== cfg.deployKey && a !== cfg.salt).join(\" \")}`);\n\n const { spawn } = await import(\"node:child_process\");\n const stdout = await new Promise<string>((resolve, reject) => {\n const child = spawn(bin, argv, {\n cwd,\n env: childEnv,\n // digstore reads no stdin here; capture stdout (the JSON) and stream stderr through.\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n shell: false,\n });\n let out = \"\";\n let err = \"\";\n child.stdout.on(\"data\", (d: Buffer) => {\n out += d.toString();\n });\n child.stderr.on(\"data\", (d: Buffer) => {\n err += d.toString();\n });\n child.on(\"error\", (e: Error) => {\n reject(\n new Error(\n `could not run \"${bin}\" — is digstore installed and on PATH? (${e.message})`,\n ),\n );\n });\n child.on(\"close\", (code: number | null) => {\n if (code === 0) resolve(out);\n else reject(new Error(`digstore deploy failed (exit ${code}).\\n${err || out}`));\n });\n });\n\n const result = parseDeployResult(stdout);\n log(`✓ deployed capsule ${result.capsule}`);\n log(` dig:// ${result.digUrl}`);\n log(` view ${result.hubUrl}`);\n return result;\n}\n"]}
1
+ {"version":3,"sources":["../src/adapters/dig-toml.ts","../src/adapters/config.ts","../src/errors.ts","../src/adapters/deploy.ts","../src/provider/injected.ts","../src/adapters/dev-shim.ts","../src/adapters/run.ts"],"names":[],"mappings":";AA0BA,IAAM,OAAA,GAA+C;AAAA,EACnD,QAAA,EAAU,SAAA;AAA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AAEzB,QAAA,MAAA;AAAA,UACE,IAAI,WAAA,CAAY,eAAA,EAAiB,CAAA,6BAAA,EAAgC,IAAI,CAAA;AAAA,EAAO,GAAA,IAAO,GAAG,CAAA,CAAA,EAAI;AAAA,YACxF,QAAA,EAAU,IAAA;AAAA,YACV,MAAA,EAAQ,GAAA,CAAI,KAAA,CAAM,CAAA,EAAG,GAAI;AAAA,WAC1B;AAAA,SACH;AAAA,IACJ,CAAC,CAAA;AAAA,EACH,CAAC,CAAA;AAED,EAAA,MAAM,MAAA,GAAS,kBAAkB,MAAM,CAAA;AACvC,EAAA,GAAA,CAAI,CAAA,wBAAA,EAAsB,MAAA,CAAO,OAAO,CAAA,CAAE,CAAA;AAE1C,EAAA,GAAA,CAAI,CAAA,UAAA,EAAa,MAAA,CAAO,OAAO,CAAA,CAAE,CAAA;AACjC,EAAA,GAAA,CAAI,CAAA,UAAA,EAAa,MAAA,CAAO,MAAM,CAAA,CAAE,CAAA;AAChC,EAAA,OAAO,MAAA;AACT","file":"adapters.js","sourcesContent":["// Minimal `dig.toml` reader for the framework adapters.\n//\n// `digstore deploy` reads its config from a project's `dig.toml` (digstore-cli/src/dig_toml.rs).\n// The adapters need the SAME few top-level keys so a project's `dig.toml` is the single source of\n// truth across the CLI and the plugins. Rather than pull in a TOML parser dependency for ~7 flat\n// `key = \"value\"` lines, we parse just those keys ourselves. We accept BOTH the canonical\n// kebab-case key and the snake_case alias, exactly like digstore's `#[serde(rename/alias)]`.\n//\n// Anything beyond these keys (tables, arrays, nested values) is intentionally ignored — the\n// adapters only forward the deploy-relevant scalars to `digstore deploy`, which re-reads the full\n// file authoritatively.\n\n/** The deploy-relevant subset of `dig.toml`, in the adapters' camelCase shape. */\nexport interface DigTomlConfig {\n storeId?: string;\n outputDir?: string;\n buildCommand?: string;\n message?: string;\n network?: string;\n remote?: string;\n waitTimeout?: number;\n}\n\n// Map each canonical/alias TOML key onto the camelCase field. kebab-case is canonical (it is what\n// `digstore new` writes); snake_case is the tolerated alias. When both appear, the canonical\n// kebab-case key wins (it is applied last).\nconst KEY_MAP: Record<string, keyof DigTomlConfig> = {\n store_id: \"storeId\",\n \"store-id\": \"storeId\",\n output_dir: \"outputDir\",\n \"output-dir\": \"outputDir\",\n build_command: \"buildCommand\",\n \"build-command\": \"buildCommand\",\n message: \"message\",\n network: \"network\",\n remote: \"remote\",\n wait_timeout: \"waitTimeout\",\n \"wait-timeout\": \"waitTimeout\",\n};\n\n// Apply snake_case first then kebab-case so the canonical kebab form overrides the alias.\nconst APPLY_ORDER = Object.keys(KEY_MAP).sort((a) =>\n a.includes(\"-\") ? 1 : -1,\n);\n\n/** Strip a `# comment` that is not inside a quoted value. */\nfunction stripComment(line: string): string {\n let inSingle = false;\n let inDouble = false;\n for (let i = 0; i < line.length; i++) {\n const ch = line[i];\n if (ch === \"'\" && !inDouble) inSingle = !inSingle;\n else if (ch === '\"' && !inSingle) inDouble = !inDouble;\n else if (ch === \"#\" && !inSingle && !inDouble) return line.slice(0, i);\n }\n return line;\n}\n\n/** Unquote a TOML scalar: `\"x\"` / `'x'` → `x`; a bare token is returned trimmed. */\nfunction unquote(raw: string): string {\n const v = raw.trim();\n if (\n (v.startsWith('\"') && v.endsWith('\"') && v.length >= 2) ||\n (v.startsWith(\"'\") && v.endsWith(\"'\") && v.length >= 2)\n ) {\n return v.slice(1, -1);\n }\n return v;\n}\n\n/**\n * Parse the deploy-relevant keys out of a `dig.toml` string. Unknown keys, tables, and nested\n * structures are ignored. Returns only the keys actually present (so it composes cleanly under the\n * precedence rules in resolveDeployConfig).\n */\nexport function parseDigToml(text: string): DigTomlConfig {\n // Collect raw (canonical-or-alias) string values keyed by the TOML key as written.\n const raw: Record<string, string> = {};\n for (const lineRaw of text.split(/\\r?\\n/)) {\n const line = stripComment(lineRaw).trim();\n if (!line || line.startsWith(\"[\")) continue; // skip blanks + table headers\n const eq = line.indexOf(\"=\");\n if (eq <= 0) continue;\n const key = line.slice(0, eq).trim();\n if (!(key in KEY_MAP)) continue;\n raw[key] = unquote(line.slice(eq + 1));\n }\n\n const out: DigTomlConfig = {};\n for (const key of APPLY_ORDER) {\n const value = raw[key];\n const field = KEY_MAP[key];\n if (value === undefined || field === undefined) continue;\n if (field === \"waitTimeout\") {\n const n = Number.parseInt(value, 10);\n if (Number.isFinite(n)) out.waitTimeout = n;\n } else {\n out[field] = value;\n }\n }\n return out;\n}\n","// Deploy-config resolution for the framework adapters.\n//\n// The final config a deploy runs with is composed from three layers, highest precedence first:\n// 1. plugin options — what the developer wrote in vite.config / the Next adapter call\n// 2. environment vars — what CI injects (DIGSTORE_*), incl. the SECRETS (deploy key, salt)\n// 3. dig.toml — the project's checked-in defaults\n// 4. built-in defaults — outputDir=\"dist\", network=\"mainnet\" (mirrors deploy.rs::resolve_config)\n//\n// This mirrors `digstore deploy`'s own resolution order (flag/env > dig.toml > default) so the\n// adapters never disagree with the CLI about what a project deploys. SECRETS are resolved ONLY from\n// env — never from options or dig.toml — so they can't end up checked into a repo or a config file.\n\nimport type { DigTomlConfig } from \"./dig-toml.js\";\n\n/** Per-call options a developer passes to the Vite plugin / Next adapter. */\nexport interface AdapterOptions {\n /** On-chain store id (64-hex) to advance. Usually set in dig.toml instead. */\n storeId?: string;\n /** Built-output directory to publish. Defaults to the framework's output (or \"dist\"). */\n outputDir?: string;\n /** Shell build command for `digstore` to run. Omit when the adapter builds itself. */\n buildCommand?: string;\n /** Commit message for the new capsule. */\n message?: string;\n /** Chain network. Defaults to \"mainnet\". */\n network?: string;\n /** The `origin` remote to publish to (e.g. `dig://<storeId>`). */\n remote?: string;\n /** Seconds to wait for on-chain confirmation. */\n waitTimeout?: number;\n}\n\n/** The fully resolved config a deploy runs with. Secrets are present only if env supplied them. */\nexport interface ResolvedDeployConfig {\n storeId?: string;\n outputDir: string;\n buildCommand?: string;\n message?: string;\n network: string;\n remote?: string;\n waitTimeout?: number;\n /** Publisher deploy key (64-hex). From env only. */\n deployKey?: string;\n /** Private-store secret salt (64-hex). From env only. */\n salt?: string;\n}\n\n/** Inputs to resolution — kept explicit so it is a pure function (no process.env read inside). */\nexport interface ResolveInput {\n options: AdapterOptions;\n digToml: DigTomlConfig;\n env: Record<string, string | undefined>;\n}\n\n/** A non-empty, trimmed env value, or undefined. Empty/whitespace env vars count as unset. */\nfunction envVal(env: Record<string, string | undefined>, key: string): string | undefined {\n const v = env[key];\n if (v == null) return undefined;\n const t = v.trim();\n return t === \"\" ? undefined : t;\n}\n\n/** First defined of the candidates (treating \"\" the caller already filtered as undefined). */\nfunction pick<T>(...candidates: (T | undefined)[]): T | undefined {\n for (const c of candidates) if (c !== undefined) return c;\n return undefined;\n}\n\n/**\n * Resolve the final deploy config. Precedence per field: options > env (DIGSTORE_*) > dig.toml >\n * default. Secrets (deployKey, salt) are taken from env ONLY.\n */\nexport function resolveDeployConfig(input: ResolveInput): ResolvedDeployConfig {\n const { options, digToml, env } = input;\n\n const storeId = pick(\n options.storeId,\n envVal(env, \"DIGSTORE_STORE_ID\"),\n digToml.storeId,\n );\n const outputDir =\n pick(options.outputDir, envVal(env, \"DIGSTORE_OUTPUT_DIR\"), digToml.outputDir) ?? \"dist\";\n const buildCommand = pick(\n options.buildCommand,\n envVal(env, \"DIGSTORE_BUILD_COMMAND\"),\n digToml.buildCommand,\n );\n const message = pick(options.message, envVal(env, \"DIGSTORE_MESSAGE\"), digToml.message);\n const network =\n pick(options.network, envVal(env, \"DIGSTORE_NETWORK\"), digToml.network) ?? \"mainnet\";\n const remote = pick(options.remote, envVal(env, \"DIGSTORE_REMOTE\"), digToml.remote);\n\n const waitFromEnv = envVal(env, \"DIGSTORE_WAIT_TIMEOUT\");\n const waitTimeout = pick(\n options.waitTimeout,\n waitFromEnv != null ? Number.parseInt(waitFromEnv, 10) : undefined,\n digToml.waitTimeout,\n );\n\n return {\n storeId,\n outputDir,\n buildCommand,\n message,\n network,\n remote,\n waitTimeout: Number.isFinite(waitTimeout) ? waitTimeout : undefined,\n // SECRETS — env only.\n deployKey: envVal(env, \"DIGSTORE_DEPLOY_KEY\"),\n salt: envVal(env, \"DIGSTORE_STORE_SALT\"),\n };\n}\n","// The SDK's typed error taxonomy — the machine-readable failure contract.\n//\n// 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","// The pure glue around `digstore deploy --json`: build the child argv + env, and parse the result.\n//\n// The adapters SHELL OUT to the installed `digstore` binary (the canonical deployer — it advances\n// the on-chain root, stages the build dir, and pushes the new capsule to DIGHUb). They never\n// re-implement deploy. These helpers are the deterministic, side-effect-free pieces:\n//\n// • buildDeployArgs — resolved config → argv (always `deploy --json`, only set flags).\n// • buildDeployEnv — resolved config → the env overlay carrying the SECRETS to the child, so the\n// deploy key / salt are NEVER on the argv (process-table leak), matching\n// digstore-cli's own guidance (deploy.rs).\n// • parseDeployResult— `digstore deploy --json` stdout → { capsule, storeId, root, chiaUrl,\n// digUrl, hubUrl, pushed }, deriving the URLs exactly as digstore does\n// (capsule = storeId:root; hub view = https://hub.dig.net/stores/<id>;\n// chiaUrl = the user-facing content-open address chia://<store>:<root>/,\n// matching digstore's printed `content_address`).\n\nimport type { ResolvedDeployConfig } from \"./config.js\";\nimport { DigSdkError } from \"../errors.js\";\n\n/** Knobs for argv construction. */\nexport interface DeployArgsOptions {\n /**\n * The adapter already ran the framework build, so don't hand `--build-command` to digstore (it\n * would rebuild). The output dir is staged as-is.\n */\n skipBuild?: boolean;\n}\n\n/**\n * Build the argv for `digstore <argv>` from a resolved config. Always `deploy --json`. Only flags\n * whose values are set are emitted. SECRETS (deployKey, salt) are intentionally excluded — they go\n * through the env (buildDeployEnv) so they never appear in the process table.\n */\nexport function buildDeployArgs(\n cfg: ResolvedDeployConfig,\n opts: DeployArgsOptions = {},\n): string[] {\n const argv: string[] = [\"deploy\", \"--json\"];\n if (cfg.storeId) argv.push(\"--store-id\", cfg.storeId);\n if (cfg.outputDir) argv.push(\"--output-dir\", cfg.outputDir);\n if (!opts.skipBuild && cfg.buildCommand) argv.push(\"--build-command\", cfg.buildCommand);\n if (cfg.message) argv.push(\"--message\", cfg.message);\n if (cfg.network) argv.push(\"--network\", cfg.network);\n if (cfg.remote) argv.push(\"--remote\", cfg.remote);\n if (cfg.waitTimeout != null) argv.push(\"--wait-timeout\", String(cfg.waitTimeout));\n return argv;\n}\n\n/**\n * The env overlay to merge onto the child process env: the SECRETS, passed out-of-band so they are\n * never visible on the command line. Returns only the keys that have a value.\n */\nexport function buildDeployEnv(cfg: ResolvedDeployConfig): Record<string, string> {\n const env: Record<string, string> = {};\n if (cfg.deployKey) env.DIGSTORE_DEPLOY_KEY = cfg.deployKey;\n if (cfg.salt) env.DIGSTORE_STORE_SALT = cfg.salt;\n return env;\n}\n\n/** The friendly, parsed outcome of a deploy. */\nexport interface DeployResult {\n /** `storeId:rootHash` — the capsule identity (the ecosystem-vocabulary id the user shares). */\n capsule: string;\n /** Store identity (64-hex). */\n storeId: string;\n /** The new on-chain root (64-hex). */\n root: string;\n /**\n * The user-facing content-open address `chia://<storeId>:<rootHash>/` — what a user types/clicks\n * to open this verified capsule in the DIG Browser / extension (the scheme they register). This\n * matches digstore deploy's printed `content_address` exactly. (Distinct from the §21 remote\n * locator `dig://<host>/<store_id>` and the `urn:dig:` namespace, which stay `dig://`.)\n */\n chiaUrl: string;\n /**\n * @deprecated Use {@link chiaUrl}. Kept as a back-compat alias for consumers that read `digUrl`;\n * it now carries the SAME `chia://<storeId>:<rootHash>/` content-open value (NOT a `dig://` URL).\n */\n digUrl: string;\n /** The human \"view it\" URL on DIGHUb (the same one `digstore deploy` prints). */\n hubUrl: string;\n /** Whether the capsule was pushed to DIGHUb (when the JSON reported it). */\n pushed?: boolean;\n}\n\nconst CAPSULE_RE = /^([0-9a-f]{64}):([0-9a-f]{64})$/i;\n\n/**\n * Parse `digstore deploy --json` stdout into a DeployResult. digstore emits a single JSON object\n * (with at least `capsule` and `root`); we also tolerate extra JSON log lines by scanning lines\n * bottom-up for the first object that carries a `capsule`. Throws a clear error if none is found or\n * the output isn't JSON at all.\n */\nexport function parseDeployResult(stdout: string): DeployResult {\n const lines = stdout\n .split(/\\r?\\n/)\n .map((l) => l.trim())\n .filter((l) => l.startsWith(\"{\") && l.endsWith(\"}\"));\n\n if (lines.length === 0) {\n throw new DigSdkError(\n \"DEPLOY_OUTPUT_UNPARSEABLE\",\n `could not parse digstore deploy output (no JSON object found). Output was:\\n${stdout.slice(0, 500)}`,\n { stdout: stdout.slice(0, 500) },\n );\n }\n\n // Prefer the LAST JSON object that has a capsule (deploy emits one final result object). Keep the\n // first parseable object as a fallback so the error message can show what digstore DID return.\n let obj: Record<string, unknown> | undefined;\n let fallback: Record<string, unknown> | undefined;\n for (let i = lines.length - 1; i >= 0; i--) {\n const line = lines[i];\n if (line === undefined) continue;\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(line) as Record<string, unknown>;\n } catch {\n continue; // not JSON — skip this line\n }\n if (typeof parsed.capsule === \"string\") {\n obj = parsed;\n break;\n }\n if (!fallback) fallback = parsed;\n }\n\n if (!obj) {\n if (fallback) {\n throw new DigSdkError(\n \"DEPLOY_OUTPUT_UNPARSEABLE\",\n `digstore deploy did not report a capsule (deploy may have failed). Output:\\n${JSON.stringify(fallback)}`,\n { output: fallback },\n );\n }\n throw new DigSdkError(\n \"DEPLOY_OUTPUT_UNPARSEABLE\",\n `could not parse digstore deploy output as JSON:\\n${stdout.slice(0, 500)}`,\n { stdout: stdout.slice(0, 500) },\n );\n }\n\n const capsule = obj.capsule as string;\n const m = CAPSULE_RE.exec(capsule);\n if (!m || m[1] === undefined || m[2] === undefined) {\n throw new DigSdkError(\n \"INVALID_ARGUMENT\",\n `digstore deploy reported a malformed capsule \"${capsule}\" (expected storeId:root)`,\n { value: capsule, expected: \"storeId:root\" },\n );\n }\n const storeId = m[1].toLowerCase();\n const root = (typeof obj.root === \"string\" ? obj.root : m[2]).toLowerCase();\n\n // The user-facing content-open address. Prefer the value digstore itself printed\n // (`content_address`, the single source of truth — digstore deploy.rs::branding::content_url) so\n // the SDK stays byte-identical to the CLI; otherwise derive it the same way digstore does:\n // chia://<storeId>:<rootHash>/ (trailing slash, no resource). This is what a user opens in the\n // DIG Browser/extension — NOT the §21 remote dig:// locator.\n const chiaUrl =\n typeof obj.content_address === \"string\"\n ? obj.content_address\n : `chia://${storeId}:${root}/`;\n\n return {\n capsule,\n storeId,\n root,\n chiaUrl,\n // Deprecated alias: same chia:// content-open value (back-compat for consumers reading digUrl).\n digUrl: chiaUrl,\n // Mirrors digstore deploy.rs::hub_url — the public DIGHUb view of an owned store.\n hubUrl: `https://hub.dig.net/stores/${storeId}`,\n pushed: typeof obj.pushed === \"boolean\" ? obj.pushed : undefined,\n };\n}\n","// Injected-provider transport — the DIG Browser's in-process wallet (and compatible CHIP-0002\n// extensions), exposed on every page as `window.chia`. When present the SDK PREFERS it over\n// WalletConnect: no QR, no relay, no pairing. The native provider returns the SAME response shapes\n// Sage returns over WalletConnect, so the normalizers in provider/methods.ts are unchanged — only\n// the TRANSPORT differs. Genericized from hub.dig.net/apps/web/lib/injected-wallet.js.\n//\n// Detection: we key on the explicit, unspoofable `isDIG` marker the DIG Browser provider sets, not\n// merely the presence of `window.chia` (a different Chia provider could also define that).\n\nimport type { InjectedChiaProvider, WalletBackend } from \"../types.js\";\nimport { WALLET_METHODS, DEFAULT_CHAIN } from \"../methods.js\";\nimport type { WalletTransport } from \"./transport.js\";\nimport { DigSdkError } from \"../errors.js\";\n\n/** The injected provider on the current global, or undefined when not running in a DIG Browser. */\nexport function getInjectedProvider(): InjectedChiaProvider | undefined {\n const g = globalThis as { chia?: InjectedChiaProvider };\n return typeof g !== \"undefined\" ? g.chia : undefined;\n}\n\n/**\n * True iff an injected DIG wallet is available. Detects on the unspoofable `isDIG` marker. Pass\n * `{ anyChia: true }` to accept any `window.chia` that implements `request` (e.g. a non-DIG\n * CHIP-0002 extension).\n */\nexport function isInjectedAvailable(opts: { anyChia?: boolean } = {}): boolean {\n const p = getInjectedProvider();\n if (!p) return false;\n if (opts.anyChia) return typeof p.request === \"function\";\n return !!p.isDIG;\n}\n\n/** Sentinel topic for the injected backend (it has no per-session relay topic). */\nexport const INJECTED_TOPIC = \"injected\";\n\n/** A WalletTransport backed by the injected window.chia provider. */\nexport class InjectedTransport implements WalletTransport {\n readonly backend: WalletBackend = \"injected\";\n readonly topic = INJECTED_TOPIC;\n readonly chain: string;\n private readonly provider: InjectedChiaProvider;\n\n constructor(provider: InjectedChiaProvider, chain: string = DEFAULT_CHAIN) {\n this.provider = provider;\n this.chain = chain;\n }\n\n /** Connect: ask the native wallet to approve this origin. Blocks until approved/rejected. */\n async connect(eager = false): Promise<void> {\n if (typeof this.provider.connect === \"function\") {\n await this.provider.connect(eager);\n }\n // A provider without connect() (older build) is tolerated — request() will gate per-method.\n }\n\n // The native wallet implements the full canonical set (it returns Sage-shaped responses), so\n // support is a static allowlist — no per-session negotiation as with WalletConnect.\n supports(method: string): boolean {\n return (WALLET_METHODS as readonly string[]).includes(method);\n }\n\n async request(method: string, params: unknown): Promise<unknown> {\n if (!this.supports(method)) {\n throw new DigSdkError(\n \"METHOD_NOT_SUPPORTED\",\n `The DIG Browser wallet does not support \"${method}\".`,\n { method },\n );\n }\n return this.provider.request({ method, params });\n }\n\n async disconnect(): Promise<void> {\n // The injected wallet has no per-session teardown; per-origin consent is managed in the wallet.\n }\n}\n","// The `window.chia` DEV shim the adapters inject during `dev`.\n//\n// In production a dapp's wallet is the REAL injected provider — the DIG Browser's in-process wallet\n// (or a CHIP-0002 extension) — which the SDK's ChiaProvider detects on `window.chia` via the\n// `isDIG` marker (see src/provider/injected.ts). During local `vite dev` / `next dev` there is no\n// such wallet, so calling `ChiaProvider.connect({ mode: \"injected\" })` would fail and the developer\n// couldn't exercise the wallet path at all.\n//\n// This shim installs a MINIMAL, clearly-labelled stub that satisfies the SAME injected-provider\n// contract the SDK detects (`isDIG`, `request({method,params})`, `connect()`), so the wallet code\n// path runs end-to-end in dev. It is a STUB, not a wallet: it returns a configurable mock address\n// and otherwise throws on methods that would need real signing, so a developer is never misled into\n// thinking a signature is real. It is generated as a self-contained, eval-free `<script>` body\n// (CSP-safe) that GUARDS on an existing `window.chia`, so a real wallet always wins.\n//\n// The shim's method names + response envelope mirror src/provider/injected.ts and\n// src/provider/methods.ts (the native provider returns `{ data }`), so the SAME normalizers run in\n// dev as in production — only the values are mocked.\n\nimport { INJECTED_TOPIC } from \"../provider/injected.js\";\n\n/** A literal substring stamped into the shim so it is unmistakably a dev stub (asserted in tests). */\nexport const DEV_SHIM_MARKER = \"dig-sdk:dev-wallet-shim\";\n\n/** Options for the generated dev shim. */\nexport interface DevShimOptions {\n /** Mock receive address the shim returns from `getAddress`. A clearly-fake default is used. */\n address?: string;\n}\n\n/** A clearly-fake default dev address (so it is obvious in the UI this is not a real wallet). */\nconst DEFAULT_DEV_ADDRESS = \"xch1dev0000000000000000000000000000000000000000000000000000devshim\";\n\n/** JSON-encode a string for safe inlining into a script literal. */\nfunction lit(s: string): string {\n return JSON.stringify(s);\n}\n\n/**\n * Generate the dev-shim `<script>` body (no surrounding `<script>` tags). Inline it into the dev\n * server's served HTML. It is an IIFE that installs `window.chia` ONLY if one is not already\n * present, so the DIG Browser / a real extension always takes precedence. Eval-free and\n * dependency-free — safe under a strict CSP.\n */\nexport function devShimScript(options: DevShimOptions = {}): string {\n const address = options.address ?? DEFAULT_DEV_ADDRESS;\n // The shim mirrors the injected-provider contract the SDK detects. `request` resolves a small set\n // of read methods with mock data and rejects signing methods (a dev stub must not fake a\n // signature). Method names are the bare CHIP-0002 names the SDK normalizes.\n return [\n `/* ${DEV_SHIM_MARKER} — DEV ONLY. A stub wallet for local development; NOT a real wallet. */`,\n `(function () {`,\n ` \"use strict\";`,\n ` if (typeof window === \"undefined\") return;`,\n ` // A real injected wallet (DIG Browser / extension) always wins — never clobber it.`,\n ` if (window.chia) return;`,\n ` var DEV_ADDRESS = ${lit(address)};`,\n ` var TOPIC = ${lit(INJECTED_TOPIC)};`,\n ` function ok(data) { return Promise.resolve({ data: data }); }`,\n ` function nope(method) {`,\n ` return Promise.reject(new Error(`,\n ` \"[\" + ${lit(DEV_SHIM_MARKER)} + \"] '\" + method + \"' needs a real wallet; the dev shim does not sign. \" +`,\n ` \"Open in the DIG Browser or connect a wallet to sign for real.\"));`,\n ` }`,\n ` window.chia = {`,\n ` isDIG: true, // detected by the SDK's injected-provider check`,\n ` isDevShim: true, // so the app can tell it is the dev stub`,\n ` topic: TOPIC,`,\n ` connect: function () { return Promise.resolve(true); },`,\n ` request: function (args) {`,\n ` var method = args && args.method ? String(args.method) : \"\";`,\n ` switch (method) {`,\n ` case \"chip0002_connect\": return ok(true);`,\n ` case \"chip0002_getPublicKeys\": return ok([]);`,\n ` case \"getAddress\":`,\n ` case \"chia_getAddress\": return ok(DEV_ADDRESS);`,\n ` default:`,\n ` // Signing / spend methods must not be faked.`,\n ` return nope(method);`,\n ` }`,\n ` },`,\n ` on: function () {},`,\n ` off: function () {},`,\n ` };`,\n ` if (window.console && window.console.info) {`,\n ` window.console.info(\"[\" + ${lit(DEV_SHIM_MARKER)} + \"] installed a DEV window.chia (mock address \" + DEV_ADDRESS + \").\");`,\n ` }`,\n `})();`,\n ].join(\"\\n\");\n}\n","// The shared, Node-only deploy runner both framework adapters call on their `publish` step.\n//\n// It composes the pure pieces (load dig.toml → resolve config → build argv + env), spawns the\n// installed `digstore` binary with `deploy --json`, and parses the result into a friendly\n// DeployResult ({ capsule, chiaUrl, hubUrl }). It is intentionally thin: ALL deploy logic lives in\n// `digstore deploy` (the canonical deployer — advances the on-chain root, stages, pushes the\n// capsule); this only marshals config in and the result out.\n//\n// Node-only: it uses node:child_process / node:fs. The framework entrypoints import it lazily on\n// the publish path so importing the plugin in a browser/config context never pulls Node APIs.\n\nimport { resolveDeployConfig, type AdapterOptions } from \"./config.js\";\nimport { parseDigToml, type DigTomlConfig } from \"./dig-toml.js\";\nimport {\n buildDeployArgs,\n buildDeployEnv,\n parseDeployResult,\n type DeployArgsOptions,\n type DeployResult,\n} from \"./deploy.js\";\nimport { DigSdkError } from \"../errors.js\";\n\n/** Options for {@link runDeploy}. */\nexport interface RunDeployOptions extends AdapterOptions, DeployArgsOptions {\n /** Project root that holds `dig.toml` and the build output. Defaults to `process.cwd()`. */\n cwd?: string;\n /** The `digstore` executable. Defaults to `\"digstore\"` (must be on PATH). */\n digstoreBin?: string;\n /** Sink for human-readable progress. Defaults to `console.log`. */\n logger?: (line: string) => void;\n}\n\n/** Read `dig.toml` from `cwd` (returns {} when absent). */\nasync function readDigToml(cwd: string): Promise<DigTomlConfig> {\n const { readFile } = await import(\"node:fs/promises\");\n const path = await import(\"node:path\");\n try {\n const text = await readFile(path.join(cwd, \"dig.toml\"), \"utf8\");\n return parseDigToml(text);\n } catch {\n return {}; // no dig.toml — rely on options + env\n }\n}\n\n/**\n * Resolve config, run `digstore deploy --json`, and parse the capsule. Spawns `digstore` with the\n * SECRETS injected through the child env (never the argv). Rejects with digstore's stderr on\n * non-zero exit. Returns the parsed {@link DeployResult}.\n */\nexport async function runDeploy(options: RunDeployOptions = {}): Promise<DeployResult> {\n const cwd = options.cwd ?? process.cwd();\n const bin = options.digstoreBin ?? \"digstore\";\n const log = options.logger ?? ((l: string) => console.log(l));\n\n const digToml = await readDigToml(cwd);\n const cfg = resolveDeployConfig({\n options: {\n storeId: options.storeId,\n outputDir: options.outputDir,\n buildCommand: options.buildCommand,\n message: options.message,\n network: options.network,\n remote: options.remote,\n waitTimeout: options.waitTimeout,\n },\n digToml,\n env: process.env,\n });\n\n const argv = buildDeployArgs(cfg, { skipBuild: options.skipBuild });\n const childEnv = { ...process.env, ...buildDeployEnv(cfg) };\n\n log(`▶ digstore ${argv.filter((a) => a !== cfg.deployKey && a !== cfg.salt).join(\" \")}`);\n\n const { spawn } = await import(\"node:child_process\");\n const stdout = await new Promise<string>((resolve, reject) => {\n const child = spawn(bin, argv, {\n cwd,\n env: childEnv,\n // digstore reads no stdin here; capture stdout (the JSON) and stream stderr through.\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n shell: false,\n });\n let out = \"\";\n let err = \"\";\n child.stdout.on(\"data\", (d: Buffer) => {\n out += d.toString();\n });\n child.stderr.on(\"data\", (d: Buffer) => {\n err += d.toString();\n });\n child.on(\"error\", (e: Error) => {\n reject(\n new DigSdkError(\n \"DIGSTORE_NOT_FOUND\",\n `could not run \"${bin}\" — is digstore installed and on PATH? (${e.message})`,\n { bin },\n { cause: e },\n ),\n );\n });\n child.on(\"close\", (code: number | null) => {\n if (code === 0) resolve(out);\n else\n reject(\n new DigSdkError(\"DEPLOY_FAILED\", `digstore deploy failed (exit ${code}).\\n${err || out}`, {\n exitCode: code,\n stderr: err.slice(0, 2000),\n }),\n );\n });\n });\n\n const result = parseDeployResult(stdout);\n log(`✓ deployed capsule ${result.capsule}`);\n // chia:// is the user-facing content-open address (what they open in the DIG Browser/extension).\n log(` open ${result.chiaUrl}`);\n log(` view ${result.hubUrl}`);\n return result;\n}\n"]}
@@ -85,11 +85,21 @@ interface DeployResult {
85
85
  storeId: string;
86
86
  /** The new on-chain root (64-hex). */
87
87
  root: string;
88
- /** The dig:// URL naming this store (resolves through the network to the latest version). */
88
+ /**
89
+ * The user-facing content-open address `chia://<storeId>:<rootHash>/` — what a user types/clicks
90
+ * to open this verified capsule in the DIG Browser / extension (the scheme they register). This
91
+ * matches digstore deploy's printed `content_address` exactly. (Distinct from the §21 remote
92
+ * locator `dig://<host>/<store_id>` and the `urn:dig:` namespace, which stay `dig://`.)
93
+ */
94
+ chiaUrl: string;
95
+ /**
96
+ * @deprecated Use {@link chiaUrl}. Kept as a back-compat alias for consumers that read `digUrl`;
97
+ * it now carries the SAME `chia://<storeId>:<rootHash>/` content-open value (NOT a `dig://` URL).
98
+ */
89
99
  digUrl: string;
90
- /** The human "view it" URL on DIGHub (the same one `digstore deploy` prints). */
100
+ /** The human "view it" URL on DIGHUb (the same one `digstore deploy` prints). */
91
101
  hubUrl: string;
92
- /** Whether the capsule was pushed to DIGHub (when the JSON reported it). */
102
+ /** Whether the capsule was pushed to DIGHUb (when the JSON reported it). */
93
103
  pushed?: boolean;
94
104
  }
95
105
  /**
@@ -85,11 +85,21 @@ interface DeployResult {
85
85
  storeId: string;
86
86
  /** The new on-chain root (64-hex). */
87
87
  root: string;
88
- /** The dig:// URL naming this store (resolves through the network to the latest version). */
88
+ /**
89
+ * The user-facing content-open address `chia://<storeId>:<rootHash>/` — what a user types/clicks
90
+ * to open this verified capsule in the DIG Browser / extension (the scheme they register). This
91
+ * matches digstore deploy's printed `content_address` exactly. (Distinct from the §21 remote
92
+ * locator `dig://<host>/<store_id>` and the `urn:dig:` namespace, which stay `dig://`.)
93
+ */
94
+ chiaUrl: string;
95
+ /**
96
+ * @deprecated Use {@link chiaUrl}. Kept as a back-compat alias for consumers that read `digUrl`;
97
+ * it now carries the SAME `chia://<storeId>:<rootHash>/` content-open value (NOT a `dig://` URL).
98
+ */
89
99
  digUrl: string;
90
- /** The human "view it" URL on DIGHub (the same one `digstore deploy` prints). */
100
+ /** The human "view it" URL on DIGHUb (the same one `digstore deploy` prints). */
91
101
  hubUrl: string;
92
- /** Whether the capsule was pushed to DIGHub (when the JSON reported it). */
102
+ /** Whether the capsule was pushed to DIGHUb (when the JSON reported it). */
93
103
  pushed?: boolean;
94
104
  }
95
105
  /**
@@ -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 };