@snowcone-app/sdk 0.14.0 → 0.16.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/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.16.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#662](https://github.com/snowcone-app/snowcone-monorepo/pull/662) [`755ad1d`](https://github.com/snowcone-app/snowcone-monorepo/commit/755ad1dc55449c4ec2b0da0158ff411913dce832) Thanks [@kevinsproles](https://github.com/kevinsproles)! - Semantic visual search for the designs catalog: every design gets an AI-generated visual caption (indexed + searchable) and the index carries an embedder, so descriptive queries like "pink cowgirl boots on the moon" match designs regardless of publisher metadata. `searchDesigns` (SDK) and `snowcone_search_designs` (MCP) now send hybrid keyword+semantic search by default — tune with `semanticRatio` / `semantic_ratio` (0 = keyword-only).
8
+
9
+ ## 0.15.0
10
+
11
+ ### Minor Changes
12
+
13
+ - [#652](https://github.com/snowcone-app/snowcone-monorepo/pull/652) [`3f9175f`](https://github.com/snowcone-app/snowcone-monorepo/commit/3f9175fb1986642c94757f6b0f1b586c196f0ac6) Thanks [@kevinsproles](https://github.com/kevinsproles)! - Render catalog designs by reference (ADR-0086): new `design=<pairingId|slug>` wire param. `getMockupUrl` accepts `designRef`, and the MCP `snowcone_search_designs` tool now returns `design=` reference URLs instead of re-assembling raw asset components. Catalog design renders are free — they never count against the shop's usage budget.
14
+
15
+ ### Patch Changes
16
+
17
+ - [#651](https://github.com/snowcone-app/snowcone-monorepo/pull/651) [`925a52d`](https://github.com/snowcone-app/snowcone-monorepo/commit/925a52dccbe7c094bce5965c8e388c56a62a4e60) Thanks [@kevinsproles](https://github.com/kevinsproles)! - `fetchMockupImage(url)` — fetch a rendered mockup URL and prove it's a real image, absorbing the mint→edge KV propagation lag: bounded ~10s retry on "Unknown shop" for freshly minted shops, then a loud structured throw naming the propagation cause (`SnowconeSdkError` `SHOP_NOT_PROPAGATED`); allowlist denials surface as `ASSET_FORBIDDEN` with the failed assets named, other failures as `RENDER_FAILED` (agent-DX decision F2).
18
+
3
19
  ## 0.14.0
4
20
 
5
21
  ### Minor Changes
@@ -3,7 +3,25 @@ var PARAMS = {
3
3
  shop: "shop",
4
4
  asset: "asset",
5
5
  assets: "assets",
6
+ /**
7
+ * Render a catalog design by reference (ADR-0086): `design=<pairingId|slug>`.
8
+ * The resolver looks the design up in the public `snowcone-designs` index
9
+ * (membership = license) and injects its asset components server-side, so no
10
+ * raw asset URL crosses the wire and no origin allowlisting is involved.
11
+ * Catalog renders are FREE — mutually exclusive with `asset`/`asset.<key>`/
12
+ * `color.<key>` (free = the design as published).
13
+ */
14
+ design: "design",
6
15
  placement: "placement",
16
+ /**
17
+ * Album page selector (ADR-0086 §5): `page=N` (positive integer) picks which
18
+ * page/spread of an album product a mockup renders. Only valid on products
19
+ * whose catalog entry carries an `album` block — the edge resolver maps page
20
+ * N onto the repeating page placement (`page_N` → the geometry of
21
+ * `album.pagePlacement`); the catalog never enumerates `page_1…page_100` and
22
+ * rendercenter is unchanged.
23
+ */
24
+ page: "page",
7
25
  variant: "variant",
8
26
  mockup: "mockup",
9
27
  width: "width",
@@ -149,10 +167,15 @@ function buildPublicMockupUrl(options, cfg = {}) {
149
167
  }
150
168
  } else if (options.assetUrl !== void 0) {
151
169
  parts.push(`${PARAMS.asset}=${enc(options.assetUrl)}`);
170
+ } else if (options.designRef !== void 0) {
171
+ parts.push(`${PARAMS.design}=${enc(options.designRef)}`);
152
172
  }
153
173
  if (options.placement !== void 0) {
154
174
  parts.push(`${PARAMS.placement}=${enc(options.placement)}`);
155
175
  }
176
+ if (options.page !== void 0) {
177
+ parts.push(`${PARAMS.page}=${options.page}`);
178
+ }
156
179
  if (options.options) {
157
180
  for (const attr of Object.keys(options.options).sort()) {
158
181
  parts.push(`${PARAM_PREFIX.opt}${enc(attr)}=${enc(options.options[attr])}`);
@@ -172,8 +195,10 @@ function buildPublicMockupUrl(options, cfg = {}) {
172
195
  }
173
196
  var PUBLIC_PARAM_NAMES = [
174
197
  PARAMS.asset,
198
+ PARAMS.design,
175
199
  PARAMS.shop,
176
200
  PARAMS.placement,
201
+ PARAMS.page,
177
202
  PARAMS.variant,
178
203
  PARAMS.mockup,
179
204
  PARAMS.width,
package/dist/index.cjs CHANGED
@@ -56,6 +56,7 @@ __export(index_exports, {
56
56
  REALTIME_WS_URL: () => REALTIME_WS_URL,
57
57
  RealtimeMockupService: () => RealtimeMockupService,
58
58
  RenderSession: () => RenderSession,
59
+ SnowconeSdkError: () => SnowconeSdkError,
59
60
  StandardComponents: () => StandardComponents,
60
61
  StandardEvents: () => StandardEvents,
61
62
  StateManager: () => StateManager,
@@ -102,6 +103,7 @@ __export(index_exports, {
102
103
  describeProductPrice: () => describeProductPrice,
103
104
  describeProductTitle: () => describeProductTitle,
104
105
  extractProductId: () => extractProductId,
106
+ fetchMockupImage: () => fetchMockupImage,
105
107
  fetchRealtimeGrant: () => fetchRealtimeGrant,
106
108
  filterImagePlacements: () => filterImagePlacements,
107
109
  findBestCombination: () => findBestCombination,
@@ -122,8 +124,10 @@ __export(index_exports, {
122
124
  getSnapPoints: () => getSnapPoints,
123
125
  getVariant: () => getVariant,
124
126
  handleOptionChange: () => handleOptionChange,
127
+ imageKindOf: () => imageKindOf,
125
128
  isOptionAvailable: () => isOptionAvailable,
126
129
  isSelectionComplete: () => isSelectionComplete,
130
+ isSnowconeSdkError: () => isSnowconeSdkError,
127
131
  isValidAlignment: () => isValidAlignment,
128
132
  isValidTileCount: () => isValidTileCount,
129
133
  listProducts: () => listProducts,
@@ -478,7 +482,25 @@ var PARAMS = {
478
482
  shop: "shop",
479
483
  asset: "asset",
480
484
  assets: "assets",
485
+ /**
486
+ * Render a catalog design by reference (ADR-0086): `design=<pairingId|slug>`.
487
+ * The resolver looks the design up in the public `snowcone-designs` index
488
+ * (membership = license) and injects its asset components server-side, so no
489
+ * raw asset URL crosses the wire and no origin allowlisting is involved.
490
+ * Catalog renders are FREE — mutually exclusive with `asset`/`asset.<key>`/
491
+ * `color.<key>` (free = the design as published).
492
+ */
493
+ design: "design",
481
494
  placement: "placement",
495
+ /**
496
+ * Album page selector (ADR-0086 §5): `page=N` (positive integer) picks which
497
+ * page/spread of an album product a mockup renders. Only valid on products
498
+ * whose catalog entry carries an `album` block — the edge resolver maps page
499
+ * N onto the repeating page placement (`page_N` → the geometry of
500
+ * `album.pagePlacement`); the catalog never enumerates `page_1…page_100` and
501
+ * rendercenter is unchanged.
502
+ */
503
+ page: "page",
482
504
  variant: "variant",
483
505
  mockup: "mockup",
484
506
  width: "width",
@@ -624,10 +646,15 @@ function buildPublicMockupUrl(options, cfg = {}) {
624
646
  }
625
647
  } else if (options.assetUrl !== void 0) {
626
648
  parts.push(`${PARAMS.asset}=${enc(options.assetUrl)}`);
649
+ } else if (options.designRef !== void 0) {
650
+ parts.push(`${PARAMS.design}=${enc(options.designRef)}`);
627
651
  }
628
652
  if (options.placement !== void 0) {
629
653
  parts.push(`${PARAMS.placement}=${enc(options.placement)}`);
630
654
  }
655
+ if (options.page !== void 0) {
656
+ parts.push(`${PARAMS.page}=${options.page}`);
657
+ }
631
658
  if (options.options) {
632
659
  for (const attr of Object.keys(options.options).sort()) {
633
660
  parts.push(`${PARAM_PREFIX.opt}${enc(attr)}=${enc(options.options[attr])}`);
@@ -647,8 +674,10 @@ function buildPublicMockupUrl(options, cfg = {}) {
647
674
  }
648
675
  var PUBLIC_PARAM_NAMES = [
649
676
  PARAMS.asset,
677
+ PARAMS.design,
650
678
  PARAMS.shop,
651
679
  PARAMS.placement,
680
+ PARAMS.page,
652
681
  PARAMS.variant,
653
682
  PARAMS.mockup,
654
683
  PARAMS.width,
@@ -919,6 +948,7 @@ function getMockupUrl(a, b, c) {
919
948
  shop: opts.shop,
920
949
  ...opts.design ? { design: opts.design } : {},
921
950
  ...assetUrl !== void 0 ? { assetUrl } : {},
951
+ ...opts.designRef !== void 0 ? { designRef: opts.designRef } : {},
922
952
  ...opts.options ? { options: opts.options } : {},
923
953
  ...opts.width !== void 0 ? { width: opts.width } : {},
924
954
  ...opts.aspect !== void 0 ? { aspect: opts.aspect } : {},
@@ -2414,6 +2444,109 @@ async function retryOperation(operation, options = {}) {
2414
2444
  throw lastError;
2415
2445
  }
2416
2446
 
2447
+ // src/error/structured.ts
2448
+ var SnowconeSdkError = class extends Error {
2449
+ code;
2450
+ data;
2451
+ constructor(code, message, data = {}) {
2452
+ super(`${code}: ${message}`);
2453
+ this.name = "SnowconeSdkError";
2454
+ this.code = code;
2455
+ this.data = { code, ...data };
2456
+ }
2457
+ };
2458
+ function isSnowconeSdkError(err) {
2459
+ return err instanceof Error && err.name === "SnowconeSdkError" && "code" in err;
2460
+ }
2461
+
2462
+ // src/mockup/fetchMockupImage.ts
2463
+ function imageKindOf(b) {
2464
+ if (b[0] === 137 && b[1] === 80) return "PNG";
2465
+ if (b[0] === 255 && b[1] === 216) return "JPEG";
2466
+ if (b[0] === 71 && b[1] === 73 && b[2] === 70) return "GIF";
2467
+ if (b[0] === 82 && b[1] === 73 && b[2] === 70 && b[3] === 70) return "WebP";
2468
+ if (b.length >= 12 && String.fromCharCode(b[4], b[5], b[6], b[7]) === "ftyp") return "AVIF";
2469
+ return void 0;
2470
+ }
2471
+ var DEFAULT_RETRY_DELAYS_MS = [500, 1e3, 2e3, 2e3, 2e3, 2e3];
2472
+ function parseFailure(status, bytes) {
2473
+ const text = new TextDecoder().decode(bytes).slice(0, 1e3);
2474
+ let error = `HTTP ${status}`;
2475
+ let failedAssets = [];
2476
+ try {
2477
+ const j = JSON.parse(text);
2478
+ error = String(j.error ?? j.message ?? (text || error));
2479
+ if (Array.isArray(j.failedAssets)) failedAssets = j.failedAssets;
2480
+ } catch {
2481
+ if (text) error = text;
2482
+ }
2483
+ return { status, error, failedAssets, bodyText: text };
2484
+ }
2485
+ function isUnknownShop(f) {
2486
+ return /unknown shop/i.test(f.error);
2487
+ }
2488
+ function isAssetForbidden(f) {
2489
+ if (f.failedAssets.some((a) => a.status === 403 || /blocked|forbidden|allowlist|not allowed/i.test(`${a.reason ?? ""} ${a.code ?? ""}`))) {
2490
+ return true;
2491
+ }
2492
+ return /host blocked|allowlist|not an allowed|forbidden/i.test(f.error);
2493
+ }
2494
+ async function fetchMockupImage(url, opts = {}) {
2495
+ const f = opts.fetchImpl ?? globalThis.fetch;
2496
+ const retryWindowMs = opts.retryWindowMs ?? 1e4;
2497
+ const delays = opts.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
2498
+ const timeoutMs = opts.timeoutMs ?? 2e4;
2499
+ const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
2500
+ let waited = 0;
2501
+ let attempt = 0;
2502
+ let last = null;
2503
+ for (; ; ) {
2504
+ const controller = new AbortController();
2505
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
2506
+ let failure;
2507
+ try {
2508
+ const res = await f(url, { signal: controller.signal });
2509
+ const bytes = new Uint8Array(await res.arrayBuffer());
2510
+ const kind = imageKindOf(bytes);
2511
+ if (res.ok && kind) {
2512
+ return { status: res.status, kind, bytes };
2513
+ }
2514
+ failure = parseFailure(res.status, bytes);
2515
+ } catch (err) {
2516
+ const message = err instanceof Error ? err.message : String(err);
2517
+ failure = { status: 0, error: `network error fetching ${url}: ${message}`, failedAssets: [], bodyText: "" };
2518
+ } finally {
2519
+ clearTimeout(timer);
2520
+ }
2521
+ last = failure;
2522
+ if (isAssetForbidden(failure)) {
2523
+ throw new SnowconeSdkError(
2524
+ "ASSET_FORBIDDEN",
2525
+ `the shop's asset-origin allowlist denied an asset in this design: ${failure.error}. Add the asset's origin to the shop's allowed asset origins (or host the asset on the shop's storage origin) and retry \u2014 the URL and your code are otherwise fine.`,
2526
+ { url, status: failure.status, failedAssets: failure.failedAssets }
2527
+ );
2528
+ }
2529
+ const nextDelay = delays[Math.min(attempt, delays.length - 1)] ?? 2e3;
2530
+ const canRetry = isUnknownShop(failure) && waited + nextDelay <= retryWindowMs;
2531
+ if (!canRetry) break;
2532
+ await sleep(nextDelay);
2533
+ waited += nextDelay;
2534
+ attempt += 1;
2535
+ }
2536
+ if (last && isUnknownShop(last)) {
2537
+ throw new SnowconeSdkError(
2538
+ "SHOP_NOT_PROPAGATED",
2539
+ `the render edge still answers "Unknown shop" after ${Math.round(retryWindowMs / 1e3)}s of retries. For a freshly minted shop this is edge KV propagation lag (normally ~1\u20133s) \u2014 your code is not the problem. If this shop is NOT freshly minted, the shop id is wrong: confirm the publishable shop id (shop.id) you passed.`,
2540
+ { url, status: last.status, retriedMs: waited, cause: "kv-propagation" }
2541
+ );
2542
+ }
2543
+ throw new SnowconeSdkError(
2544
+ "RENDER_FAILED",
2545
+ `mockup URL did not render an image: ${last?.error ?? "unknown error"}`,
2546
+ { url, status: last?.status ?? 0, error: last?.error, failedAssets: last?.failedAssets ?? [] }
2547
+ );
2548
+ }
2549
+
2417
2550
  // src/context/synchronization.ts
2418
2551
  var ContextSynchronizer = class {
2419
2552
  constructor(options = {}) {
@@ -6121,7 +6254,15 @@ async function searchDesigns(query = "", options) {
6121
6254
  q: query,
6122
6255
  limit: options?.limit || 50,
6123
6256
  ...options?.offset ? { offset: options.offset } : {},
6124
- ...options?.filter ? { filter: options.filter } : {}
6257
+ ...options?.filter ? { filter: options.filter } : {},
6258
+ // Hybrid semantic search over the AI visual captions (default on for
6259
+ // real queries; an empty q is a plain listing).
6260
+ ...query && (options?.semanticRatio ?? 0.5) > 0 ? {
6261
+ hybrid: {
6262
+ embedder: "default",
6263
+ semanticRatio: options?.semanticRatio ?? 0.5
6264
+ }
6265
+ } : {}
6125
6266
  })
6126
6267
  });
6127
6268
  if (!res.ok) throw new Error(`searchDesigns failed: ${res.status}`);
@@ -6181,6 +6322,7 @@ function createClient(config) {
6181
6322
  REALTIME_WS_URL,
6182
6323
  RealtimeMockupService,
6183
6324
  RenderSession,
6325
+ SnowconeSdkError,
6184
6326
  StandardComponents,
6185
6327
  StandardEvents,
6186
6328
  StateManager,
@@ -6227,6 +6369,7 @@ function createClient(config) {
6227
6369
  describeProductPrice,
6228
6370
  describeProductTitle,
6229
6371
  extractProductId,
6372
+ fetchMockupImage,
6230
6373
  fetchRealtimeGrant,
6231
6374
  filterImagePlacements,
6232
6375
  findBestCombination,
@@ -6247,8 +6390,10 @@ function createClient(config) {
6247
6390
  getSnapPoints,
6248
6391
  getVariant,
6249
6392
  handleOptionChange,
6393
+ imageKindOf,
6250
6394
  isOptionAvailable,
6251
6395
  isSelectionComplete,
6396
+ isSnowconeSdkError,
6252
6397
  isValidAlignment,
6253
6398
  isValidTileCount,
6254
6399
  listProducts,
package/dist/index.d.cts CHANGED
@@ -96,6 +96,27 @@ interface CatalogProduct {
96
96
  autoFilledByVariant: boolean;
97
97
  }[];
98
98
  defaultGvid?: string | null;
99
+ /**
100
+ * ADR-0086: marks an album/book product whose single page placement repeats. Consumers (edge resolver, buy worker, supplier export) expand `page_1..page_N` on demand from `pageExtent` — catalog documents never enumerate pages. Additive: products without this block are unaffected.
101
+ */
102
+ album?: {
103
+ /**
104
+ * Wire `key` of the repeating page placement (e.g. "page"). Page N is addressed as `<pagePlacement>_N` and resolves to this placement's geometry.
105
+ */
106
+ pagePlacement: string;
107
+ /**
108
+ * Name of the `options.attributes` entry that carries the page count (e.g. "Pages"). An ordinary affectsCombinations axis — combinations stay Size × Pages rows.
109
+ */
110
+ pageAxis: string;
111
+ /**
112
+ * Buyable page counts: min..max in increments of step.
113
+ */
114
+ pageExtent: {
115
+ min: number;
116
+ max: number;
117
+ step: number;
118
+ };
119
+ };
99
120
  }
100
121
 
101
122
  /**
@@ -227,6 +248,13 @@ interface GetMockupUrlOptions {
227
248
  * params. Takes precedence over `asset`.
228
249
  */
229
250
  design?: Design;
251
+ /**
252
+ * Catalog design reference (ADR-0086): a `pairingId` or `slug` from the
253
+ * public designs catalog (`searchDesigns`). Emitted as `design=` — the
254
+ * resolver injects the published components server-side and the render is
255
+ * FREE (no usage charge). Mutually exclusive with `asset`/`design`.
256
+ */
257
+ designRef?: string;
230
258
  /**
231
259
  * Variant option picks: attribute name → choice label (e.g. `{ size: "m" }`).
232
260
  * Emitted as `opt.<attr>`. Matched case-insensitively by the resolver.
@@ -1194,6 +1222,93 @@ declare function retryOperation<T>(operation: () => Promise<T>, options?: {
1194
1222
  onRetry?: (attempt: number, error: Error) => void;
1195
1223
  }): Promise<T>;
1196
1224
 
1225
+ /**
1226
+ * Structured SDK errors (agent-DX decision E3, ADR-0085 plan): every public
1227
+ * throw carries a STABLE `code` plus machine-readable `data`, with the human
1228
+ * message rendered from them. Tests (and agents) assert on `code` + `data`
1229
+ * fields — never on prose substrings.
1230
+ */
1231
+ type SnowconeSdkErrorCode =
1232
+ /** Freshly minted shop not yet visible at the render edge (KV lag). */
1233
+ 'SHOP_NOT_PROPAGATED'
1234
+ /** The shop's asset-origin allowlist denied an asset in the design. */
1235
+ | 'ASSET_FORBIDDEN'
1236
+ /** Any other render failure (server reason in `data.error`). */
1237
+ | 'RENDER_FAILED';
1238
+ declare class SnowconeSdkError extends Error {
1239
+ readonly code: SnowconeSdkErrorCode;
1240
+ readonly data: Record<string, unknown>;
1241
+ constructor(code: SnowconeSdkErrorCode, message: string, data?: Record<string, unknown>);
1242
+ }
1243
+ declare function isSnowconeSdkError(err: unknown): err is SnowconeSdkError;
1244
+
1245
+ /**
1246
+ * Fetch a rendered mockup URL and prove it is a real image — with the
1247
+ * mint→edge propagation lag absorbed (agent-DX decision F2, ADR-0085 plan).
1248
+ *
1249
+ * THE TRAP THIS KILLS: a freshly minted (sandbox) shop takes a few seconds to
1250
+ * propagate to the render edge's KV store. A render request in that window
1251
+ * 404s `"Unknown shop"` — on CORRECT code. Agents (and humans) then debug the
1252
+ * integration instead of waiting. This helper retries that one failure mode
1253
+ * inside a bounded window (~10s by default) and, if the shop still isn't
1254
+ * visible, throws a LOUD structured error naming the propagation cause — so
1255
+ * nobody ever bisects working code over KV lag.
1256
+ *
1257
+ * Every other failure (asset blocked by the shop's asset-origin allowlist,
1258
+ * product not found, non-image response) throws immediately with a stable
1259
+ * `code` + `data` (no retry — they are deterministic).
1260
+ */
1261
+ /** Identify common raster formats by magic bytes; undefined if not an image. */
1262
+ declare function imageKindOf(b: Uint8Array): string | undefined;
1263
+ /** One failed asset, as reported by the render edge (`failedAssets[]`). */
1264
+ interface FailedAsset {
1265
+ url?: string;
1266
+ reason?: string;
1267
+ code?: string;
1268
+ status?: number;
1269
+ }
1270
+ interface MockupImage {
1271
+ /** Always 200-family when this resolves. */
1272
+ status: number;
1273
+ /** 'PNG' | 'JPEG' | 'WebP' | 'AVIF' | 'GIF'. */
1274
+ kind: string;
1275
+ /** The raw encoded image. */
1276
+ bytes: Uint8Array;
1277
+ }
1278
+ interface FetchMockupImageOptions {
1279
+ /**
1280
+ * Total window to keep retrying `"Unknown shop"` (the mint→edge KV
1281
+ * propagation lag) before throwing `SHOP_NOT_PROPAGATED`. Default 10_000ms.
1282
+ * Set 0 to disable the retry entirely.
1283
+ */
1284
+ retryWindowMs?: number;
1285
+ /**
1286
+ * Backoff schedule inside the window (ms between attempts). Exposed mostly
1287
+ * for tests; the default ramps 500 → 2000ms.
1288
+ */
1289
+ retryDelaysMs?: number[];
1290
+ /** Per-attempt fetch timeout. Default 20_000ms. */
1291
+ timeoutMs?: number;
1292
+ /** Override fetch (tests / non-global-fetch runtimes). */
1293
+ fetchImpl?: typeof fetch;
1294
+ /** Override sleeping between retries (tests). */
1295
+ sleep?: (ms: number) => Promise<void>;
1296
+ }
1297
+ /**
1298
+ * Fetch `url` until it yields a real raster image.
1299
+ *
1300
+ * Resolves with the image bytes on success. Throws {@link SnowconeSdkError}:
1301
+ *
1302
+ * - `SHOP_NOT_PROPAGATED` — the edge still answers `"Unknown shop"` after the
1303
+ * retry window. For a freshly minted shop this is KV propagation lag, not a
1304
+ * bug in your code; the message says exactly that.
1305
+ * - `ASSET_FORBIDDEN` — the shop's asset-origin allowlist denied an asset
1306
+ * referenced by the design (`data.failedAssets` names which, and why).
1307
+ * - `RENDER_FAILED` — any other non-image response (`data.error` carries the
1308
+ * server's reason, e.g. "Product not found").
1309
+ */
1310
+ declare function fetchMockupImage(url: string, opts?: FetchMockupImageOptions): Promise<MockupImage>;
1311
+
1197
1312
  /**
1198
1313
  * Context synchronization utilities for managing state updates
1199
1314
  * across React and Web Component implementations
@@ -3144,6 +3259,13 @@ interface SearchDesignsOptions extends Partial<SdkConfig> {
3144
3259
  offset?: number;
3145
3260
  /** Meilisearch filter, e.g. "occasion = 'christmas' AND style = 'watercolor'". */
3146
3261
  filter?: string;
3262
+ /**
3263
+ * Hybrid (semantic + keyword) blend, 0..1. The index carries an embedder
3264
+ * over each design's AI visual caption, so descriptive queries ("pink
3265
+ * cowgirl boots on the moon") match designs whose metadata never said so.
3266
+ * Default 0.5 for non-empty queries; pass 0 for keyword-only.
3267
+ */
3268
+ semanticRatio?: number;
3147
3269
  }
3148
3270
  interface SnowconeClient {
3149
3271
  catalog: {
@@ -3170,4 +3292,4 @@ declare function searchDesigns(query?: string, options?: SearchDesignsOptions):
3170
3292
  */
3171
3293
  declare function createClient(config: SdkConfig): SnowconeClient;
3172
3294
 
3173
- export { AbstractTemplateRenderer, type AddToCartOptions, Animations, type ArtSelectorContext, type ArtSelectorDescriptor, type ArtSelectorOptions, type ArtworkData, type AspectRatio, Attributes, type BaseDescriptor, type BlendConfig, type BuildMockupUrlConfig, type CartDetail, type CatalogDesign, type CatalogListResponse, type CatalogProduct, ClassNames, type ColorDesignElement, ColorPickerUtils, Combination, CommonProps, ComponentContext, type ComponentDefinition, ComponentDescriptor, ComponentEventManager, ComponentFactory, ComponentLifecycle, ComponentLifecycleHooks, type ComponentMetadata, ComponentProps, ComponentRegistry, ComponentState, type ComponentTemplate, ComponentTemplates, type ContainerDescriptor, ContextBridge, type ContextComparator, type ContextConsumer, ContextInjector, type ContextProviderConfig, type ContextSubscriber, ContextSynchronizer, type CreateDesignStateInput, type CreatedDesignState, DEFAULT_ARTWORK_URL, DEFAULT_ASPECT_RATIO, DEFAULT_BUY_BASE, DEFAULT_COLOR, DEFAULT_GRANT_BASE, DEFAULT_MOCKUP_BASE, DEFAULT_PLACEMENT_DIMENSIONS, type Descriptor, type Design, type DesignElement, type DesignGenerationContext, type DesignLike, type DesignsSearchResponse, type Effects, Elements, type ErrorContext, type ErrorHandler, ErrorManager, type EventDefinition, EventDelegator, EventEmitter, EventHandler, type EventListener, type EventPayload, type Fill, Focus, FrameworkAdapter, FrameworkUtilities, type GetMockupUrlOptions, type ImageAlignment, type ImageDesignElement, type LifecycleHook, LifecycleManager, type LifecyclePhase, type LifecycleTransition, LitAdapter, type MaskOverride, type MockupGenerationOptions, MockupResult, type MockupService, type MockupServiceConfig, OptionAttribute, type OptionChoice, type OptionChoiceRenderData, type OptionRenderData, OptionSelection, type Placement, type PlacementDesign, PlacementSettings, type ProductArtAlignmentContext, type ProductArtAlignmentDescriptor, type ProductArtAlignmentOptions, type ProductContext, type ProductContextEvents, ProductContextManager, type ProductData, type ProductFetcher, type ProductImageDescriptor, type ProductImageOptions, ProductLoader, type ProductMockupData, type ProductOptionChoice, type ProductOptionData, type ProductOptionsDescriptor, type ProductOptionsOptions, type ProductPlacement, type ProductPriceDescriptor, type ProductPriceOptions, ProductProps, type ProductSpec, type ProductTitleDescriptor, type ProductTitleOptions, type ProductVariant, type PropDefinition, type PropSchema, type PropType, PropertyManager, REALTIME_WS_URL, type RateLimitState, type RealtimeGrant, RealtimeMockupService, type RegularArtwork, type RenderProduct, type RenderProductAttribute, type RenderProductAttributeChoice, type RenderProductCombination, type RenderProductMockup, type RenderProductOptions, type RenderProductRequiredPlacement, RenderSession, type RenderSessionOptions, type RenderState, type SdkConfig, type SeamlessPattern, type SearchDesignsOptions, type SignedUrlResponse, type SnowconeClient, StandardComponents, StandardEvents, StateManager, type StateManagerOptions, type StateMiddleware, type StateSelector, type StateSubscriber, type StateUpdater, Styles, SvelteAdapter, SwatchUtils, type TagName, TemplateBuilder, type TemplateNode, type TemplateNodeType, type TemplateRenderer, type TextDescriptor, type TileCount, UniversalContextProvider, type UserSelection, type ValidationError, type ValidationResult, VueAdapter, assertVariantSelected, autoRegister, bffSigner, buildMockupUrl, componentRegistry, createAddToCartEvent, createAddToCartHandler, createCartDetail, createClient, createContextProvider, createDesignForPlacements, createDesignState, createErrorHandler, createEventManager, createLifecycle, createLitComponent, createProductContext, createProductLoader, createPropertyManager, createStateHook, createStateStore, createSvelteComponent, createUniversalProvider, createVueComponent, describeArtSelector, describeProductArtAlignment, describeProductImage, describeProductOptions, describeProductPrice, describeProductTitle, extractProductId, fetchRealtimeGrant, filterImagePlacements, findClosestSnapPoint, findVariantForSelection, formatPrice, formatValidationErrors, getBuyUrl, getDefaultVariantId, getEffectiveAlignment, getIncompleteSelectionMessage, getMissingSelections, getMockupUrl, getOptionRenderType, getProduct, getSelectionDisplayText, getSnapPoints, getVariant, handleOptionChange, isSelectionComplete, isValidAlignment, isValidTileCount, listProducts, mintRealtimeGrant, mockupUrl, normalizeChoice, prepareOptionRenderData, registerStandardComponents, resolveMockupId, resolveVariantId, retryOperation, searchDesigns, simulateCartOperation, toCombinations, toOptionAttributes, useFrameworkAdapter as useVueAdapter, validateAlignment, validateDesignElement, validateEffects, validateImageUrl, validateMockupOptions, validateProductSelection, validateProductSpec, validateRequiredOptions, validateTileCount, warnVariantNotSelected, withContext, withErrorHandling, withSyncErrorHandling };
3295
+ export { AbstractTemplateRenderer, type AddToCartOptions, Animations, type ArtSelectorContext, type ArtSelectorDescriptor, type ArtSelectorOptions, type ArtworkData, type AspectRatio, Attributes, type BaseDescriptor, type BlendConfig, type BuildMockupUrlConfig, type CartDetail, type CatalogDesign, type CatalogListResponse, type CatalogProduct, ClassNames, type ColorDesignElement, ColorPickerUtils, Combination, CommonProps, ComponentContext, type ComponentDefinition, ComponentDescriptor, ComponentEventManager, ComponentFactory, ComponentLifecycle, ComponentLifecycleHooks, type ComponentMetadata, ComponentProps, ComponentRegistry, ComponentState, type ComponentTemplate, ComponentTemplates, type ContainerDescriptor, ContextBridge, type ContextComparator, type ContextConsumer, ContextInjector, type ContextProviderConfig, type ContextSubscriber, ContextSynchronizer, type CreateDesignStateInput, type CreatedDesignState, DEFAULT_ARTWORK_URL, DEFAULT_ASPECT_RATIO, DEFAULT_BUY_BASE, DEFAULT_COLOR, DEFAULT_GRANT_BASE, DEFAULT_MOCKUP_BASE, DEFAULT_PLACEMENT_DIMENSIONS, type Descriptor, type Design, type DesignElement, type DesignGenerationContext, type DesignLike, type DesignsSearchResponse, type Effects, Elements, type ErrorContext, type ErrorHandler, ErrorManager, type EventDefinition, EventDelegator, EventEmitter, EventHandler, type EventListener, type EventPayload, type FailedAsset, type FetchMockupImageOptions, type Fill, Focus, FrameworkAdapter, FrameworkUtilities, type GetMockupUrlOptions, type ImageAlignment, type ImageDesignElement, type LifecycleHook, LifecycleManager, type LifecyclePhase, type LifecycleTransition, LitAdapter, type MaskOverride, type MockupGenerationOptions, type MockupImage, MockupResult, type MockupService, type MockupServiceConfig, OptionAttribute, type OptionChoice, type OptionChoiceRenderData, type OptionRenderData, OptionSelection, type Placement, type PlacementDesign, PlacementSettings, type ProductArtAlignmentContext, type ProductArtAlignmentDescriptor, type ProductArtAlignmentOptions, type ProductContext, type ProductContextEvents, ProductContextManager, type ProductData, type ProductFetcher, type ProductImageDescriptor, type ProductImageOptions, ProductLoader, type ProductMockupData, type ProductOptionChoice, type ProductOptionData, type ProductOptionsDescriptor, type ProductOptionsOptions, type ProductPlacement, type ProductPriceDescriptor, type ProductPriceOptions, ProductProps, type ProductSpec, type ProductTitleDescriptor, type ProductTitleOptions, type ProductVariant, type PropDefinition, type PropSchema, type PropType, PropertyManager, REALTIME_WS_URL, type RateLimitState, type RealtimeGrant, RealtimeMockupService, type RegularArtwork, type RenderProduct, type RenderProductAttribute, type RenderProductAttributeChoice, type RenderProductCombination, type RenderProductMockup, type RenderProductOptions, type RenderProductRequiredPlacement, RenderSession, type RenderSessionOptions, type RenderState, type SdkConfig, type SeamlessPattern, type SearchDesignsOptions, type SignedUrlResponse, type SnowconeClient, SnowconeSdkError, type SnowconeSdkErrorCode, StandardComponents, StandardEvents, StateManager, type StateManagerOptions, type StateMiddleware, type StateSelector, type StateSubscriber, type StateUpdater, Styles, SvelteAdapter, SwatchUtils, type TagName, TemplateBuilder, type TemplateNode, type TemplateNodeType, type TemplateRenderer, type TextDescriptor, type TileCount, UniversalContextProvider, type UserSelection, type ValidationError, type ValidationResult, VueAdapter, assertVariantSelected, autoRegister, bffSigner, buildMockupUrl, componentRegistry, createAddToCartEvent, createAddToCartHandler, createCartDetail, createClient, createContextProvider, createDesignForPlacements, createDesignState, createErrorHandler, createEventManager, createLifecycle, createLitComponent, createProductContext, createProductLoader, createPropertyManager, createStateHook, createStateStore, createSvelteComponent, createUniversalProvider, createVueComponent, describeArtSelector, describeProductArtAlignment, describeProductImage, describeProductOptions, describeProductPrice, describeProductTitle, extractProductId, fetchMockupImage, fetchRealtimeGrant, filterImagePlacements, findClosestSnapPoint, findVariantForSelection, formatPrice, formatValidationErrors, getBuyUrl, getDefaultVariantId, getEffectiveAlignment, getIncompleteSelectionMessage, getMissingSelections, getMockupUrl, getOptionRenderType, getProduct, getSelectionDisplayText, getSnapPoints, getVariant, handleOptionChange, imageKindOf, isSelectionComplete, isSnowconeSdkError, isValidAlignment, isValidTileCount, listProducts, mintRealtimeGrant, mockupUrl, normalizeChoice, prepareOptionRenderData, registerStandardComponents, resolveMockupId, resolveVariantId, retryOperation, searchDesigns, simulateCartOperation, toCombinations, toOptionAttributes, useFrameworkAdapter as useVueAdapter, validateAlignment, validateDesignElement, validateEffects, validateImageUrl, validateMockupOptions, validateProductSelection, validateProductSpec, validateRequiredOptions, validateTileCount, warnVariantNotSelected, withContext, withErrorHandling, withSyncErrorHandling };
package/dist/index.d.ts CHANGED
@@ -96,6 +96,27 @@ interface CatalogProduct {
96
96
  autoFilledByVariant: boolean;
97
97
  }[];
98
98
  defaultGvid?: string | null;
99
+ /**
100
+ * ADR-0086: marks an album/book product whose single page placement repeats. Consumers (edge resolver, buy worker, supplier export) expand `page_1..page_N` on demand from `pageExtent` — catalog documents never enumerate pages. Additive: products without this block are unaffected.
101
+ */
102
+ album?: {
103
+ /**
104
+ * Wire `key` of the repeating page placement (e.g. "page"). Page N is addressed as `<pagePlacement>_N` and resolves to this placement's geometry.
105
+ */
106
+ pagePlacement: string;
107
+ /**
108
+ * Name of the `options.attributes` entry that carries the page count (e.g. "Pages"). An ordinary affectsCombinations axis — combinations stay Size × Pages rows.
109
+ */
110
+ pageAxis: string;
111
+ /**
112
+ * Buyable page counts: min..max in increments of step.
113
+ */
114
+ pageExtent: {
115
+ min: number;
116
+ max: number;
117
+ step: number;
118
+ };
119
+ };
99
120
  }
100
121
 
101
122
  /**
@@ -227,6 +248,13 @@ interface GetMockupUrlOptions {
227
248
  * params. Takes precedence over `asset`.
228
249
  */
229
250
  design?: Design;
251
+ /**
252
+ * Catalog design reference (ADR-0086): a `pairingId` or `slug` from the
253
+ * public designs catalog (`searchDesigns`). Emitted as `design=` — the
254
+ * resolver injects the published components server-side and the render is
255
+ * FREE (no usage charge). Mutually exclusive with `asset`/`design`.
256
+ */
257
+ designRef?: string;
230
258
  /**
231
259
  * Variant option picks: attribute name → choice label (e.g. `{ size: "m" }`).
232
260
  * Emitted as `opt.<attr>`. Matched case-insensitively by the resolver.
@@ -1194,6 +1222,93 @@ declare function retryOperation<T>(operation: () => Promise<T>, options?: {
1194
1222
  onRetry?: (attempt: number, error: Error) => void;
1195
1223
  }): Promise<T>;
1196
1224
 
1225
+ /**
1226
+ * Structured SDK errors (agent-DX decision E3, ADR-0085 plan): every public
1227
+ * throw carries a STABLE `code` plus machine-readable `data`, with the human
1228
+ * message rendered from them. Tests (and agents) assert on `code` + `data`
1229
+ * fields — never on prose substrings.
1230
+ */
1231
+ type SnowconeSdkErrorCode =
1232
+ /** Freshly minted shop not yet visible at the render edge (KV lag). */
1233
+ 'SHOP_NOT_PROPAGATED'
1234
+ /** The shop's asset-origin allowlist denied an asset in the design. */
1235
+ | 'ASSET_FORBIDDEN'
1236
+ /** Any other render failure (server reason in `data.error`). */
1237
+ | 'RENDER_FAILED';
1238
+ declare class SnowconeSdkError extends Error {
1239
+ readonly code: SnowconeSdkErrorCode;
1240
+ readonly data: Record<string, unknown>;
1241
+ constructor(code: SnowconeSdkErrorCode, message: string, data?: Record<string, unknown>);
1242
+ }
1243
+ declare function isSnowconeSdkError(err: unknown): err is SnowconeSdkError;
1244
+
1245
+ /**
1246
+ * Fetch a rendered mockup URL and prove it is a real image — with the
1247
+ * mint→edge propagation lag absorbed (agent-DX decision F2, ADR-0085 plan).
1248
+ *
1249
+ * THE TRAP THIS KILLS: a freshly minted (sandbox) shop takes a few seconds to
1250
+ * propagate to the render edge's KV store. A render request in that window
1251
+ * 404s `"Unknown shop"` — on CORRECT code. Agents (and humans) then debug the
1252
+ * integration instead of waiting. This helper retries that one failure mode
1253
+ * inside a bounded window (~10s by default) and, if the shop still isn't
1254
+ * visible, throws a LOUD structured error naming the propagation cause — so
1255
+ * nobody ever bisects working code over KV lag.
1256
+ *
1257
+ * Every other failure (asset blocked by the shop's asset-origin allowlist,
1258
+ * product not found, non-image response) throws immediately with a stable
1259
+ * `code` + `data` (no retry — they are deterministic).
1260
+ */
1261
+ /** Identify common raster formats by magic bytes; undefined if not an image. */
1262
+ declare function imageKindOf(b: Uint8Array): string | undefined;
1263
+ /** One failed asset, as reported by the render edge (`failedAssets[]`). */
1264
+ interface FailedAsset {
1265
+ url?: string;
1266
+ reason?: string;
1267
+ code?: string;
1268
+ status?: number;
1269
+ }
1270
+ interface MockupImage {
1271
+ /** Always 200-family when this resolves. */
1272
+ status: number;
1273
+ /** 'PNG' | 'JPEG' | 'WebP' | 'AVIF' | 'GIF'. */
1274
+ kind: string;
1275
+ /** The raw encoded image. */
1276
+ bytes: Uint8Array;
1277
+ }
1278
+ interface FetchMockupImageOptions {
1279
+ /**
1280
+ * Total window to keep retrying `"Unknown shop"` (the mint→edge KV
1281
+ * propagation lag) before throwing `SHOP_NOT_PROPAGATED`. Default 10_000ms.
1282
+ * Set 0 to disable the retry entirely.
1283
+ */
1284
+ retryWindowMs?: number;
1285
+ /**
1286
+ * Backoff schedule inside the window (ms between attempts). Exposed mostly
1287
+ * for tests; the default ramps 500 → 2000ms.
1288
+ */
1289
+ retryDelaysMs?: number[];
1290
+ /** Per-attempt fetch timeout. Default 20_000ms. */
1291
+ timeoutMs?: number;
1292
+ /** Override fetch (tests / non-global-fetch runtimes). */
1293
+ fetchImpl?: typeof fetch;
1294
+ /** Override sleeping between retries (tests). */
1295
+ sleep?: (ms: number) => Promise<void>;
1296
+ }
1297
+ /**
1298
+ * Fetch `url` until it yields a real raster image.
1299
+ *
1300
+ * Resolves with the image bytes on success. Throws {@link SnowconeSdkError}:
1301
+ *
1302
+ * - `SHOP_NOT_PROPAGATED` — the edge still answers `"Unknown shop"` after the
1303
+ * retry window. For a freshly minted shop this is KV propagation lag, not a
1304
+ * bug in your code; the message says exactly that.
1305
+ * - `ASSET_FORBIDDEN` — the shop's asset-origin allowlist denied an asset
1306
+ * referenced by the design (`data.failedAssets` names which, and why).
1307
+ * - `RENDER_FAILED` — any other non-image response (`data.error` carries the
1308
+ * server's reason, e.g. "Product not found").
1309
+ */
1310
+ declare function fetchMockupImage(url: string, opts?: FetchMockupImageOptions): Promise<MockupImage>;
1311
+
1197
1312
  /**
1198
1313
  * Context synchronization utilities for managing state updates
1199
1314
  * across React and Web Component implementations
@@ -3144,6 +3259,13 @@ interface SearchDesignsOptions extends Partial<SdkConfig> {
3144
3259
  offset?: number;
3145
3260
  /** Meilisearch filter, e.g. "occasion = 'christmas' AND style = 'watercolor'". */
3146
3261
  filter?: string;
3262
+ /**
3263
+ * Hybrid (semantic + keyword) blend, 0..1. The index carries an embedder
3264
+ * over each design's AI visual caption, so descriptive queries ("pink
3265
+ * cowgirl boots on the moon") match designs whose metadata never said so.
3266
+ * Default 0.5 for non-empty queries; pass 0 for keyword-only.
3267
+ */
3268
+ semanticRatio?: number;
3147
3269
  }
3148
3270
  interface SnowconeClient {
3149
3271
  catalog: {
@@ -3170,4 +3292,4 @@ declare function searchDesigns(query?: string, options?: SearchDesignsOptions):
3170
3292
  */
3171
3293
  declare function createClient(config: SdkConfig): SnowconeClient;
3172
3294
 
3173
- export { AbstractTemplateRenderer, type AddToCartOptions, Animations, type ArtSelectorContext, type ArtSelectorDescriptor, type ArtSelectorOptions, type ArtworkData, type AspectRatio, Attributes, type BaseDescriptor, type BlendConfig, type BuildMockupUrlConfig, type CartDetail, type CatalogDesign, type CatalogListResponse, type CatalogProduct, ClassNames, type ColorDesignElement, ColorPickerUtils, Combination, CommonProps, ComponentContext, type ComponentDefinition, ComponentDescriptor, ComponentEventManager, ComponentFactory, ComponentLifecycle, ComponentLifecycleHooks, type ComponentMetadata, ComponentProps, ComponentRegistry, ComponentState, type ComponentTemplate, ComponentTemplates, type ContainerDescriptor, ContextBridge, type ContextComparator, type ContextConsumer, ContextInjector, type ContextProviderConfig, type ContextSubscriber, ContextSynchronizer, type CreateDesignStateInput, type CreatedDesignState, DEFAULT_ARTWORK_URL, DEFAULT_ASPECT_RATIO, DEFAULT_BUY_BASE, DEFAULT_COLOR, DEFAULT_GRANT_BASE, DEFAULT_MOCKUP_BASE, DEFAULT_PLACEMENT_DIMENSIONS, type Descriptor, type Design, type DesignElement, type DesignGenerationContext, type DesignLike, type DesignsSearchResponse, type Effects, Elements, type ErrorContext, type ErrorHandler, ErrorManager, type EventDefinition, EventDelegator, EventEmitter, EventHandler, type EventListener, type EventPayload, type Fill, Focus, FrameworkAdapter, FrameworkUtilities, type GetMockupUrlOptions, type ImageAlignment, type ImageDesignElement, type LifecycleHook, LifecycleManager, type LifecyclePhase, type LifecycleTransition, LitAdapter, type MaskOverride, type MockupGenerationOptions, MockupResult, type MockupService, type MockupServiceConfig, OptionAttribute, type OptionChoice, type OptionChoiceRenderData, type OptionRenderData, OptionSelection, type Placement, type PlacementDesign, PlacementSettings, type ProductArtAlignmentContext, type ProductArtAlignmentDescriptor, type ProductArtAlignmentOptions, type ProductContext, type ProductContextEvents, ProductContextManager, type ProductData, type ProductFetcher, type ProductImageDescriptor, type ProductImageOptions, ProductLoader, type ProductMockupData, type ProductOptionChoice, type ProductOptionData, type ProductOptionsDescriptor, type ProductOptionsOptions, type ProductPlacement, type ProductPriceDescriptor, type ProductPriceOptions, ProductProps, type ProductSpec, type ProductTitleDescriptor, type ProductTitleOptions, type ProductVariant, type PropDefinition, type PropSchema, type PropType, PropertyManager, REALTIME_WS_URL, type RateLimitState, type RealtimeGrant, RealtimeMockupService, type RegularArtwork, type RenderProduct, type RenderProductAttribute, type RenderProductAttributeChoice, type RenderProductCombination, type RenderProductMockup, type RenderProductOptions, type RenderProductRequiredPlacement, RenderSession, type RenderSessionOptions, type RenderState, type SdkConfig, type SeamlessPattern, type SearchDesignsOptions, type SignedUrlResponse, type SnowconeClient, StandardComponents, StandardEvents, StateManager, type StateManagerOptions, type StateMiddleware, type StateSelector, type StateSubscriber, type StateUpdater, Styles, SvelteAdapter, SwatchUtils, type TagName, TemplateBuilder, type TemplateNode, type TemplateNodeType, type TemplateRenderer, type TextDescriptor, type TileCount, UniversalContextProvider, type UserSelection, type ValidationError, type ValidationResult, VueAdapter, assertVariantSelected, autoRegister, bffSigner, buildMockupUrl, componentRegistry, createAddToCartEvent, createAddToCartHandler, createCartDetail, createClient, createContextProvider, createDesignForPlacements, createDesignState, createErrorHandler, createEventManager, createLifecycle, createLitComponent, createProductContext, createProductLoader, createPropertyManager, createStateHook, createStateStore, createSvelteComponent, createUniversalProvider, createVueComponent, describeArtSelector, describeProductArtAlignment, describeProductImage, describeProductOptions, describeProductPrice, describeProductTitle, extractProductId, fetchRealtimeGrant, filterImagePlacements, findClosestSnapPoint, findVariantForSelection, formatPrice, formatValidationErrors, getBuyUrl, getDefaultVariantId, getEffectiveAlignment, getIncompleteSelectionMessage, getMissingSelections, getMockupUrl, getOptionRenderType, getProduct, getSelectionDisplayText, getSnapPoints, getVariant, handleOptionChange, isSelectionComplete, isValidAlignment, isValidTileCount, listProducts, mintRealtimeGrant, mockupUrl, normalizeChoice, prepareOptionRenderData, registerStandardComponents, resolveMockupId, resolveVariantId, retryOperation, searchDesigns, simulateCartOperation, toCombinations, toOptionAttributes, useFrameworkAdapter as useVueAdapter, validateAlignment, validateDesignElement, validateEffects, validateImageUrl, validateMockupOptions, validateProductSelection, validateProductSpec, validateRequiredOptions, validateTileCount, warnVariantNotSelected, withContext, withErrorHandling, withSyncErrorHandling };
3295
+ export { AbstractTemplateRenderer, type AddToCartOptions, Animations, type ArtSelectorContext, type ArtSelectorDescriptor, type ArtSelectorOptions, type ArtworkData, type AspectRatio, Attributes, type BaseDescriptor, type BlendConfig, type BuildMockupUrlConfig, type CartDetail, type CatalogDesign, type CatalogListResponse, type CatalogProduct, ClassNames, type ColorDesignElement, ColorPickerUtils, Combination, CommonProps, ComponentContext, type ComponentDefinition, ComponentDescriptor, ComponentEventManager, ComponentFactory, ComponentLifecycle, ComponentLifecycleHooks, type ComponentMetadata, ComponentProps, ComponentRegistry, ComponentState, type ComponentTemplate, ComponentTemplates, type ContainerDescriptor, ContextBridge, type ContextComparator, type ContextConsumer, ContextInjector, type ContextProviderConfig, type ContextSubscriber, ContextSynchronizer, type CreateDesignStateInput, type CreatedDesignState, DEFAULT_ARTWORK_URL, DEFAULT_ASPECT_RATIO, DEFAULT_BUY_BASE, DEFAULT_COLOR, DEFAULT_GRANT_BASE, DEFAULT_MOCKUP_BASE, DEFAULT_PLACEMENT_DIMENSIONS, type Descriptor, type Design, type DesignElement, type DesignGenerationContext, type DesignLike, type DesignsSearchResponse, type Effects, Elements, type ErrorContext, type ErrorHandler, ErrorManager, type EventDefinition, EventDelegator, EventEmitter, EventHandler, type EventListener, type EventPayload, type FailedAsset, type FetchMockupImageOptions, type Fill, Focus, FrameworkAdapter, FrameworkUtilities, type GetMockupUrlOptions, type ImageAlignment, type ImageDesignElement, type LifecycleHook, LifecycleManager, type LifecyclePhase, type LifecycleTransition, LitAdapter, type MaskOverride, type MockupGenerationOptions, type MockupImage, MockupResult, type MockupService, type MockupServiceConfig, OptionAttribute, type OptionChoice, type OptionChoiceRenderData, type OptionRenderData, OptionSelection, type Placement, type PlacementDesign, PlacementSettings, type ProductArtAlignmentContext, type ProductArtAlignmentDescriptor, type ProductArtAlignmentOptions, type ProductContext, type ProductContextEvents, ProductContextManager, type ProductData, type ProductFetcher, type ProductImageDescriptor, type ProductImageOptions, ProductLoader, type ProductMockupData, type ProductOptionChoice, type ProductOptionData, type ProductOptionsDescriptor, type ProductOptionsOptions, type ProductPlacement, type ProductPriceDescriptor, type ProductPriceOptions, ProductProps, type ProductSpec, type ProductTitleDescriptor, type ProductTitleOptions, type ProductVariant, type PropDefinition, type PropSchema, type PropType, PropertyManager, REALTIME_WS_URL, type RateLimitState, type RealtimeGrant, RealtimeMockupService, type RegularArtwork, type RenderProduct, type RenderProductAttribute, type RenderProductAttributeChoice, type RenderProductCombination, type RenderProductMockup, type RenderProductOptions, type RenderProductRequiredPlacement, RenderSession, type RenderSessionOptions, type RenderState, type SdkConfig, type SeamlessPattern, type SearchDesignsOptions, type SignedUrlResponse, type SnowconeClient, SnowconeSdkError, type SnowconeSdkErrorCode, StandardComponents, StandardEvents, StateManager, type StateManagerOptions, type StateMiddleware, type StateSelector, type StateSubscriber, type StateUpdater, Styles, SvelteAdapter, SwatchUtils, type TagName, TemplateBuilder, type TemplateNode, type TemplateNodeType, type TemplateRenderer, type TextDescriptor, type TileCount, UniversalContextProvider, type UserSelection, type ValidationError, type ValidationResult, VueAdapter, assertVariantSelected, autoRegister, bffSigner, buildMockupUrl, componentRegistry, createAddToCartEvent, createAddToCartHandler, createCartDetail, createClient, createContextProvider, createDesignForPlacements, createDesignState, createErrorHandler, createEventManager, createLifecycle, createLitComponent, createProductContext, createProductLoader, createPropertyManager, createStateHook, createStateStore, createSvelteComponent, createUniversalProvider, createVueComponent, describeArtSelector, describeProductArtAlignment, describeProductImage, describeProductOptions, describeProductPrice, describeProductTitle, extractProductId, fetchMockupImage, fetchRealtimeGrant, filterImagePlacements, findClosestSnapPoint, findVariantForSelection, formatPrice, formatValidationErrors, getBuyUrl, getDefaultVariantId, getEffectiveAlignment, getIncompleteSelectionMessage, getMissingSelections, getMockupUrl, getOptionRenderType, getProduct, getSelectionDisplayText, getSnapPoints, getVariant, handleOptionChange, imageKindOf, isSelectionComplete, isSnowconeSdkError, isValidAlignment, isValidTileCount, listProducts, mintRealtimeGrant, mockupUrl, normalizeChoice, prepareOptionRenderData, registerStandardComponents, resolveMockupId, resolveVariantId, retryOperation, searchDesigns, simulateCartOperation, toCombinations, toOptionAttributes, useFrameworkAdapter as useVueAdapter, validateAlignment, validateDesignElement, validateEffects, validateImageUrl, validateMockupOptions, validateProductSelection, validateProductSpec, validateRequiredOptions, validateTileCount, warnVariantNotSelected, withContext, withErrorHandling, withSyncErrorHandling };
package/dist/index.js CHANGED
@@ -11,7 +11,7 @@ import {
11
11
  canonicalForSig,
12
12
  normalizeDesignElements,
13
13
  normalizeWidth
14
- } from "./chunk-Z5M4JEZU.js";
14
+ } from "./chunk-IUFDVHRZ.js";
15
15
 
16
16
  // src/validation.ts
17
17
  import { z } from "zod";
@@ -552,6 +552,7 @@ function getMockupUrl(a, b, c) {
552
552
  shop: opts.shop,
553
553
  ...opts.design ? { design: opts.design } : {},
554
554
  ...assetUrl !== void 0 ? { assetUrl } : {},
555
+ ...opts.designRef !== void 0 ? { designRef: opts.designRef } : {},
555
556
  ...opts.options ? { options: opts.options } : {},
556
557
  ...opts.width !== void 0 ? { width: opts.width } : {},
557
558
  ...opts.aspect !== void 0 ? { aspect: opts.aspect } : {},
@@ -2047,6 +2048,109 @@ async function retryOperation(operation, options = {}) {
2047
2048
  throw lastError;
2048
2049
  }
2049
2050
 
2051
+ // src/error/structured.ts
2052
+ var SnowconeSdkError = class extends Error {
2053
+ code;
2054
+ data;
2055
+ constructor(code, message, data = {}) {
2056
+ super(`${code}: ${message}`);
2057
+ this.name = "SnowconeSdkError";
2058
+ this.code = code;
2059
+ this.data = { code, ...data };
2060
+ }
2061
+ };
2062
+ function isSnowconeSdkError(err) {
2063
+ return err instanceof Error && err.name === "SnowconeSdkError" && "code" in err;
2064
+ }
2065
+
2066
+ // src/mockup/fetchMockupImage.ts
2067
+ function imageKindOf(b) {
2068
+ if (b[0] === 137 && b[1] === 80) return "PNG";
2069
+ if (b[0] === 255 && b[1] === 216) return "JPEG";
2070
+ if (b[0] === 71 && b[1] === 73 && b[2] === 70) return "GIF";
2071
+ if (b[0] === 82 && b[1] === 73 && b[2] === 70 && b[3] === 70) return "WebP";
2072
+ if (b.length >= 12 && String.fromCharCode(b[4], b[5], b[6], b[7]) === "ftyp") return "AVIF";
2073
+ return void 0;
2074
+ }
2075
+ var DEFAULT_RETRY_DELAYS_MS = [500, 1e3, 2e3, 2e3, 2e3, 2e3];
2076
+ function parseFailure(status, bytes) {
2077
+ const text = new TextDecoder().decode(bytes).slice(0, 1e3);
2078
+ let error = `HTTP ${status}`;
2079
+ let failedAssets = [];
2080
+ try {
2081
+ const j = JSON.parse(text);
2082
+ error = String(j.error ?? j.message ?? (text || error));
2083
+ if (Array.isArray(j.failedAssets)) failedAssets = j.failedAssets;
2084
+ } catch {
2085
+ if (text) error = text;
2086
+ }
2087
+ return { status, error, failedAssets, bodyText: text };
2088
+ }
2089
+ function isUnknownShop(f) {
2090
+ return /unknown shop/i.test(f.error);
2091
+ }
2092
+ function isAssetForbidden(f) {
2093
+ if (f.failedAssets.some((a) => a.status === 403 || /blocked|forbidden|allowlist|not allowed/i.test(`${a.reason ?? ""} ${a.code ?? ""}`))) {
2094
+ return true;
2095
+ }
2096
+ return /host blocked|allowlist|not an allowed|forbidden/i.test(f.error);
2097
+ }
2098
+ async function fetchMockupImage(url, opts = {}) {
2099
+ const f = opts.fetchImpl ?? globalThis.fetch;
2100
+ const retryWindowMs = opts.retryWindowMs ?? 1e4;
2101
+ const delays = opts.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
2102
+ const timeoutMs = opts.timeoutMs ?? 2e4;
2103
+ const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
2104
+ let waited = 0;
2105
+ let attempt = 0;
2106
+ let last = null;
2107
+ for (; ; ) {
2108
+ const controller = new AbortController();
2109
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
2110
+ let failure;
2111
+ try {
2112
+ const res = await f(url, { signal: controller.signal });
2113
+ const bytes = new Uint8Array(await res.arrayBuffer());
2114
+ const kind = imageKindOf(bytes);
2115
+ if (res.ok && kind) {
2116
+ return { status: res.status, kind, bytes };
2117
+ }
2118
+ failure = parseFailure(res.status, bytes);
2119
+ } catch (err) {
2120
+ const message = err instanceof Error ? err.message : String(err);
2121
+ failure = { status: 0, error: `network error fetching ${url}: ${message}`, failedAssets: [], bodyText: "" };
2122
+ } finally {
2123
+ clearTimeout(timer);
2124
+ }
2125
+ last = failure;
2126
+ if (isAssetForbidden(failure)) {
2127
+ throw new SnowconeSdkError(
2128
+ "ASSET_FORBIDDEN",
2129
+ `the shop's asset-origin allowlist denied an asset in this design: ${failure.error}. Add the asset's origin to the shop's allowed asset origins (or host the asset on the shop's storage origin) and retry \u2014 the URL and your code are otherwise fine.`,
2130
+ { url, status: failure.status, failedAssets: failure.failedAssets }
2131
+ );
2132
+ }
2133
+ const nextDelay = delays[Math.min(attempt, delays.length - 1)] ?? 2e3;
2134
+ const canRetry = isUnknownShop(failure) && waited + nextDelay <= retryWindowMs;
2135
+ if (!canRetry) break;
2136
+ await sleep(nextDelay);
2137
+ waited += nextDelay;
2138
+ attempt += 1;
2139
+ }
2140
+ if (last && isUnknownShop(last)) {
2141
+ throw new SnowconeSdkError(
2142
+ "SHOP_NOT_PROPAGATED",
2143
+ `the render edge still answers "Unknown shop" after ${Math.round(retryWindowMs / 1e3)}s of retries. For a freshly minted shop this is edge KV propagation lag (normally ~1\u20133s) \u2014 your code is not the problem. If this shop is NOT freshly minted, the shop id is wrong: confirm the publishable shop id (shop.id) you passed.`,
2144
+ { url, status: last.status, retriedMs: waited, cause: "kv-propagation" }
2145
+ );
2146
+ }
2147
+ throw new SnowconeSdkError(
2148
+ "RENDER_FAILED",
2149
+ `mockup URL did not render an image: ${last?.error ?? "unknown error"}`,
2150
+ { url, status: last?.status ?? 0, error: last?.error, failedAssets: last?.failedAssets ?? [] }
2151
+ );
2152
+ }
2153
+
2050
2154
  // src/context/synchronization.ts
2051
2155
  var ContextSynchronizer = class {
2052
2156
  constructor(options = {}) {
@@ -4996,7 +5100,15 @@ async function searchDesigns(query = "", options) {
4996
5100
  q: query,
4997
5101
  limit: options?.limit || 50,
4998
5102
  ...options?.offset ? { offset: options.offset } : {},
4999
- ...options?.filter ? { filter: options.filter } : {}
5103
+ ...options?.filter ? { filter: options.filter } : {},
5104
+ // Hybrid semantic search over the AI visual captions (default on for
5105
+ // real queries; an empty q is a plain listing).
5106
+ ...query && (options?.semanticRatio ?? 0.5) > 0 ? {
5107
+ hybrid: {
5108
+ embedder: "default",
5109
+ semanticRatio: options?.semanticRatio ?? 0.5
5110
+ }
5111
+ } : {}
5000
5112
  })
5001
5113
  });
5002
5114
  if (!res.ok) throw new Error(`searchDesigns failed: ${res.status}`);
@@ -5055,6 +5167,7 @@ export {
5055
5167
  REALTIME_WS_URL,
5056
5168
  RealtimeMockupService,
5057
5169
  RenderSession,
5170
+ SnowconeSdkError,
5058
5171
  StandardComponents,
5059
5172
  StandardEvents,
5060
5173
  StateManager,
@@ -5101,6 +5214,7 @@ export {
5101
5214
  describeProductPrice,
5102
5215
  describeProductTitle,
5103
5216
  extractProductId,
5217
+ fetchMockupImage,
5104
5218
  fetchRealtimeGrant,
5105
5219
  filterImagePlacements,
5106
5220
  findBestCombination,
@@ -5121,8 +5235,10 @@ export {
5121
5235
  getSnapPoints,
5122
5236
  getVariant,
5123
5237
  handleOptionChange,
5238
+ imageKindOf,
5124
5239
  isOptionAvailable,
5125
5240
  isSelectionComplete,
5241
+ isSnowconeSdkError,
5126
5242
  isValidAlignment,
5127
5243
  isValidTileCount,
5128
5244
  listProducts,
package/dist/server.cjs CHANGED
@@ -34,7 +34,25 @@ var PARAMS = {
34
34
  shop: "shop",
35
35
  asset: "asset",
36
36
  assets: "assets",
37
+ /**
38
+ * Render a catalog design by reference (ADR-0086): `design=<pairingId|slug>`.
39
+ * The resolver looks the design up in the public `snowcone-designs` index
40
+ * (membership = license) and injects its asset components server-side, so no
41
+ * raw asset URL crosses the wire and no origin allowlisting is involved.
42
+ * Catalog renders are FREE — mutually exclusive with `asset`/`asset.<key>`/
43
+ * `color.<key>` (free = the design as published).
44
+ */
45
+ design: "design",
37
46
  placement: "placement",
47
+ /**
48
+ * Album page selector (ADR-0086 §5): `page=N` (positive integer) picks which
49
+ * page/spread of an album product a mockup renders. Only valid on products
50
+ * whose catalog entry carries an `album` block — the edge resolver maps page
51
+ * N onto the repeating page placement (`page_N` → the geometry of
52
+ * `album.pagePlacement`); the catalog never enumerates `page_1…page_100` and
53
+ * rendercenter is unchanged.
54
+ */
55
+ page: "page",
38
56
  variant: "variant",
39
57
  mockup: "mockup",
40
58
  width: "width",
@@ -55,8 +73,10 @@ var PARAMS = {
55
73
  };
56
74
  var PUBLIC_PARAM_NAMES = [
57
75
  PARAMS.asset,
76
+ PARAMS.design,
58
77
  PARAMS.shop,
59
78
  PARAMS.placement,
79
+ PARAMS.page,
60
80
  PARAMS.variant,
61
81
  PARAMS.mockup,
62
82
  PARAMS.width,
package/dist/server.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  canonicalForSig,
3
3
  signDevSig
4
- } from "./chunk-Z5M4JEZU.js";
4
+ } from "./chunk-IUFDVHRZ.js";
5
5
 
6
6
  // src/server.ts
7
7
  function json(body, status = 200) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@snowcone-app/sdk",
3
- "version": "0.14.0",
3
+ "version": "0.16.0",
4
4
  "description": "Snowcone SDK for product mockups and print-on-demand",
5
5
  "keywords": [
6
6
  "merch",
@@ -85,7 +85,7 @@
85
85
  "tsup": "^8.1.0",
86
86
  "typescript": "^5.5.4",
87
87
  "vitest": "^2.0.5",
88
- "@snowcone-app/mockup-url": "0.1.1"
88
+ "@snowcone-app/mockup-url": "0.2.0"
89
89
  },
90
90
  "engines": {
91
91
  "node": ">=18"