@tokenoftrust/cli 6.14.5 → 6.15.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/bin/tot.mjs CHANGED
@@ -85,6 +85,11 @@ const COMMANDS = [
85
85
  { invocation: "app replay <deliveryId>", blurb: "re-send a webhook delivery to its install" },
86
86
  { invocation: "app test-order bind <installId> | create | release <orderId>", blurb: "synthetic preview orders bound to your test install (preview host)" },
87
87
  { invocation: "app candidate", blurb: "stage a production candidate (pending_approval) for owner approval" },
88
+ { invocation: "app candidate status", blurb: "your store's candidates and their status" },
89
+ { invocation: "app suspend <installId>", blurb: "disable an install's tokens, webhooks and widgets (reversible)" },
90
+ { invocation: "app resume <installId>", blurb: "bring a suspended install back to active" },
91
+ { invocation: "app uninstall <installId>", blurb: "revoke an install's credentials and clear its placements" },
92
+ { invocation: "app validate [<manifest>]", blurb: "lint tot-app.json offline (invalid_manifest on refusal)" },
88
93
  { invocation: "catalog seed --preset=<name>", blurb: "seed your store checkout with synthetic products (general, regulated-vape, multi-warehouse)" },
89
94
  { invocation: "help", blurb: "show this help" },
90
95
  { invocation: "--version", blurb: "print the CLI version" },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/cli",
3
- "version": "6.14.5",
3
+ "version": "6.15.0",
4
4
  "description": "Token of Trust developer CLI — clone a tenant store, run it locally with save→reload, and submit it for preview. Installs the `tot` command.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Token of Trust",
@@ -5,10 +5,13 @@
5
5
  * network — a developer building a Storefront Private App gets a runnable
6
6
  * skeleton before they've registered anything with Token of Trust.
7
7
  *
8
- * The scaffolded tree also gets its own copy of `src/vendor/private-apps-devkit.mjs`
9
- * (as `lib/private-apps-devkit.mjs`) so the stub `server.js` can verify webhook
10
- * signatures with zero runtime dependencies — see that file's module doc for
11
- * why this is a vendored copy rather than a package.json dependency.
8
+ * The scaffolded tree gets two vendored copies, neither a package.json dependency:
9
+ * - `vendor/connector-kit/` — the Devkit's connector-kit source (auth, RFC 9421
10
+ * webhook verification, idempotent API client), pinned to a Devkit commit by
11
+ * `src/vendor/connector-kit/PIN.json`. It ships inside this package so
12
+ * scaffolding stays offline and a given CLI version always emits the same
13
+ * reviewed bytes; `scripts/vendor-connector-kit.mjs` refreshes it.
14
+ * - `lib/private-apps-devkit.mjs` — the dev-only signer the template's tests use.
12
15
  */
13
16
  import { cpSync, existsSync, mkdirSync, readdirSync } from "node:fs";
14
17
  import { fileURLToPath } from "node:url";
@@ -26,6 +29,11 @@ export function vendoredDevkitPath() {
26
29
  return resolve(here, "vendor", "private-apps-devkit.mjs");
27
30
  }
28
31
 
32
+ /** Absolute path to the vendored connector-kit source (with its PIN.json) copied into every scaffolded app. */
33
+ export function vendoredConnectorKitDir() {
34
+ return resolve(here, "vendor", "connector-kit");
35
+ }
36
+
29
37
  /** A directory carries a scaffolded app if it has a `tot-app.json` manifest. */
