@snowcone-app/mockup-resolver 1.0.9 → 1.0.10

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,12 @@
1
1
  # @snowcone-app/mockup-resolver
2
2
 
3
+ ## 1.0.10
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [[`45c7428`](https://github.com/snowcone-app/snowcone-monorepo/commit/45c7428ae50fda88af2c26daff5d169156e7a141)]:
8
+ - @snowcone-app/mockup-url@0.5.0
9
+
3
10
  ## 1.0.9
4
11
 
5
12
  ### Patch Changes
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@snowcone-app/mockup-resolver",
3
- "version": "1.0.9",
3
+ "version": "1.0.10",
4
4
  "description": "URL signing and verification Cloudflare Worker",
5
5
  "main": "dist/index.js",
6
6
  "author": "",
7
7
  "license": "ISC",
8
8
  "dependencies": {
9
- "@snowcone-app/mockup-url": "0.4.0"
9
+ "@snowcone-app/mockup-url": "0.5.0"
10
10
  },
11
11
  "devDependencies": {
12
12
  "@cloudflare/workers-types": "^4.20250303.0",
package/src/index.ts CHANGED
@@ -1014,9 +1014,13 @@ import {
1014
1014
  fetchProduct,
1015
1015
  looksLikeResolveRequest,
1016
1016
  resolveAlbumPagePlacement,
1017
+ resolveBundleScene,
1017
1018
  resolveDefaults,
1018
1019
  resolveVariant,
1019
1020
  unknownOptionPick,
1021
+ type BundleScene,
1022
+ type ResolveDefaults,
1023
+ type VariantResolution,
1020
1024
  type ResolvedPlacement,
1021
1025
  } from "./resolve";
1022
1026
  import { rejectUnknownPublicParams } from "./public-params";
@@ -1683,6 +1687,44 @@ async function handlePublicResolve(
1683
1687
  );
1684
1688
  }
1685
1689
  }
1690
+ // 4-bundle (ADR-0099 slice 3). A bundle record resolves per SLOT: picks
1691
+ // decide which alternative's placements exist and which mockup fits, then
1692
+ // each slot resolves its own SKU through the member's combinations
1693
+ // (`variant.<role>=`, `opt.<role>.<attr>=`). The box URL keys its cache on
1694
+ // the per-role render-gvid set (one deterministic token), and the elements
1695
+ // carry role-scoped placement keys. Bare `variant=`/`opt.<attr>=` on a
1696
+ // bundle name no slot and are refused with the roles listed; bundle params
1697
+ // on a non-bundle are refused too — never silently ignored.
1698
+ let bundleScene: BundleScene | null = null;
1699
+ if (product.bundle) {
1700
+ if (catalogDesign) {
1701
+ return errResp(
1702
+ 400,
1703
+ `design= is not yet supported on bundle ${productCode} — bundle pairings land with the cart work (ADR-0099 slice 5). Render with asset= / asset.<role>.<placement>= for now.`,
1704
+ "E_BUNDLE_DESIGN_UNSUPPORTED"
1705
+ );
1706
+ }
1707
+ if (pagePlacement) {
1708
+ return errResp(400, `page= is not valid on bundle ${productCode} (bundles have no album block)`);
1709
+ }
1710
+ const r = resolveBundleScene(product, {
1711
+ picks: parsed.picks ?? {},
1712
+ variants: parsed.variants ?? {},
1713
+ options: optionPicks,
1714
+ variantOverride,
1715
+ mockupOverride,
1716
+ });
1717
+ if (!r.ok) return errResp(r.status, r.message, r.code);
1718
+ bundleScene = r.scene;
1719
+ } else if (parsed.picks || parsed.variants) {
1720
+ return errResp(
1721
+ 400,
1722
+ `pick.<role>= and variant.<role>= are bundle parameters — ${productCode} is not a bundle. ` +
1723
+ `Use variant=<gvid> and opt.<attribute>=<choice>.`,
1724
+ "E_NOT_A_BUNDLE"
1725
+ );
1726
+ }
1727
+
1686
1728
  // 4a. Resolve the variant from option picks (both catalog shapes) + the
1687
1729
  // render-only optionSelections rendercenter needs. resolveDefaults then supplies
1688
1730
  // the mockup scene and a default placement (for the bare-asset case).
@@ -1691,39 +1733,56 @@ async function handlePublicResolve(
1691
1733
  // box and render with no underlay; an unknown combination choice fell back
1692
1734
  // to the default variant — both silently (ADR-0099 lab product probe,
1693
1735
  // 2026-09-06). Named, with the valid values, like unknown placement keys.
1694
- const badPick = unknownOptionPick(product, optionPicks);
1695
- if (badPick) {
1696
- return badPick.validChoices
1697
- ? errResp(
1698
- 400,
1699
- `Unknown choice "${badPick.choice}" for option "${badPick.attribute}" on ${productCode}. ` +
1700
- `Valid choices: ${badPick.validChoices.join(", ")}.`,
1701
- "E_OPTION_CHOICE_NOT_FOUND"
1702
- )
1703
- : errResp(
1704
- 400,
1705
- `Unknown option "${badPick.attribute}" on ${productCode}. ` +
1706
- (badPick.validAttributes.length
1707
- ? `Valid options: ${badPick.validAttributes.join(", ")}.`
1708
- : `This product has no options.`),
1709
- "E_OPTION_NOT_FOUND"
1710
- );
1711
- }
1712
- const vr = resolveVariant(product, optionPicks, variantOverride);
1713
- if (!vr) {
1714
- return errResp(422, `Product ${productCode} has no renderable combination`);
1715
- }
1716
- const scene = resolveDefaults(product, {
1717
- variant: vr.variantId,
1718
- mockupId: mockupOverride,
1719
- placement: placementOverride,
1720
- });
1721
- if (!scene) {
1722
- return errResp(422, `Product ${productCode} has no renderable combination`);
1736
+ let vr: VariantResolution;
1737
+ let scene: ResolveDefaults;
1738
+ if (bundleScene) {
1739
+ vr = { variantId: bundleScene.variantToken, optionSelections: bundleScene.optionSelections };
1740
+ scene = {
1741
+ variantId: bundleScene.variantToken,
1742
+ mockupId: bundleScene.mockupId,
1743
+ placement: bundleScene.placements[0],
1744
+ };
1745
+ } else {
1746
+ const badPick = unknownOptionPick(product, optionPicks);
1747
+ if (badPick) {
1748
+ return badPick.validChoices
1749
+ ? errResp(
1750
+ 400,
1751
+ `Unknown choice "${badPick.choice}" for option "${badPick.attribute}" on ${productCode}. ` +
1752
+ `Valid choices: ${badPick.validChoices.join(", ")}.`,
1753
+ "E_OPTION_CHOICE_NOT_FOUND"
1754
+ )
1755
+ : errResp(
1756
+ 400,
1757
+ `Unknown option "${badPick.attribute}" on ${productCode}. ` +
1758
+ (badPick.validAttributes.length
1759
+ ? `Valid options: ${badPick.validAttributes.join(", ")}.`
1760
+ : `This product has no options.`),
1761
+ "E_OPTION_NOT_FOUND"
1762
+ );
1763
+ }
1764
+ const resolvedVariant = resolveVariant(product, optionPicks, variantOverride);
1765
+ if (!resolvedVariant) {
1766
+ return errResp(422, `Product ${productCode} has no renderable combination`);
1767
+ }
1768
+ vr = resolvedVariant;
1769
+ const resolvedScene = resolveDefaults(product, {
1770
+ variant: vr.variantId,
1771
+ mockupId: mockupOverride,
1772
+ placement: placementOverride,
1773
+ });
1774
+ if (!resolvedScene) {
1775
+ return errResp(422, `Product ${productCode} has no renderable combination`);
1776
+ }
1777
+ scene = resolvedScene;
1778
+ // page=N selects which album page feeds the scene: the resolved default
1779
+ // placement becomes the repeating page placement's geometry.
1780
+ if (pagePlacement) scene.placement = pagePlacement;
1723
1781
  }
1724
- // page=N selects which album page feeds the scene: the resolved default
1725
- // placement becomes the repeating page placement's geometry.
1726
- if (pagePlacement) scene.placement = pagePlacement;
1782
+ // The placements artwork resolves against: a bundle's are narrowed to the
1783
+ // pick set (so `top.front` is the picked alternative's Front and the
1784
+ // E_PLACEMENT_NOT_FOUND list names only keys that exist for these picks).
1785
+ const renderProduct = bundleScene ? { ...product, placements: bundleScene.placements } : product;
1727
1786
 
1728
1787
  // 4b. Build the design elements: one base broadcast across every placement
1729
1788
  // plus per-placement overrides (ADR-0089), or a catalog design verbatim.
@@ -1737,8 +1796,8 @@ async function handlePublicResolve(
1737
1796
  // the repeating placement's geometry, ADR-0086); null for everything else,
1738
1797
  // so non-album products behave exactly as before.
1739
1798
  const findPlacement = (k: string) =>
1740
- product.placements.find((p) => p.key === k) ??
1741
- resolveAlbumPagePlacement(product, k);
1799
+ renderProduct.placements.find((p) => p.key === k) ??
1800
+ resolveAlbumPagePlacement(renderProduct, k);
1742
1801
 
1743
1802
  const designElements: DesignElement[] = [];
1744
1803
  if (catalogDesign) {
@@ -1778,7 +1837,7 @@ async function handlePublicResolve(
1778
1837
  // override key fails loudly (E_PLACEMENT_NOT_FOUND, listing valid keys).
1779
1838
  // The base broadcast fans out across `product.placements` directly — it no
1780
1839
  // longer rides the single default-placement resolution.
1781
- const assembled = assembleArtwork(product, {
1840
+ const assembled = assembleArtwork(renderProduct, {
1782
1841
  asset,
1783
1842
  design,
1784
1843
  house,
package/src/resolve.ts CHANGED
@@ -63,6 +63,38 @@ export interface MeiliConfig {
63
63
  index: string;
64
64
  }
65
65
 
66
+ interface RawOptions {
67
+ attributes?: Record<
68
+ string,
69
+ { affectsCombinations?: boolean; choices?: { label?: string }[] }
70
+ >;
71
+ // Flat rows: each is `{ <AttrName>: <choiceLabel>, …, price, variantId }`.
72
+ combinations?: Array<Record<string, unknown>>;
73
+ }
74
+
75
+ interface RawVariant {
76
+ gvid?: string;
77
+ id?: string;
78
+ /** The RENDER gvid (variant_id_for_mockups) when it differs from the SKU gvid — ADR-0099 V1. */
79
+ gvidForMockup?: string | null;
80
+ }
81
+
82
+ /** ADR-0099: the published `bundle` block (catalog/src/bundle.ts `pareBundleForDoc`). */
83
+ interface RawBundle {
84
+ members?: Array<{
85
+ role?: string;
86
+ required?: boolean;
87
+ products?: Array<{
88
+ productId?: string;
89
+ defaultGvid?: string | null;
90
+ variants?: RawVariant[];
91
+ options?: RawOptions;
92
+ }>;
93
+ }>;
94
+ priceRule?: unknown;
95
+ uncoveredPickSets?: unknown;
96
+ }
97
+
66
98
  interface RawProduct {
67
99
  id: string;
68
100
  placements?: {
@@ -71,23 +103,20 @@ interface RawProduct {
71
103
  type?: string | null;
72
104
  width?: number;
73
105
  height?: number;
106
+ /** ADR-0099: bundle member slot + product this placement belongs to. */
107
+ role?: string;
108
+ memberProductId?: string;
74
109
  }[];
75
- variants?: { gvid?: string; id?: string }[];
76
- mockups?: { id: string; gvids?: string[] }[];
110
+ variants?: RawVariant[];
111
+ mockups?: { id: string; gvids?: string[]; picks?: Record<string, string> }[];
77
112
  defaultGvid?: string | null;
78
- options?: {
79
- attributes?: Record<
80
- string,
81
- { affectsCombinations?: boolean; choices?: { label?: string }[] }
82
- >;
83
- // Flat rows: each is `{ <AttrName>: <choiceLabel>, …, price, variantId }`.
84
- combinations?: Array<Record<string, unknown>>;
85
- };
113
+ options?: RawOptions;
86
114
  album?: {
87
115
  pagePlacement?: string;
88
116
  pageAxis?: string;
89
117
  pageExtent?: { min?: number; max?: number; step?: number };
90
118
  };
119
+ bundle?: RawBundle | null;
91
120
  }
92
121
 
93
122
  /**
@@ -105,12 +134,38 @@ export interface AlbumBlock {
105
134
  }
106
135
 
107
136
  export interface ResolvedPlacement {
108
- /** URL-safe slug (catalog `key`, or a slug derived from `label` as a fallback). */
137
+ /** URL-safe slug (catalog `key`, or a slug derived from `label` as a fallback).
138
+ * On a bundle record: the role-scoped wire key `<role>.<key>` (ADR-0099 D3). */
109
139
  key: string;
110
140
  label: string;
111
141
  type: "image" | "color";
112
142
  width: number;
113
143
  height: number;
144
+ /** ADR-0099: the bundle slot this placement belongs to; absent on single products. */
145
+ role?: string;
146
+ /** ADR-0099: the member product (alternative) this placement belongs to. */
147
+ memberProductId?: string;
148
+ }
149
+
150
+ /** ADR-0099: one alternative product of a bundle slot, with what per-role variant resolution needs. */
151
+ export interface ResolvedBundleAlternative {
152
+ productId: string;
153
+ defaultGvid: string | null;
154
+ variants: { gvid: string; gvidForMockup: string | null }[];
155
+ attributes: Record<string, { affectsCombinations: boolean; choices: string[] }>;
156
+ combinations: { variantId: string; options: Record<string, string> }[];
157
+ }
158
+
159
+ export interface ResolvedBundleMember {
160
+ role: string;
161
+ required: boolean;
162
+ /** Alternatives; `[0]` is the default pick. Never empty. */
163
+ products: ResolvedBundleAlternative[];
164
+ }
165
+
166
+ export interface ResolvedBundle {
167
+ members: ResolvedBundleMember[];
168
+ priceRule: unknown;
114
169
  }
115
170
 
116
171
  export interface ResolvedProduct {
@@ -124,8 +179,8 @@ export interface ResolvedProduct {
124
179
  * Falls back to `version` for records published before it existed. */
125
180
  renderVersion: string;
126
181
  id: string;
127
- variants: { gvid: string }[];
128
- mockups: { id: string; gvids: string[] }[];
182
+ variants: { gvid: string; gvidForMockup?: string | null }[];
183
+ mockups: { id: string; gvids: string[]; picks?: Record<string, string> | null }[];
129
184
  placements: ResolvedPlacement[];
130
185
  defaultGvid: string | null;
131
186
  /** Attribute name → metadata (whether it selects a SKU + its choice labels). */
@@ -134,8 +189,13 @@ export interface ResolvedProduct {
134
189
  combinations: { variantId: string; options: Record<string, string> }[];
135
190
  /** The album block (ADR-0086), or null for ordinary products. */
136
191
  album: AlbumBlock | null;
192
+ /** The bundle block (ADR-0099), or null for ordinary products. */
193
+ bundle?: ResolvedBundle | null;
137
194
  }
138
195
 
196
+ /** The subset of a product that variant/option resolution reads — a bundle member alternative satisfies it too. */
197
+ export type VariantResolvable = Pick<ResolvedProduct, "attributes" | "combinations" | "defaultGvid" | "variants">;
198
+
139
199
  export interface ResolveDefaults {
140
200
  variantId: string;
141
201
  mockupId: string;
@@ -269,6 +329,17 @@ export type AssembleArtworkResult =
269
329
  | { ok: true; elements: DesignElement[] }
270
330
  | { ok: false; status: number; code: string; message: string };
271
331
 
332
+ /**
333
+ * The `placement` a render element carries to the box. Single products: the
334
+ * catalog label (what the box's masks are labelled with). Bundle placements
335
+ * (ADR-0099 D2/D3): the role-scoped wire key — two members both have a
336
+ * "Front", so the label is ambiguous; the render box maps the key back to
337
+ * the member placement's label + printable before matching masks.
338
+ */
339
+ export function wirePlacement(pl: ResolvedPlacement): string {
340
+ return pl.role ? pl.key : pl.label;
341
+ }
342
+
272
343
  /** Build one image/color `DesignElement` for a placement from a parsed fill. */
273
344
  function elementFromFill(
274
345
  fill: ParsedFill,
@@ -279,7 +350,7 @@ function elementFromFill(
279
350
  return {
280
351
  type: "color",
281
352
  hex: fill.color,
282
- placement: pl.label,
353
+ placement: wirePlacement(pl),
283
354
  width: pl.width,
284
355
  height: pl.height,
285
356
  };
@@ -288,7 +359,7 @@ function elementFromFill(
288
359
  const el: DesignElement = {
289
360
  type: "image",
290
361
  imageUrl: fill.src === DEFAULT_ASSET_TOKEN ? house : fill.src,
291
- placement: pl.label,
362
+ placement: wirePlacement(pl),
292
363
  width: pl.width,
293
364
  height: pl.height,
294
365
  alignment:
@@ -332,7 +403,7 @@ export function assembleArtwork(
332
403
  byKey.set(pl.key, {
333
404
  type: "image",
334
405
  imageUrl: baseUrl,
335
- placement: pl.label,
406
+ placement: wirePlacement(pl),
336
407
  width: pl.width,
337
408
  height: pl.height,
338
409
  alignment: "center",
@@ -394,9 +465,12 @@ export async function fetchProduct(
394
465
  }
395
466
  }
396
467
 
397
- function toResolvedProduct(raw: RawProduct, version: string, renderVersion: string = version): ResolvedProduct {
398
-
399
- const rawAttrs = raw.options?.attributes ?? {};
468
+ /** Normalize a raw catalog `options` block into attribute metadata + SKU rows. */
469
+ function normalizeOptions(options: RawOptions | undefined): {
470
+ attributes: ResolvedProduct["attributes"];
471
+ combinations: ResolvedProduct["combinations"];
472
+ } {
473
+ const rawAttrs = options?.attributes ?? {};
400
474
  const attributes: ResolvedProduct["attributes"] = {};
401
475
  for (const [name, meta] of Object.entries(rawAttrs)) {
402
476
  attributes[name] = {
@@ -410,36 +484,87 @@ function toResolvedProduct(raw: RawProduct, version: string, renderVersion: stri
410
484
  const attributeNames = Object.keys(attributes);
411
485
 
412
486
  const combinations: ResolvedProduct["combinations"] = [];
413
- for (const row of raw.options?.combinations ?? []) {
487
+ for (const row of options?.combinations ?? []) {
414
488
  const variantId = typeof row.variantId === "string" ? row.variantId : "";
415
489
  if (!variantId) continue;
416
- const options: Record<string, string> = {};
490
+ const opts: Record<string, string> = {};
417
491
  for (const name of attributeNames) {
418
492
  const v = row[name];
419
- if (typeof v === "string") options[name] = v;
493
+ if (typeof v === "string") opts[name] = v;
420
494
  }
421
- combinations.push({ variantId, options });
495
+ combinations.push({ variantId, options: opts });
422
496
  }
497
+ return { attributes, combinations };
498
+ }
499
+
500
+ function normalizeVariants(raw: RawVariant[] | undefined): { gvid: string; gvidForMockup: string | null }[] {
501
+ return (raw ?? [])
502
+ .map((v) => ({
503
+ gvid: v.gvid ?? v.id ?? "",
504
+ gvidForMockup: typeof v.gvidForMockup === "string" && v.gvidForMockup ? v.gvidForMockup : null,
505
+ }))
506
+ .filter((v) => v.gvid);
507
+ }
508
+
509
+ /**
510
+ * Normalize the published `bundle` block (ADR-0099). Null unless it carries
511
+ * at least one slot with at least one alternative — a malformed block makes
512
+ * the product behave like an ordinary (non-bundle) product, which then fails
513
+ * loudly on its empty placements rather than half-rendering.
514
+ */
515
+ export function normalizeBundle(raw: RawBundle | null | undefined): ResolvedBundle | null {
516
+ if (!raw || !Array.isArray(raw.members) || raw.members.length === 0) return null;
517
+ const members: ResolvedBundleMember[] = [];
518
+ for (const m of raw.members) {
519
+ if (!m || typeof m.role !== "string" || !m.role) continue;
520
+ const products: ResolvedBundleAlternative[] = [];
521
+ for (const p of m.products ?? []) {
522
+ if (!p || typeof p.productId !== "string" || !p.productId) continue;
523
+ const { attributes, combinations } = normalizeOptions(p.options);
524
+ products.push({
525
+ productId: p.productId,
526
+ defaultGvid: typeof p.defaultGvid === "string" && p.defaultGvid ? p.defaultGvid : null,
527
+ variants: normalizeVariants(p.variants),
528
+ attributes,
529
+ combinations,
530
+ });
531
+ }
532
+ if (products.length === 0) continue;
533
+ members.push({ role: m.role, required: m.required !== false, products });
534
+ }
535
+ if (members.length === 0) return null;
536
+ return { members, priceRule: raw.priceRule ?? null };
537
+ }
538
+
539
+ function toResolvedProduct(raw: RawProduct, version: string, renderVersion: string = version): ResolvedProduct {
540
+ const { attributes, combinations } = normalizeOptions(raw.options);
423
541
 
424
542
  const resolved: ResolvedProduct = {
425
543
  version,
426
544
  renderVersion,
427
545
  id: raw.id,
428
- variants: (raw.variants ?? [])
429
- .map((v) => ({ gvid: v.gvid ?? v.id ?? "" }))
430
- .filter((v) => v.gvid),
431
- mockups: (raw.mockups ?? []).map((m) => ({ id: m.id, gvids: m.gvids ?? [] })),
546
+ variants: normalizeVariants(raw.variants),
547
+ mockups: (raw.mockups ?? []).map((m) => ({
548
+ id: m.id,
549
+ gvids: m.gvids ?? [],
550
+ ...(m.picks && typeof m.picks === "object" ? { picks: m.picks } : {}),
551
+ })),
432
552
  placements: (raw.placements ?? []).map((p) => ({
433
553
  key: p.key && p.key.length > 0 ? p.key : slugify(p.label),
434
554
  label: p.label,
435
555
  type: p.type === "color" ? "color" : "image",
436
556
  width: p.width ?? 4000,
437
557
  height: p.height ?? 4000,
558
+ ...(typeof p.role === "string" && p.role ? { role: p.role } : {}),
559
+ ...(typeof p.memberProductId === "string" && p.memberProductId
560
+ ? { memberProductId: p.memberProductId }
561
+ : {}),
438
562
  })),
439
563
  defaultGvid: raw.defaultGvid ?? null,
440
564
  attributes,
441
565
  combinations,
442
566
  album: normalizeAlbum(raw.album),
567
+ bundle: normalizeBundle(raw.bundle),
443
568
  };
444
569
 
445
570
  return resolved;
@@ -497,7 +622,7 @@ export interface UnknownOptionPick {
497
622
  * keys — fail loudly, name the valid values (ADR-0089 house style).
498
623
  */
499
624
  export function unknownOptionPick(
500
- product: ResolvedProduct,
625
+ product: VariantResolvable,
501
626
  picks: Record<string, string>
502
627
  ): UnknownOptionPick | null {
503
628
  const attrs = product.attributes ?? {};
@@ -529,7 +654,7 @@ export function unknownOptionPick(
529
654
  * Returns null only if no variant can be determined at all.
530
655
  */
531
656
  export function resolveVariant(
532
- product: ResolvedProduct,
657
+ product: VariantResolvable,
533
658
  picks: Record<string, string>,
534
659
  variantOverride?: string
535
660
  ): VariantResolution | null {
@@ -575,3 +700,196 @@ export function resolveVariant(
575
700
 
576
701
  return { variantId, optionSelections };
577
702
  }
703
+
704
+ // ─── Bundles (ADR-0099): picks, per-role variants, the mockup, the placements ──
705
+
706
+ export interface BundleSceneInput {
707
+ /** `pick.<role>=<productCode>` — which alternative fills each slot (default: `products[0]`). */
708
+ picks: Record<string, string>;
709
+ /** `variant.<role>=<gvid>` — the SKU per slot. */
710
+ variants: Record<string, string>;
711
+ /** Every `opt.*` pick as parsed; on a bundle each key must be `<role>.<attribute>`. */
712
+ options: Record<string, string>;
713
+ /** A bare `variant=` (rejected on bundles — it names no slot). */
714
+ variantOverride?: string;
715
+ mockupOverride?: string;
716
+ }
717
+
718
+ export interface BundleScene {
719
+ /** The resolved pick set: role → member product code. */
720
+ picks: Record<string, string>;
721
+ /** role → the SKU gvid (what a cart line needs) and the RENDER gvid the box keys on (V1). */
722
+ variantByRole: Record<string, { skuGvid: string; renderGvid: string }>;
723
+ /** Render-only picks, role-qualified (`"<role>.<attr>": choice`). */
724
+ optionSelections: Record<string, string>;
725
+ mockupId: string;
726
+ /** The picked alternatives' placements — the record's placements narrowed to this pick set. */
727
+ placements: ResolvedPlacement[];
728
+ /**
729
+ * The per-role render-gvid set as ONE token, `role:gvid,…` sorted by role —
730
+ * the value the box URL carries in `variant=` so the box's render cache and
731
+ * scene keys are distinct per member-variant set (V1). The box parses it
732
+ * per role once rc-6 lands; until then it is an opaque, deterministic key.
733
+ */
734
+ variantToken: string;
735
+ }
736
+
737
+ export type BundleSceneResult =
738
+ | { ok: true; scene: BundleScene }
739
+ | { ok: false; status: number; code: string; message: string };
740
+
741
+ /** `role:gvid,…` sorted by role — deterministic (the URL is a cache key). */
742
+ export function bundleVariantToken(variantByRole: Record<string, { renderGvid: string }>): string {
743
+ return Object.keys(variantByRole)
744
+ .sort()
745
+ .map((role) => `${role}:${variantByRole[role].renderGvid}`)
746
+ .join(",");
747
+ }
748
+
749
+ /**
750
+ * Resolve a bundle render (ADR-0099 D3/V1, swappable-slots amendment):
751
+ * picks first (they decide which placements exist and which mockup fits),
752
+ * then one variant per slot from `variant.<role>` / `opt.<role>.<attr>`
753
+ * through the member's own combinations, then the mockup whose `picks`
754
+ * cover the most slots. Every wrong input fails loudly with a typed code
755
+ * that lists the valid values — a bare `variant=` / `opt.<attr>` names no
756
+ * slot and is refused rather than guessed.
757
+ */
758
+ export function resolveBundleScene(
759
+ product: ResolvedProduct,
760
+ input: BundleSceneInput
761
+ ): BundleSceneResult {
762
+ const bundle = product.bundle;
763
+ if (!bundle) {
764
+ return { ok: false, status: 500, code: "E_NOT_A_BUNDLE", message: `${product.id} has no bundle block` };
765
+ }
766
+ const roles = bundle.members.map((m) => m.role);
767
+ const rolesList = roles.join(", ");
768
+ const fail = (status: number, code: string, message: string): BundleSceneResult => ({ ok: false, status, code, message });
769
+
770
+ if (input.variantOverride !== undefined) {
771
+ return fail(
772
+ 400,
773
+ "E_BUNDLE_ROLE_REQUIRED",
774
+ `variant= names no slot on bundle ${product.id} — use variant.<role>=<gvid>. Roles: ${rolesList}.`
775
+ );
776
+ }
777
+ for (const role of Object.keys(input.picks)) {
778
+ if (!roles.includes(role)) {
779
+ return fail(400, "E_BUNDLE_ROLE_NOT_FOUND", `Unknown role "${role}" in pick.${role}= on bundle ${product.id}. Roles: ${rolesList}.`);
780
+ }
781
+ }
782
+ for (const role of Object.keys(input.variants)) {
783
+ if (!roles.includes(role)) {
784
+ return fail(400, "E_BUNDLE_ROLE_NOT_FOUND", `Unknown role "${role}" in variant.${role}= on bundle ${product.id}. Roles: ${rolesList}.`);
785
+ }
786
+ }
787
+ const optionsByRole: Record<string, Record<string, string>> = {};
788
+ for (const [key, value] of Object.entries(input.options)) {
789
+ const dot = key.indexOf(".");
790
+ if (dot <= 0 || dot === key.length - 1) {
791
+ return fail(
792
+ 400,
793
+ "E_BUNDLE_ROLE_REQUIRED",
794
+ `opt.${key}= names no slot on bundle ${product.id} — use opt.<role>.<attribute>=<choice>. Roles: ${rolesList}.`
795
+ );
796
+ }
797
+ const role = key.slice(0, dot);
798
+ const attr = key.slice(dot + 1);
799
+ if (!roles.includes(role)) {
800
+ return fail(400, "E_BUNDLE_ROLE_NOT_FOUND", `Unknown role "${role}" in opt.${key}= on bundle ${product.id}. Roles: ${rolesList}.`);
801
+ }
802
+ (optionsByRole[role] ??= {})[attr] = value;
803
+ }
804
+
805
+ const picks: Record<string, string> = {};
806
+ const variantByRole: BundleScene["variantByRole"] = {};
807
+ const optionSelections: Record<string, string> = {};
808
+ for (const member of bundle.members) {
809
+ const wanted = input.picks[member.role];
810
+ const alt = wanted === undefined
811
+ ? member.products[0]
812
+ : member.products.find((p) => p.productId === wanted);
813
+ if (!alt) {
814
+ return fail(
815
+ 400,
816
+ "E_BUNDLE_PICK_NOT_FOUND",
817
+ `Unknown pick "${wanted}" for role "${member.role}" on bundle ${product.id}. ` +
818
+ `Alternatives: ${member.products.map((p) => p.productId).join(", ")}.`
819
+ );
820
+ }
821
+ picks[member.role] = alt.productId;
822
+ const roleOpts = optionsByRole[member.role] ?? {};
823
+ const bad = unknownOptionPick(alt, roleOpts);
824
+ if (bad) {
825
+ return bad.validChoices
826
+ ? fail(
827
+ 400,
828
+ "E_OPTION_CHOICE_NOT_FOUND",
829
+ `Unknown choice "${bad.choice}" for option "${bad.attribute}" on ${alt.productId} (role "${member.role}"). ` +
830
+ `Valid choices: ${bad.validChoices.join(", ")}.`
831
+ )
832
+ : fail(
833
+ 400,
834
+ "E_OPTION_NOT_FOUND",
835
+ `Unknown option "${bad.attribute}" on ${alt.productId} (role "${member.role}"). ` +
836
+ (bad.validAttributes.length
837
+ ? `Valid options: ${bad.validAttributes.join(", ")}.`
838
+ : `This product has no options.`)
839
+ );
840
+ }
841
+ const vr = resolveVariant(alt, roleOpts, input.variants[member.role]);
842
+ if (!vr) {
843
+ return fail(422, "E_BUNDLE_MEMBER_NO_VARIANT", `${alt.productId} (role "${member.role}") has no renderable combination`);
844
+ }
845
+ const renderGvid = alt.variants.find((v) => v.gvid === vr.variantId)?.gvidForMockup ?? vr.variantId;
846
+ variantByRole[member.role] = { skuGvid: vr.variantId, renderGvid };
847
+ for (const [attr, choice] of Object.entries(vr.optionSelections)) {
848
+ optionSelections[`${member.role}.${attr}`] = choice;
849
+ }
850
+ }
851
+
852
+ // The mockup: an explicit override, else the one whose picks cover the most
853
+ // slots (a photo depicts exactly one alternative per slot; unmatched slots
854
+ // render blank — their masks belong to a product not in the photo).
855
+ let mockup: ResolvedProduct["mockups"][number] | undefined;
856
+ if (input.mockupOverride) {
857
+ mockup = product.mockups.find((m) => m.id === input.mockupOverride);
858
+ if (!mockup) {
859
+ return fail(
860
+ 400,
861
+ "E_MOCKUP_NOT_FOUND",
862
+ `Unknown mockup "${input.mockupOverride}" for bundle ${product.id}. Mockups: ${product.mockups.map((m) => m.id).join(", ") || "(none)"}.`
863
+ );
864
+ }
865
+ } else {
866
+ let best = -1;
867
+ for (const m of product.mockups) {
868
+ const score = roles.filter((r) => m.picks?.[r] === picks[r]).length;
869
+ if (score > best) {
870
+ best = score;
871
+ mockup = m;
872
+ }
873
+ }
874
+ }
875
+ if (!mockup) {
876
+ return fail(422, "E_BUNDLE_NO_MOCKUP", `Bundle ${product.id} has no published mockup`);
877
+ }
878
+
879
+ const placements = product.placements.filter((p) => p.role && picks[p.role] === p.memberProductId);
880
+ if (placements.length === 0) {
881
+ return fail(422, "E_BUNDLE_NO_PLACEMENTS", `Bundle ${product.id} has no placements for the pick set ${JSON.stringify(picks)}`);
882
+ }
883
+
884
+ return {
885
+ ok: true,
886
+ scene: {
887
+ picks,
888
+ variantByRole,
889
+ optionSelections,
890
+ mockupId: mockup.id,
891
+ placements,
892
+ variantToken: bundleVariantToken(variantByRole),
893
+ },
894
+ };
895
+ }
@@ -7,6 +7,7 @@ import {
7
7
  PUBLIC_PARAM_GRAMMAR,
8
8
  PUBLIC_PARAM_NAMES,
9
9
  isKnownPublicParam,
10
+ parsePublicUrl,
10
11
  unknownPublicParams,
11
12
  unknownPublicParamsMessage,
12
13
  } from '@snowcone-app/mockup-url'
@@ -29,6 +30,20 @@ describe('isKnownPublicParam', () => {
29
30
  }
30
31
  })
31
32
 
33
+ it('accepts the ADR-0099 bundle families (role level) and parses them', () => {
34
+ for (const name of ['variant.top', 'pick.top', 'opt.top.Size', 'asset.top.front', 'asset.top', 'color.shorts.front']) {
35
+ expect(isKnownPublicParam(name), name).toBe(true)
36
+ }
37
+ expect(isKnownPublicParam('variant.')).toBe(false)
38
+ expect(isKnownPublicParam('pick.')).toBe(false)
39
+ const parsed = parsePublicUrl('https://img.snowcone.app/SUMSET?shop=s&asset=https%3A%2F%2Fa%2Fx.png&variant.top=tM&pick.top=TEE001&opt.shorts.Color=Navy&asset.shorts.front=https%3A%2F%2Fa%2Fy.png')
40
+ expect(parsed.variants).toEqual({ top: 'tM' })
41
+ expect(parsed.picks).toEqual({ top: 'TEE001' })
42
+ expect(parsed.options).toEqual({ 'shorts.Color': 'Navy' })
43
+ expect(parsed.design).toEqual({ 'shorts.front': { src: 'https://a/y.png' } })
44
+ expect(PUBLIC_PARAM_GRAMMAR).toMatch(/variant\.<role>, pick\.<role>/)
45
+ })
46
+
32
47
  it('rejects a bare dotted prefix (empty placement key)', () => {
33
48
  for (const name of ['asset.', 'color.', 'tile.', 'align.', 'opt.']) {
34
49
  expect(isKnownPublicParam(name), name).toBe(false)
@@ -495,3 +495,180 @@ describe("unknownOptionPick (E_OPTION_NOT_FOUND / E_OPTION_CHOICE_NOT_FOUND)", (
495
495
  expect(unknownOptionPick(cap, { Crown: "anything" })).toBeNull();
496
496
  });
497
497
  });
498
+
499
+ // ─── ADR-0099 bundles: per-role picks, variants and the mockup choice ───────
500
+ import {
501
+ bundleVariantToken,
502
+ normalizeBundle,
503
+ resolveBundleScene,
504
+ wirePlacement,
505
+ } from "../src/resolve";
506
+
507
+ const bundleRaw = {
508
+ members: [
509
+ {
510
+ role: "top",
511
+ required: true,
512
+ products: [
513
+ {
514
+ productId: "TANK01",
515
+ defaultGvid: "tS",
516
+ variants: [{ gvid: "tS", gvidForMockup: "tR" }, { gvid: "tM" }],
517
+ options: {
518
+ attributes: { Size: { affectsCombinations: true, choices: [{ label: "S" }, { label: "M" }] } },
519
+ combinations: [{ Size: "S", variantId: "tS" }, { Size: "M", variantId: "tM" }],
520
+ },
521
+ },
522
+ { productId: "TEE001", defaultGvid: "eS", variants: [{ gvid: "eS" }], options: { attributes: {}, combinations: [] } },
523
+ ],
524
+ },
525
+ {
526
+ role: "shorts",
527
+ required: true,
528
+ products: [
529
+ {
530
+ productId: "SH0RT5",
531
+ defaultGvid: null,
532
+ variants: [{ gvid: "sS" }],
533
+ options: {
534
+ attributes: { Color: { affectsCombinations: false, choices: [{ label: "Red" }, { label: "Navy" }] } },
535
+ combinations: [],
536
+ },
537
+ },
538
+ ],
539
+ },
540
+ ],
541
+ priceRule: { kind: "percent_off", bps: 1000 },
542
+ };
543
+
544
+ const bundleProduct = (): ResolvedProduct => ({
545
+ version: "v1",
546
+ renderVersion: "r1",
547
+ id: "SUMSET",
548
+ variants: [],
549
+ mockups: [
550
+ { id: "mTank", gvids: ["tS", "sS"], picks: { top: "TANK01", shorts: "SH0RT5" } },
551
+ { id: "mTee", gvids: ["eS", "sS"], picks: { top: "TEE001", shorts: "SH0RT5" } },
552
+ ],
553
+ placements: [
554
+ { key: "top.front", label: "Front", type: "image", width: 10, height: 12, role: "top", memberProductId: "TANK01" },
555
+ { key: "top.back", label: "Back", type: "image", width: 10, height: 12, role: "top", memberProductId: "TANK01" },
556
+ { key: "top.front", label: "Front", type: "image", width: 11, height: 13, role: "top", memberProductId: "TEE001" },
557
+ { key: "shorts.front", label: "Front", type: "image", width: 8, height: 9, role: "shorts", memberProductId: "SH0RT5" },
558
+ ],
559
+ defaultGvid: null,
560
+ attributes: {},
561
+ combinations: [],
562
+ album: null,
563
+ bundle: normalizeBundle(bundleRaw),
564
+ });
565
+
566
+ describe("normalizeBundle", () => {
567
+ it("normalizes members, alternatives, variants (with render gvids) and options", () => {
568
+ const b = normalizeBundle(bundleRaw)!;
569
+ expect(b.members.map((m) => m.role)).toEqual(["top", "shorts"]);
570
+ expect(b.members[0].products[0].variants).toEqual([{ gvid: "tS", gvidForMockup: "tR" }, { gvid: "tM", gvidForMockup: null }]);
571
+ expect(b.members[0].products[0].attributes.Size).toEqual({ affectsCombinations: true, choices: ["S", "M"] });
572
+ expect(b.members[1].products[0].defaultGvid).toBeNull();
573
+ });
574
+ it("is null for absent or empty blocks", () => {
575
+ expect(normalizeBundle(undefined)).toBeNull();
576
+ expect(normalizeBundle({ members: [] })).toBeNull();
577
+ expect(normalizeBundle({ members: [{ role: "x", products: [] }] })).toBeNull();
578
+ });
579
+ });
580
+
581
+ describe("resolveBundleScene", () => {
582
+ const ok = (r: ReturnType<typeof resolveBundleScene>) => {
583
+ if (!r.ok) throw new Error(`${r.code}: ${r.message}`);
584
+ return r.scene;
585
+ };
586
+
587
+ it("defaults: products[0] per slot, the member's default SKU, the RENDER gvid in the token, the best-covering mockup", () => {
588
+ const scene = ok(resolveBundleScene(bundleProduct(), { picks: {}, variants: {}, options: {} }));
589
+ expect(scene.picks).toEqual({ top: "TANK01", shorts: "SH0RT5" });
590
+ expect(scene.variantByRole).toEqual({ top: { skuGvid: "tS", renderGvid: "tR" }, shorts: { skuGvid: "sS", renderGvid: "sS" } });
591
+ expect(scene.variantToken).toBe("shorts:sS,top:tR");
592
+ expect(scene.mockupId).toBe("mTank");
593
+ expect(scene.placements.map((p) => [p.key, p.memberProductId])).toEqual([["top.front", "TANK01"], ["top.back", "TANK01"], ["shorts.front", "SH0RT5"]]);
594
+ expect(scene.optionSelections).toEqual({});
595
+ });
596
+
597
+ it("pick.<role> swaps the alternative, narrows placements and re-picks the mockup", () => {
598
+ const scene = ok(resolveBundleScene(bundleProduct(), { picks: { top: "TEE001" }, variants: {}, options: {} }));
599
+ expect(scene.picks.top).toBe("TEE001");
600
+ expect(scene.mockupId).toBe("mTee");
601
+ expect(scene.placements.map((p) => [p.key, p.width])).toEqual([["top.front", 11], ["shorts.front", 8]]);
602
+ expect(scene.variantToken).toBe("shorts:sS,top:eS");
603
+ });
604
+
605
+ it("variant.<role> and opt.<role>.<attr> resolve through the member's combinations; render-only picks are role-qualified", () => {
606
+ const byOpt = ok(resolveBundleScene(bundleProduct(), { picks: {}, variants: {}, options: { "top.size": "m", "shorts.color": "navy" } }));
607
+ expect(byOpt.variantByRole.top).toEqual({ skuGvid: "tM", renderGvid: "tM" });
608
+ expect(byOpt.optionSelections).toEqual({ "shorts.Color": "Navy" });
609
+ const byVariant = ok(resolveBundleScene(bundleProduct(), { picks: {}, variants: { top: "tM" }, options: {} }));
610
+ expect(byVariant.variantToken).toBe("shorts:sS,top:tM");
611
+ });
612
+
613
+ it("mockup= override wins; an unknown one lists the mockups", () => {
614
+ expect(ok(resolveBundleScene(bundleProduct(), { picks: {}, variants: {}, options: {}, mockupOverride: "mTee" })).mockupId).toBe("mTee");
615
+ const r = resolveBundleScene(bundleProduct(), { picks: {}, variants: {}, options: {}, mockupOverride: "nope" });
616
+ expect(r.ok).toBe(false);
617
+ if (!r.ok) expect(r.code).toBe("E_MOCKUP_NOT_FOUND");
618
+ });
619
+
620
+ it.each([
621
+ ["bare variant=", { picks: {}, variants: {}, options: {}, variantOverride: "tS" }, "E_BUNDLE_ROLE_REQUIRED", /variant\.<role>=/],
622
+ ["bare opt.<attr>", { picks: {}, variants: {}, options: { Size: "M" } }, "E_BUNDLE_ROLE_REQUIRED", /opt\.<role>\.<attribute>/],
623
+ ["unknown role in pick", { picks: { hat: "X" }, variants: {}, options: {} }, "E_BUNDLE_ROLE_NOT_FOUND", /Roles: top, shorts/],
624
+ ["unknown role in variant", { picks: {}, variants: { hat: "X" }, options: {} }, "E_BUNDLE_ROLE_NOT_FOUND", /variant\.hat=/],
625
+ ["unknown role in opt", { picks: {}, variants: {}, options: { "hat.Size": "M" } }, "E_BUNDLE_ROLE_NOT_FOUND", /opt\.hat\.Size=/],
626
+ ["unknown pick", { picks: { top: "HOODIE" }, variants: {}, options: {} }, "E_BUNDLE_PICK_NOT_FOUND", /Alternatives: TANK01, TEE001/],
627
+ ["unknown option on the member", { picks: {}, variants: {}, options: { "top.Fit": "slim" } }, "E_OPTION_NOT_FOUND", /TANK01 \(role "top"\)/],
628
+ ["unknown choice on the member", { picks: {}, variants: {}, options: { "shorts.Color": "Teal" } }, "E_OPTION_CHOICE_NOT_FOUND", /Valid choices: Red, Navy/],
629
+ ])("fails loudly: %s", (_name, input, code, re) => {
630
+ const r = resolveBundleScene(bundleProduct(), input as any);
631
+ expect(r.ok).toBe(false);
632
+ if (!r.ok) {
633
+ expect(r.code).toBe(code);
634
+ expect(r.message).toMatch(re);
635
+ expect(r.status).toBe(400);
636
+ }
637
+ });
638
+
639
+ it("no mockups → 422 E_BUNDLE_NO_MOCKUP", () => {
640
+ const p = bundleProduct();
641
+ p.mockups = [];
642
+ const r = resolveBundleScene(p, { picks: {}, variants: {}, options: {} });
643
+ expect(r.ok).toBe(false);
644
+ if (!r.ok) expect([r.status, r.code]).toEqual([422, "E_BUNDLE_NO_MOCKUP"]);
645
+ });
646
+
647
+ it("the variant token is sorted by role (deterministic cache key)", () => {
648
+ expect(bundleVariantToken({ top: { renderGvid: "b" }, shorts: { renderGvid: "a" } })).toBe("shorts:a,top:b");
649
+ });
650
+ });
651
+
652
+ describe("assembleArtwork on a bundle (role-scoped wire keys)", () => {
653
+ it("elements carry the role-scoped key as their placement; base broadcasts across the pick set; overrides by scoped key", () => {
654
+ const scene = ok2(resolveBundleScene(bundleProduct(), { picks: {}, variants: {}, options: {} }));
655
+ const view = { ...bundleProduct(), placements: scene.placements };
656
+ const findPlacement = (k: string) => view.placements.find((p) => p.key === k) ?? null;
657
+ const base = assembleArtwork(view, { asset: "https://a/x.png", design: {}, house: "https://h/b.png", findPlacement });
658
+ expect(base.ok && base.elements.map((e) => e.placement)).toEqual(["top.front", "top.back", "shorts.front"]);
659
+ const over = assembleArtwork(view, { asset: "https://a/x.png", design: { "shorts.front": { src: "https://a/y.png" } }, house: "https://h/b.png", findPlacement });
660
+ expect(over.ok && over.elements.find((e) => e.placement === "shorts.front")).toMatchObject({ imageUrl: "https://a/y.png" });
661
+ const bad = assembleArtwork(view, { asset: null, design: { "top.left_sleeve": { src: "https://a/y.png" } }, house: "https://h/b.png", findPlacement });
662
+ expect(bad.ok).toBe(false);
663
+ if (!bad.ok) expect(bad.message).toMatch(/Valid placements: top.front, top.back, shorts.front/);
664
+ });
665
+ it("single-product placements keep the label on the wire", () => {
666
+ expect(wirePlacement({ key: "front", label: "Front", type: "image", width: 1, height: 1 })).toBe("Front");
667
+ expect(wirePlacement({ key: "top.front", label: "Front", type: "image", width: 1, height: 1, role: "top" })).toBe("top.front");
668
+ });
669
+ });
670
+
671
+ function ok2(r: ReturnType<typeof resolveBundleScene>) {
672
+ if (!r.ok) throw new Error(`${r.code}: ${r.message}`);
673
+ return r.scene;
674
+ }