30
38
  export function isAppScaffold(dir) {
31
39
  return existsSync(join(dir, "tot-app.json"));
@@ -44,7 +52,7 @@ function isEmptyDir(dir) {
44
52
  /**
45
53
  * Materialize a Private App skeleton at `destDir`: copy the bundled template
46
54
  * (`tot-app.json`, `fixtures/`, `README.md`, `Dockerfile`, `.env.example`,
47
- * `server.js`) in, then drop this package's vendored devkit at `lib/`.
55
+ * `server.js`, `connector.js`, `test/`) in, then drop this package's vendored devkit at `lib/`.
48
56
  * Idempotent — re-running against an already-scaffolded directory is a no-op
49
57
  * that returns it. Refuses to clobber a non-scaffold, non-empty directory.
50
58
  *
@@ -78,6 +86,7 @@ export function scaffoldApp(destDir, { force = false, log = () => {} } = {}) {
78
86
  cpSync(template, dir, { recursive: true });
79
87
  mkdirSync(join(dir, "lib"), { recursive: true });
80
88
  cpSync(vendoredDevkitPath(), join(dir, "lib", "private-apps-devkit.mjs"));
89
+ cpSync(vendoredConnectorKitDir(), join(dir, "vendor", "connector-kit"), { recursive: true });
81
90
 
82
91
  log(` ✓ scaffolded a private app → ${dir}`);
83
92
  return { dir, created: true };
@@ -23,7 +23,7 @@ import { missingGrantsOf, refusalHint } from "../../admission-hint.mjs";
23
23
  import { validateManifest } from "../../vendor/private-apps-devkit.mjs";
24
24
 
25
25
  export const DEFAULT_APP_ENV = "test";
26
- const OPTION_VERBS = new Set(["install", "update", "rotate", "list", "replay", "test-order", "candidate"]);
26
+ const OPTION_VERBS = new Set(["install", "update", "rotate", "list", "replay", "test-order", "candidate", "suspend", "resume", "uninstall", "validate"]);
27
27
 
28
28
  export const ADMIN_USAGE = `tot app — manage Private App installs on your store
29
29
 
@@ -31,6 +31,10 @@ export const ADMIN_USAGE = `tot app — manage Private App installs on your stor
31
31
  install the app in <dir> (reads its tot-app.json); prints the client secret ONCE
32
32
  tot app update <installId> [--app <dir>] [--webhook-endpoint <url|none>]
33
33
  push the app's current version, scopes, manifest and widgets to an install
34
+ tot app suspend <installId> disable an install's tokens, webhooks and widgets (reversible)
35
+ tot app resume <installId> bring a suspended install back to active
36
+ tot app uninstall <installId> revoke an install's credentials and clear its placements (the audit trail stays)
37
+ tot app validate [<manifest>] lint tot-app.json offline; a refused manifest is reported as invalid_manifest
34
38
  tot app rotate <installId> issue a new client secret (printed ONCE); the old one stops working
35
39
  tot app list your store's installs: id, app, version, env, status, scopes (never secrets)
36
40
  tot app replay <deliveryId> re-send a webhook delivery to its install
@@ -41,6 +45,7 @@ export const ADMIN_USAGE = `tot app — manage Private App installs on your stor
41
45
  claim and release one synthetic preview order
42
46
  (test orders always act on the store's preview stage, at
43
47
  ${DEFAULT_STOREFRONT_ORIGIN}/<tenant>; no --url needed)
48
+ tot app candidate status this store's candidates: id, app, version, status
44
49
  tot app candidate [--app <dir>] [--jwks-uri <url> | --jwks <file>] [--request-consent] [--webhook-endpoint <url>]
45
50
  stage a production candidate (pending_approval) for owner approval;
46
51
  keys come from --jwks-uri, --jwks, or the manifest's clientAuth
@@ -90,6 +95,16 @@ export function parseAdminArgs(argv) {
90
95
  return a;
91
96
  }
92
97
 
98
+ /** Plain wording for the ownership and entitlement refusals; null when neither applies. */
99
+ function plainRefusal(status, body) {
100
+ const code = typeof body?.code === "string" ? body.code : "";
101
+ if (code === "not_found" && status === 404) return "not_owner: that install is not on this store";
102
+ if (code === "owner_required_for_production_app" || (status === 403 && missingGrantsOf(body).length)) {
103
+ return "not_entitled: your sign-in is not allowed to do this on this store";
104
+ }
105
+ return null;
106
+ }
107
+
93
108
  /**
94
109
  * The next step for a refused call: the server's `code` first, then the generic admission hint.
95
110
  * @param {number} status @param {any} body @param {{ tenant: string, urlOverridden: boolean }} target
@@ -134,6 +149,8 @@ export async function runAdmin(argv, ctx, deps = {}) {
134
149
  if (args.unknown.length) return fail(`unknown option ${args.unknown[0]}`, "tot app --help");
135
150
  const verb = args.verb;
136
151
 
152
+ if (verb === "validate") return runValidateManifest(args, ctx, out, err);
153
+
137
154
  // ── build the request from local files and arguments, before any network call ──
138
155
  /** @type {{ method: string, path: string, body?: unknown }} */
139
156
  let request;
@@ -188,6 +205,12 @@ export async function runAdmin(argv, ctx, deps = {}) {
188
205
  method: "POST", path: "/api/apps/admin/test-orders",
189
206
  body: action === "bind" ? { action, installId: id } : action === "release" ? { action, orderId: id } : { action },
190
207
  };
208
+ } else if (verb === "suspend" || verb === "resume" || verb === "uninstall") {
209
+ const installId = args.positional[0];
210
+ if (!installId) return fail(`no install to ${verb}`, `tot app ${verb} <installId> (find it with \`tot app list\`)`);
211
+ request = { method: "POST", path: `/api/apps/admin/${verb}`, body: { installId } };
212
+ } else if (verb === "candidate" && args.positional[0] === "status") {
213
+ request = { method: "GET", path: "/api/apps/admin/candidates" };
191
214
  } else if (verb === "candidate") {
192
215
  const loaded = loadManifest(args.app, ctx);
193
216
  if (!loaded.ok) return fail(loaded.message, loaded.next);
@@ -248,7 +271,7 @@ export async function runAdmin(argv, ctx, deps = {}) {
248
271
  ? `\n refused scopes: ${data.denials.map((d) => d?.scope ?? d?.id ?? JSON.stringify(d)).join(", ")}` : "";
249
272
  const storefrontUrl = String(args.url || env.TOT_STOREFRONT_URL || "").trim().replace(/\/+$/, "");
250
273
  const urlOverridden = storefrontUrl !== "" && storefrontUrl !== DEFAULT_STOREFRONT_ORIGIN;
251
- err(`✗ tot app ${verb}: ${reason}${denials}\n\n → next: ${nextForRefusal(res.status, data, { tenant, urlOverridden })}`);
274
+ err(`✗ tot app ${verb}: ${plainRefusal(res.status, data) ? `${plainRefusal(res.status, data)} (${reason})` : reason}${denials}\n\n → next: ${nextForRefusal(res.status, data, { tenant, urlOverridden })}`);
252
275
  return res.status === 401 || res.status === 403 ? 1 : (res.status >= 500 ? 1 : 2);
253
276
  }
254
277
 
@@ -260,6 +283,16 @@ export async function runAdmin(argv, ctx, deps = {}) {
260
283
  return 0;
261
284
  }
262
285
  if (verb === "test-order") return renderTestOrder(data, args, out);
286
+ if (verb === "suspend" || verb === "resume" || verb === "uninstall") {
287
+ if (args.json) out(JSON.stringify(data));
288
+ else {
289
+ const i = data?.install;
290
+ const done = verb === "uninstall" ? "uninstalled" : verb === "suspend" ? "suspended" : "resumed";
291
+ out(`✓ ${done} ${i?.installId ?? args.positional[0]} (${i?.appId ?? "app"}, status ${i?.status ?? ""})`);
292
+ }
293
+ return 0;
294
+ }
295
+ if (verb === "candidate" && args.positional[0] === "status") return renderCandidates(data, args.json, out);
263
296
  if (verb === "candidate") {
264
297
  if (args.json) out(JSON.stringify(data));
265
298
  else {
@@ -273,6 +306,40 @@ export async function runAdmin(argv, ctx, deps = {}) {
273
306
  return 0;
274
307
  }
275
308
 
309
+ /** `tot app validate`: offline manifest lint; a refused manifest is `invalid_manifest`, exit 1. */
310
+ function runValidateManifest(args, ctx, out, err) {
311
+ const path = args.positional[0]
312
+ ? resolve(ctx?.cwd || process.cwd(), args.positional[0])
313
+ : join(resolve(args.app || ctx?.cwd || process.cwd()), "tot-app.json");
314
+ if (!existsSync(path)) {
315
+ err(`✗ no manifest at ${path}\n\n → next: pass a path, or \`tot app scaffold <name>\``);
316
+ return 2;
317
+ }
318
+ let parsed;
319
+ try { parsed = JSON.parse(readFileSync(path, "utf8")); }
320
+ catch (e) { err(`✗ invalid_manifest: ${path} is not valid JSON: ${e.message}`); return 1; }
321
+ const result = validateManifest(parsed);
322
+ if (result.ok) {
323
+ if (args.json) out(JSON.stringify({ ok: true }));
324
+ else out(`✓ ${path} is a valid tot-app.json`);
325
+ return 0;
326
+ }
327
+ const errors = result.errors || [];
328
+ if (args.json) out(JSON.stringify({ ok: false, code: "invalid_manifest", errors }));
329
+ else err(`✗ invalid_manifest: ${path}\n${errors.map((e) => ` - ${e}`).join("\n")}\n\n → next: fix the manifest, then re-run \`tot app validate\``);
330
+ return 1;
331
+ }
332
+
333
+ function renderCandidates(data, json, out) {
334
+ const rows = (Array.isArray(data?.candidates) ? data.candidates : []).map((c) => ({
335
+ candidateId: c?.candidateId ?? c?.id, appId: c?.appId, appVersion: c?.appVersion, status: c?.status,
336
+ }));
337
+ if (json) { out(JSON.stringify(rows)); return 0; }
338
+ if (!rows.length) { out("No candidates on this store. Stage one with `tot app candidate`."); return 0; }
339
+ for (const r of rows) out(`${r.candidateId ?? ""} ${r.appId ?? ""} ${r.appVersion ?? ""} ${r.status ?? ""}`.trimEnd());
340
+ return 0;
341
+ }
342
+
276
343
  /**
277
344
  * A response body as JSON, or null when the store answered with something that is not JSON (an
278
345
  * HTML error page from a proxy, an empty 204). Only a parse failure maps to null.
@@ -19,6 +19,9 @@ const USAGE = `tot app — build and install a Storefront Private App
19
19
  tot app list your store's installs (never secrets)
20
20
  tot app replay <deliveryId> re-send a webhook delivery
21
21
  tot app test-order bind <installId> | create | release <orderId> synthetic preview orders for your test install
22
+ tot app suspend|resume|uninstall <installId> lifecycle of an install on your store
23
+ tot app validate [<manifest>] lint tot-app.json offline (invalid_manifest on refusal)
24
+ tot app candidate status your store's candidates and their status
22
25
  tot app candidate stage a production candidate (pending_approval) for owner approval
23
26
 
24
27
  Run \`tot app <command> --help\` for options. Online commands use your \`tot login\` session.`;
@@ -39,7 +42,7 @@ export async function run(argv, ctx) {
39
42
  const { run: runDev } = await import("./dev.mjs");
40
43
  return /** @type {any} */ (runDev)(rest, ctx);
41
44
  }
42
- if (sub === "install" || sub === "update" || sub === "rotate" || sub === "list" || sub === "replay" || sub === "test-order" || sub === "candidate") {
45
+ if (sub === "install" || sub === "update" || sub === "rotate" || sub === "list" || sub === "replay" || sub === "test-order" || sub === "candidate" || sub === "suspend" || sub === "resume" || sub === "uninstall" || sub === "validate") {
43
46
  const { runAdmin } = await import("./admin.mjs");
44
47
  return runAdmin(argv, ctx);
45
48
  }
@@ -0,0 +1,18 @@
1
+ {
2
+ "source": "tokenoftrust/storefront-devkit",
3
+ "path": "packages/connector-kit/src",
4
+ "commit": "1c64de79cdbf0860cbdcb76fa0cf78b442a79758",
5
+ "kitVersion": "1.0.0",
6
+ "files": {
7
+ "api.js": "b183146afb89fb45a2a36316fc305dde9bea80e93b8c8d3181a784cd510c5001",
8
+ "auth.js": "dfd1cf50703de0976e6c5387632cf8ff593516cf32d19277fd44b8f7c99d2129",
9
+ "encoding.js": "6de8900e65174a9d53c6fb55bcfee2afe12a08f99a34280c002a176f1c1a388c",
10
+ "errors.js": "de5a6bb0b4ef23d8820fc2afc2ab2174a45ce2ea74f91f3382950da4ab02b0d2",
11
+ "http-signature.js": "a823f1e897e65839a65562951102baccb7e64395db4201b13cb1e6c21891b424",
12
+ "index.js": "9a967f429b55a2c5f51b6c2a38e8882e1b2cbef6396b611903e0847680f03570",
13
+ "metadata.js": "0c4af4c3e9d7fdd0110d70283b99c4991a83cdeb09c8dc3ead2cecec46aded67",
14
+ "retry.js": "b28bffdf79d792a059b03387e9f1d7e4fdfdf0bdc02768024b420e40209496d4",
15
+ "structured-fields.js": "e253d027e19c61f5c48dbb09d927dc42d9cf43c926fe512c44cc06c77d08d5cc",
16
+ "webhook.js": "c90534b1db38e289fdae2c6d7c090389d6e0077f0fc919f95cc2dc07d703e428"
17
+ }
18
+ }
@@ -0,0 +1,271 @@
1
+ // Pull API client for `/api/apps/v1`. Every mutating call carries an
2
+ // Idempotency-Key, generated once per call when the caller supplies none, and
3
+ // every retry re-sends the same bytes under the same key, so a lost response is
4
+ // safe to retry. 408/429/502/503/504 and network failures are retried with
5
+ // bounded backoff; `Retry-After` is honored exactly. One 401 refreshes the
6
+ // token and repeats the call. Cursor pagination (`cursor` / `nextCursor`, with
7
+ // `limit` and `updatedSince`) drains every page.
8
+ import { ApiError, AuthError, ConnectorError, TransportError, safeCode, safeRequestId } from './errors.js';
9
+ import { hex, sha256, utf8 } from './encoding.js';
10
+ import { API_PREFIX, normalizeOrigin } from './metadata.js';
11
+ import { RETRYABLE_STATUS, backoffDelay, defaultSleep, parseRetryAfter, retryPolicy } from './retry.js';
12
+
13
+ const MUTATING = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
14
+ const METHODS = new Set(['GET', 'HEAD', ...MUTATING]);
15
+ const IDEMPOTENCY_KEY = /^[\x21-\x7e]{8,128}$/;
16
+ const TRACEPARENT = /^[0-9a-f]{2}-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/;
17
+ const SAFE_PATH = /^\/[A-Za-z0-9._~%!$&'()*+,;=:@/-]*$/;
18
+
19
+ /** A random Idempotency-Key for one logical write. */
20
+ export function newIdempotencyKey(prefix = 'ck') {
21
+ return `${prefix}-${crypto.randomUUID()}`;
22
+ }
23
+
24
+ /**
25
+ * A deterministic Idempotency-Key: the same prefix and parts always yield the
26
+ * same key, so a write re-derived after a restart replays instead of
27
+ * duplicating. Parts are JSON-serialized with sorted object keys.
28
+ */
29
+ export async function deriveIdempotencyKey(prefix, ...parts) {
30
+ const canonical = JSON.stringify(parts, (_k, v) =>
31
+ v && typeof v === 'object' && !Array.isArray(v) ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, v[k]])) : v,
32
+ );
33
+ return `${prefix}-${hex(await sha256(utf8(canonical))).slice(0, 48)}`;
34
+ }
35
+
36
+ function appendQuery(params, query) {
37
+ for (const [key, value] of Object.entries(query ?? {})) {
38
+ if (value === undefined || value === null) continue;
39
+ for (const v of Array.isArray(value) ? value : [value]) params.append(key, v instanceof Date ? v.toISOString() : String(v));
40
+ }
41
+ }
42
+
43
+ function itemsOf(body, itemsKey) {
44
+ if (itemsKey !== undefined) {
45
+ if (!Array.isArray(body?.[itemsKey])) throw new TypeError(`page has no "${itemsKey}" array`);
46
+ return body[itemsKey];
47
+ }
48
+ const arrays = Object.keys(body ?? {}).filter((k) => Array.isArray(body[k]));
49
+ if (arrays.length !== 1) throw new TypeError('cannot infer the items array of this page; pass itemsKey');
50
+ return body[arrays[0]];
51
+ }
52
+
53
+ export class ApiClient {
54
+ /**
55
+ * @param {object} options
56
+ * @param {string} options.origin The storefront origin, e.g. https://acme.tokenoftrust.store.
57
+ * @param {{ getAccessToken(): Promise<string>, invalidate?(token: string): void }} options.auth Usually a ConnectorAuthClient.
58
+ * @param {object} [options.retry] Retry policy overrides (see DEFAULT_RETRY_POLICY).
59
+ * @param {typeof fetch} [options.fetch]
60
+ * @param {(ms: number, signal?: AbortSignal) => Promise<void>} [options.sleep]
61
+ * @param {() => number} [options.random]
62
+ * @param {() => number} [options.now] Milliseconds since the epoch.
63
+ * @param {(info: { attempt: number, delayMs: number, error: ConnectorError }) => void} [options.onRetry] Observe retries (for logging).
64
+ */
65
+ constructor({
66
+ origin,
67
+ auth,
68
+ retry,
69
+ fetch: fetchImpl = (...args) => globalThis.fetch(...args),
70
+ sleep = defaultSleep,
71
+ random = Math.random,
72
+ now = () => Date.now(),
73
+ onRetry,
74
+ }) {
75
+ if (!auth || typeof auth.getAccessToken !== 'function') throw new TypeError('auth must provide getAccessToken()');
76
+ this.origin = normalizeOrigin(origin);
77
+ this.auth = auth;
78
+ this.retry = retryPolicy(retry);
79
+ this.fetch = fetchImpl;
80
+ this.sleep = sleep;
81
+ this.random = random;
82
+ this.now = now;
83
+ this.onRetry = onRetry;
84
+ }
85
+
86
+ get(path, options) {
87
+ return this.request({ ...options, method: 'GET', path });
88
+ }
89
+
90
+ delete(path, options) {
91
+ return this.request({ ...options, method: 'DELETE', path });
92
+ }
93
+
94
+ post(path, body, options) {
95
+ return this.request({ ...options, method: 'POST', path, body });
96
+ }
97
+
98
+ put(path, body, options) {
99
+ return this.request({ ...options, method: 'PUT', path, body });
100
+ }
101
+
102
+ patch(path, body, options) {
103
+ return this.request({ ...options, method: 'PATCH', path, body });
104
+ }
105
+
106
+ url(path, query) {
107
+ const refuse = () => new TypeError('path must be an absolute path under /api/apps/v1, e.g. /inventory; pass query separately');
108
+ if (typeof path !== 'string' || !SAFE_PATH.test(path)) throw refuse();
109
+ const url = new URL(`${API_PREFIX}${path}`, this.origin);
110
+ // Any normalization (a dot segment, an encoded dot) would move the call elsewhere.
111
+ if (url.origin !== this.origin || url.pathname !== `${API_PREFIX}${path}`) throw refuse();
112
+ appendQuery(url.searchParams, query);
113
+ return url.toString();
114
+ }
115
+
116
+ /**
117
+ * One API call with retries.
118
+ *
119
+ * @param {object} req
120
+ * @param {string} req.method
121
+ * @param {string} req.path Path under /api/apps/v1, e.g. `/inventory/movements`.
122
+ * @param {Record<string, unknown>} [req.query]
123
+ * @param {unknown} [req.body] JSON-serialized once.
124
+ * @param {string} [req.idempotencyKey] Mutating calls only; generated when omitted.
125
+ * @param {string} [req.traceparent] W3C Trace Context to propagate.
126
+ * @param {Record<string, string>} [req.headers] Extra headers.
127
+ * @param {AbortSignal} [req.signal]
128
+ * @returns {Promise<{ status: number, body: any, headers: Headers, requestId?: string, idempotencyKey?: string }>}
129
+ */
130
+ async request({ method, path, query, body, idempotencyKey, traceparent, headers = {}, signal }) {
131
+ const verb = String(method).toUpperCase();
132
+ if (!METHODS.has(verb)) throw new TypeError(`unsupported method ${method}`);
133
+ const url = this.url(path, query);
134
+ const sendHeaders = { accept: 'application/json' };
135
+ for (const [k, v] of Object.entries(headers)) sendHeaders[k.toLowerCase()] = String(v);
136
+ let key;
137
+ if (MUTATING.has(verb)) {
138
+ key = idempotencyKey ?? newIdempotencyKey();
139
+ if (!IDEMPOTENCY_KEY.test(key)) throw new TypeError('idempotencyKey must be 8..128 printable ASCII characters');
140
+ sendHeaders['idempotency-key'] = key;
141
+ } else if (idempotencyKey !== undefined) {
142
+ throw new TypeError(`${verb} takes no idempotencyKey`);
143
+ }
144
+ if (traceparent !== undefined) {
145
+ if (!TRACEPARENT.test(traceparent)) throw new TypeError('traceparent must be a W3C trace context value');
146
+ sendHeaders.traceparent = traceparent;
147
+ }
148
+ // Serialized once: every retry re-sends these exact bytes.
149
+ const payload = body === undefined ? undefined : JSON.stringify(body);
150
+ if (payload !== undefined) sendHeaders['content-type'] = 'application/json';
151
+
152
+ let refreshedAfter401 = false;
153
+ for (let attempt = 1; ; attempt++) {
154
+ let error;
155
+ let token;
156
+ try {
157
+ token = await this.auth.getAccessToken();
158
+ const res = await this.send(url, { method: verb, headers: { ...sendHeaders, authorization: `Bearer ${token}` }, body: payload, signal });
159
+ const result = await this.read(res);
160
+ if (res.ok) return { ...result, ...(key ? { idempotencyKey: key } : {}) };
161
+ error = this.refusal(res, result);
162
+ } catch (err) {
163
+ if (!(err instanceof ConnectorError)) throw err;
164
+ error = err;
165
+ }
166
+ // A failed write may still have committed: the caller resends under this key.
167
+ if (key) error.idempotencyKey = key;
168
+ // The auth client already retried its own token request.
169
+ if (error instanceof AuthError) throw error;
170
+ if (error instanceof ApiError && error.status === 401 && !refreshedAfter401) {
171
+ refreshedAfter401 = true;
172
+ this.auth.invalidate?.(token);
173
+ attempt--;
174
+ continue;
175
+ }
176
+ if (!error.retryable || attempt >= this.retry.maxAttempts) throw error;
177
+ if (error.retryAfterMs !== undefined && error.retryAfterMs > this.retry.maxRetryAfterMs) throw error;
178
+ const delayMs = error.retryAfterMs ?? backoffDelay(attempt, this.retry, this.random);
179
+ this.onRetry?.({ attempt, delayMs, error });
180
+ await this.sleep(delayMs, signal);
181
+ }
182
+ }
183
+
184
+ async send(url, init) {
185
+ try {
186
+ return await this.fetch(url, { ...init, redirect: 'manual' });
187
+ } catch (cause) {
188
+ if (init.signal?.aborted) throw new TransportError({ code: 'aborted', cause });
189
+ throw new TransportError({ code: 'network', retryable: true, cause });
190
+ }
191
+ }
192
+
193
+ async read(res) {
194
+ const requestId = safeRequestId(res.headers.get('tot-request-id'));
195
+ const text = await res.text();
196
+ let body = null;
197
+ if (text !== '') {
198
+ try {
199
+ body = JSON.parse(text);
200
+ } catch {
201
+ body = null;
202
+ }
203
+ }
204
+ return { status: res.status, body, headers: res.headers, requestId };
205
+ }
206
+
207
+ refusal(res, { body, requestId }) {
208
+ if (res.status >= 300 && res.status < 400) return new TransportError({ code: 'redirect_refused', status: res.status, requestId });
209
+ const code = safeCode(body?.code ?? body?.error ?? (body === null ? `http_${res.status}` : undefined));
210
+ const holds = Array.isArray(body?.holds) ? body.holds.map(safeCode) : undefined;
211
+ return new ApiError({
212
+ code,
213
+ status: res.status,
214
+ requestId: requestId ?? safeRequestId(body?.requestId),
215
+ retryable: RETRYABLE_STATUS.has(res.status),
216
+ retryAfterMs: parseRetryAfter(res.headers.get('retry-after'), this.now()),
217
+ holds,
218
+ });
219
+ }
220
+
221
+ /**
222
+ * Every page of a cursor-paginated list.
223
+ *
224
+ * @param {string} path e.g. `/catalog/products`.
225
+ * @param {object} [options]
226
+ * @param {Record<string, unknown>} [options.query] Extra filters.
227
+ * @param {number} [options.limit] Page size (1..100).
228
+ * @param {string|Date} [options.updatedSince] Only records changed since then.
229
+ * @param {string} [options.cursor] Resume from a saved `nextCursor`.
230
+ * @param {string} [options.itemsKey] The page's items array; inferred when the page has exactly one array.
231
+ * @param {number} [options.maxPages] Stop after this many pages.
232
+ * @param {AbortSignal} [options.signal]
233
+ * @returns {AsyncGenerator<{ items: any[], nextCursor?: string, truncated: boolean, body: any, requestId?: string }>}
234
+ */
235
+ async *pages(path, { query, limit, updatedSince, cursor, itemsKey, maxPages = Infinity, signal } = {}) {
236
+ let next = cursor;
237
+ const seen = new Set(cursor === undefined ? [] : [cursor]);
238
+ for (let page = 0; page < maxPages; page++) {
239
+ const res = await this.get(path, { query: { ...query, limit, updatedSince, cursor: next }, signal });
240
+ const nextCursor = typeof res.body?.nextCursor === 'string' && res.body.nextCursor !== '' ? res.body.nextCursor : undefined;
241
+ yield { items: itemsOf(res.body, itemsKey), nextCursor, truncated: res.body?.truncated === true, body: res.body, requestId: res.requestId };
242
+ if (nextCursor === undefined) return;
243
+ // A repeated cursor (A→A or A→B→A) would page forever.
244
+ if (seen.has(nextCursor)) throw new TransportError({ code: 'pagination_stalled', requestId: res.requestId });
245
+ seen.add(nextCursor);
246
+ next = nextCursor;
247
+ }
248
+ }
249
+
250
+ /** Every item across every page. Same options as `pages`. */
251
+ async *items(path, options) {
252
+ for await (const page of this.pages(path, options)) yield* page.items;
253
+ }
254
+
255
+ /**
256
+ * Drain a list into memory. `truncated` is true when any page said the
257
+ * server did not return everything (e.g. orders changed since `updatedSince`
258
+ * beyond its cap): run a full backfill without `updatedSince`.
259
+ */
260
+ async collect(path, options) {
261
+ const items = [];
262
+ let truncated = false;
263
+ let pages = 0;
264
+ for await (const page of this.pages(path, options)) {
265
+ items.push(...page.items);
266
+ truncated ||= page.truncated;
267
+ pages++;
268
+ }
269
+ return { items, truncated, pages };
270
+ }
271
+ }