@snowcone-app/design 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,13 @@
1
+ # @snowcone-app/design
2
+
3
+ ## 0.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#6878](https://github.com/snowcone-app/snowcone-monorepo/pull/6878) [`22be7a1`](https://github.com/snowcone-app/snowcone-monorepo/commit/22be7a1ec9a32eb3fcfe024f87ef67a6f33f9604) Thanks [@kevinsproles](https://github.com/kevinsproles)! - `@snowcone-app/design` now also describes the two formats the server reads (ADR-0115 step 1b). `SavedDesignSchema` is what the editor's change event emits and a design stores. `RenderWireSchema` is what the render box rasterises. The conversion between them lives in `@snowcone-app/design/wire` (`toRenderWire`, same as canvas's `serializeStateForServer`, which is now a re-export), together with the masked-crop and image-adjustment helpers. The entry has no zod. The conformance kit adds `toSavedDesign()` and a two-placement golden.
8
+
9
+ ## 0.1.0
10
+
11
+ ### Minor Changes
12
+
13
+ - [#6875](https://github.com/snowcone-app/snowcone-monorepo/pull/6875) [`46c6f63`](https://github.com/snowcone-app/snowcone-monorepo/commit/46c6f63ba8100a7ed51b5122862db5aef4bf3761) Thanks [@kevinsproles](https://github.com/kevinsproles)! - New package `@snowcone-app/design`, the Snowcone design format (ADR-0115 step 1a). It holds the Zod schemas for every artboard, element type and effect, `validateDesign` / `assertDesign` / `migrateDesign` with typed errors (`E_DESIGN_INVALID`, listing every path and its valid values; `E_DESIGN_VERSION`), and a conformance kit (`@snowcone-app/design/conformance`) with one golden design per element type and effect. `@snowcone-app/canvas` now uses these schemas and keeps its exports unchanged. The schemas now keep fields the editor writes that used to be stripped: `shadow`, an image's `maskedCrop` and `engrave`, `preserveDimensions`, an artboard's `imageMask`. `serializeState` / `deserializeState` now keep an artboard's `distressTexture` and `imageMask`.
package/README.md CHANGED
@@ -1,3 +1,39 @@
1
- # Temporary Holding Version
1
+ # @snowcone-app/design
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Snowcone design format, as a small package with no React, canvas or fonts: Zod schemas for every artboard, element
4
+ type and effect, plus `validateDesign`, `assertDesign`, `migrateDesign` and typed errors. Any editor can check its
5
+ output against it, ours or one you build.
6
+
7
+ ```ts
8
+ import { validateDesign, assertDesign, migrateDesign } from "@snowcone-app/design";
9
+
10
+ const r = validateDesign(json); // never throws: { success, data } or { success: false, errors, issues }
11
+ const design = assertDesign(json); // throws E_DESIGN_INVALID with every path, the valid values and the fix
12
+ const current = migrateDesign(json); // reads older formats; E_DESIGN_VERSION for a version it can't read
13
+ ```
14
+
15
+ ## Versions
16
+
17
+ The format has a major `version` (1 today, `DESIGN_VERSION`). Within a major, changes are additive only: a new
18
+ optional field, or a new element type the server renders. A breaking change is a new major with a migration.
19
+ `SUPPORTED_DESIGN_VERSIONS` lists the majors that are read: the current one and the one before it.
20
+
21
+ ## Errors
22
+
23
+ | Code | When | Data |
24
+ |---|---|---|
25
+ | `E_DESIGN_INVALID` | Not a valid design of its version | `issues: [{ path, message, valid? }]` |
26
+ | `E_DESIGN_VERSION` | A version this package does not read | `found`, `supported` |
27
+
28
+ Every error has `code`, `data` and `docSlug: "design-format"`. Assert on those, not on the message text.
29
+
30
+ ## Conformance kit
31
+
32
+ ```ts
33
+ import { GOLDEN_DESIGNS, GOLDEN_ELEMENT_TYPES, GOLDEN_EFFECTS } from "@snowcone-app/design/conformance";
34
+ ```
35
+
36
+ The kit has one small valid design per element type and per effect. An editor conforms when each golden it opens
37
+ and saves again comes back as a valid design that has kept every field: nothing dropped, nothing the format strips.
38
+ `@snowcone-app/canvas` runs exactly this check (`src/state/CanvasStateV1.conformance.test.ts`). The kit's own test
39
+ fails when an element type has no golden, so a new type can't land without one.
@@ -0,0 +1,234 @@
1
+ 'use strict';
2
+
3
+ // ../mockup-url/src/index.ts
4
+ var SNOWCONE_HOSTS = {
5
+ /** Public asset storage: the design conformance kit's golden images and fonts (`/goldens/v1/…`). */
6
+ storage: "https://2e2c853b83.storage.snowcone.app"
7
+ };
8
+ var viewGrid = (from, to, step) => Array.from({ length: Math.round((to - from) / step) + 1 }, (_, i) => Math.round((from + i * step) * 1e3) / 1e3);
9
+ viewGrid(1.3, 2.7, 0.1);
10
+ [...viewGrid(0.25, 0.475, 0.025), ...viewGrid(0.525, 0.75, 0.025)];
11
+
12
+ // src/conformance/index.ts
13
+ var GOLDEN_ELEMENT_TYPES = [
14
+ "custom",
15
+ "distort",
16
+ "circle",
17
+ "lean",
18
+ "arch",
19
+ "ascend",
20
+ "wave",
21
+ "flag",
22
+ "image",
23
+ "group",
24
+ "shape",
25
+ "path"
26
+ ];
27
+ var GOLDEN_EFFECTS = [
28
+ "stroke",
29
+ "knockout",
30
+ "mask-clip",
31
+ "mask-alpha",
32
+ "distress",
33
+ "rich-text",
34
+ "opentype",
35
+ "gradient-fill",
36
+ "clip-shape",
37
+ "artboard-distress",
38
+ "custom-font",
39
+ "hidden-layer",
40
+ "clipping-layer",
41
+ "shadow",
42
+ "engrave",
43
+ "masked-crop",
44
+ "artboard-image-mask",
45
+ "two-placements"
46
+ ];
47
+ var ARTBOARD = { id: "ab-1", name: "Front", x: 0, y: 0, width: 1e3, height: 1e3, backgroundColor: "#ffffff" };
48
+ var BASE = { x: 500, y: 500, rotation: 0, opacity: 1 };
49
+ var TEXT = { text: "SNOWCONE", fontSize: 96, fontFamily: "Anton", color: "#111111", textAlign: "center" };
50
+ var GOLDEN_IMAGE_URL = `${SNOWCONE_HOSTS.storage}/goldens/v1/grid-1000.png`;
51
+ function one(name, covers, elements, artboard = {}, extra = {}) {
52
+ return {
53
+ name,
54
+ covers,
55
+ design: {
56
+ version: 1,
57
+ artboards: [{ ...ARTBOARD, ...artboard, elementIds: elements.map((e) => String(e.id)) }],
58
+ elements,
59
+ activeArtboardId: ARTBOARD.id,
60
+ ...extra
61
+ }
62
+ };
63
+ }
64
+ var text = (id, transformType, transformData, more = {}) => ({
65
+ id,
66
+ ...BASE,
67
+ ...TEXT,
68
+ transformType,
69
+ ...transformData ? { transformData } : {},
70
+ ...more
71
+ });
72
+ var image = (id, more = {}) => ({
73
+ id,
74
+ ...BASE,
75
+ transformType: "image",
76
+ imageUrl: GOLDEN_IMAGE_URL,
77
+ imageAspectRatio: 1,
78
+ transformData: { type: "image", width: 600, height: 600, cropX: 0, cropY: 0, cropWidth: 1, cropHeight: 1, flipHorizontal: false, flipVertical: false, borderRadius: 0 },
79
+ ...more
80
+ });
81
+ var shape = (id, more = {}, data = {}) => ({
82
+ id,
83
+ ...BASE,
84
+ transformType: "shape",
85
+ transformData: { type: "shape", shapeType: "rectangle", width: 400, height: 300, fillColor: "#e4572e", ...data },
86
+ ...more
87
+ });
88
+ var GOLDEN_DESIGNS = [
89
+ one("element/custom", { elements: ["custom"], effects: [] }, [text("t-1", "custom", { type: "custom", controlPoints: [] })]),
90
+ one("element/distort", { elements: ["distort"], effects: [] }, [text("t-1", "distort", { type: "distort" })]),
91
+ one("element/circle", { elements: ["circle"], effects: [] }, [text("t-1", "circle", { type: "circle", radius: 300, scale: 1, reverse: false })]),
92
+ one("element/lean", { elements: ["lean"], effects: [] }, [text("t-1", "lean", { type: "lean", leanAmount: 20 })]),
93
+ one("element/arch", { elements: ["arch"], effects: [] }, [text("t-1", "arch", { type: "arch", archHeight: 80 })]),
94
+ one("element/ascend", { elements: ["ascend"], effects: [] }, [text("t-1", "ascend", { type: "ascend", ascendAngle: 15 })]),
95
+ one("element/wave", { elements: ["wave"], effects: [] }, [text("t-1", "wave", { type: "wave", amplitude: 30, frequency: 2 })]),
96
+ one("element/flag", { elements: ["flag"], effects: [] }, [text("t-1", "flag", { type: "flag", amplitude: 20, frequency: 1.5 })]),
97
+ one("element/image", { elements: ["image"], effects: [] }, [image("i-1")]),
98
+ one("element/group", { elements: ["group", "shape"], effects: [] }, [
99
+ {
100
+ id: "g-1",
101
+ ...BASE,
102
+ transformType: "group",
103
+ transformData: { type: "group" },
104
+ // children in artboard coordinates, placed symmetrically: the editor sets a group's centre from its children
105
+ children: [shape("s-1", { x: 400, y: 500 }, { width: 100, height: 100 }), shape("s-2", { x: 600, y: 500 }, { width: 100, height: 100 })]
106
+ }
107
+ ]),
108
+ one("element/shape", { elements: ["shape"], effects: [] }, [shape("s-1", {}, { shapeType: "star", points: 5, innerRadius: 0.5 })]),
109
+ one("element/path", { elements: ["path"], effects: [] }, [
110
+ {
111
+ id: "p-1",
112
+ ...BASE,
113
+ transformType: "path",
114
+ transformData: {
115
+ type: "path",
116
+ closed: true,
117
+ width: 400,
118
+ height: 400,
119
+ fillEnabled: true,
120
+ fillColor: "#2e86ab",
121
+ points: [
122
+ { id: "a", x: 0, y: 0, type: "corner" },
123
+ { id: "b", x: 400, y: 0, type: "smooth", handleIn: { x: 300, y: -50 }, handleOut: { x: 450, y: 50 } },
124
+ { id: "c", x: 200, y: 400, type: "bezier", handleIn: { x: 300, y: 400 }, handleOut: { x: 100, y: 400 } }
125
+ ]
126
+ }
127
+ }
128
+ ]),
129
+ one("effect/stroke", { elements: ["custom"], effects: ["stroke"] }, [
130
+ text("t-1", "custom", void 0, { stroke: { enabled: true, color: "#000000", width: 8, lineCap: "round", lineJoin: "round" } })
131
+ ]),
132
+ one("effect/knockout", { elements: ["shape", "custom"], effects: ["knockout"] }, [
133
+ shape("s-1", {}, { width: 800, height: 400 }),
134
+ text("t-1", "custom", void 0, { blendMode: "knockout", knockoutParts: { fill: true, scope: "artboard" } })
135
+ ]),
136
+ one("effect/mask-clip", { elements: ["image", "custom"], effects: ["mask-clip"] }, [
137
+ image("i-1", { masks: [{ id: "m-1", type: "clip", maskElement: text("mt-1", "custom", void 0, { x: 0, y: 0, fontSize: 200 }) }] })
138
+ ]),
139
+ one("effect/mask-alpha", { elements: ["image", "shape"], effects: ["mask-alpha"] }, [
140
+ image("i-1", { masks: [{ id: "m-1", type: "alpha", feather: 12, inverted: false, maskElement: shape("ms-1", { x: 0, y: 0 }, { shapeType: "circle", width: 400, height: 400 }) }] })
141
+ ]),
142
+ one("effect/distress", { elements: ["custom"], effects: ["distress"] }, [
143
+ text("t-1", "custom", void 0, { distressEffect: { enabled: true, style: "worn", intensity: 60, seed: 12345 } })
144
+ ]),
145
+ one("effect/rich-text", { elements: ["custom"], effects: ["rich-text"] }, [
146
+ text("t-1", "custom", void 0, {
147
+ richText: { spans: [{ text: "SNOW", style: { color: "#e4572e", bold: true } }, { text: "CONE", style: { italic: true } }] }
148
+ })
149
+ ]),
150
+ one("effect/opentype", { elements: ["custom"], effects: ["opentype"] }, [
151
+ text("t-1", "custom", void 0, { openTypeFeatures: { liga: true, ss01: true }, letterSpacing: 4, lineHeight: 1.1 })
152
+ ]),
153
+ one("effect/gradient-fill", { elements: ["shape"], effects: ["gradient-fill"] }, [
154
+ shape("s-1", {}, { fillColor: void 0, fill: { type: "linear", angle: 45, stops: [{ offset: 0, color: "#e4572e" }, { offset: 1, color: "#2e86ab" }] } })
155
+ ]),
156
+ one("effect/clip-shape", { elements: ["image"], effects: ["clip-shape"] }, [image("i-1")], { clipShape: { type: "rounded", radius: 120 } }),
157
+ one("effect/artboard-distress", { elements: ["custom"], effects: ["artboard-distress"] }, [text("t-1", "custom")], {
158
+ distressTexture: { enabled: true, textureUrl: "builtin:grunge-heavy", intensity: 50 }
159
+ }),
160
+ one("effect/custom-font", { elements: ["custom"], effects: ["custom-font"] }, [text("t-1", "custom", void 0, { fontFamily: "Golden Brand" })], {}, {
161
+ customFonts: [{ family: "Golden Brand", url: `${SNOWCONE_HOSTS.storage}/goldens/v1/brand.woff2`, weight: 400, style: "normal" }]
162
+ }),
163
+ one("effect/hidden-layer", { elements: ["custom", "shape"], effects: ["hidden-layer"] }, [shape("s-1"), text("t-1", "custom", void 0, { visible: false })]),
164
+ one("effect/shadow", { elements: ["custom"], effects: ["shadow"] }, [
165
+ text("t-1", "custom", void 0, { shadow: { enabled: true, color: "#000000", blur: 12, offsetX: 6, offsetY: 6, opacity: 0.5 } })
166
+ ]),
167
+ one("effect/engrave", { elements: ["image"], effects: ["engrave"] }, [
168
+ image("i-1", {
169
+ transformData: {
170
+ type: "image",
171
+ width: 600,
172
+ height: 600,
173
+ cropX: 0,
174
+ cropY: 0,
175
+ cropWidth: 1,
176
+ cropHeight: 1,
177
+ flipHorizontal: false,
178
+ flipVertical: false,
179
+ borderRadius: 0,
180
+ maskedCrop: "frame",
181
+ engrave: { style: "photo", amount: 0, invert: false, sourceUrl: GOLDEN_IMAGE_URL, cutLight: false }
182
+ }
183
+ })
184
+ ]),
185
+ one("effect/masked-crop", { elements: ["image", "shape"], effects: ["masked-crop", "mask-clip"] }, [
186
+ image("i-1", {
187
+ transformData: { type: "image", width: 600, height: 600, cropX: 0.25, cropY: 0.25, cropWidth: 0.5, cropHeight: 0.5, flipHorizontal: true, flipVertical: false, borderRadius: 0, maskedCrop: "frame" },
188
+ masks: [{ id: "m-1", type: "clip", maskElement: shape("ms-1", { x: 0, y: 0 }, { shapeType: "circle", width: 400, height: 400 }) }]
189
+ })
190
+ ]),
191
+ one("effect/artboard-image-mask", { elements: ["image"], effects: ["artboard-image-mask"] }, [image("i-1")], {
192
+ imageMask: { enabled: true, imageUrl: GOLDEN_IMAGE_URL, maskType: "alpha", opacity: 100, inverted: false }
193
+ }),
194
+ {
195
+ name: "effect/two-placements",
196
+ covers: { elements: ["custom", "shape"], effects: ["two-placements"] },
197
+ design: {
198
+ version: 1,
199
+ artboards: [
200
+ { ...ARTBOARD, id: "ab-front", name: "Front", elementIds: ["t-front"] },
201
+ { ...ARTBOARD, id: "ab-back", name: "Back", width: 800, height: 1200, elementIds: ["s-back"] }
202
+ ],
203
+ elements: [text("t-front", "custom"), shape("s-back")],
204
+ activeArtboardId: "ab-front"
205
+ }
206
+ },
207
+ one("effect/clipping-layer", { elements: ["shape", "image"], effects: ["clipping-layer"] }, [shape("s-1", { isClipping: true }), image("i-1")])
208
+ ];
209
+ function toSavedDesign(design) {
210
+ const artboardOf = /* @__PURE__ */ new Map();
211
+ for (const a of design.artboards) for (const id of a.elementIds) artboardOf.set(id, a.name);
212
+ const active = design.artboards.find((a) => a.id === design.activeArtboardId);
213
+ return {
214
+ elements: design.elements.map((e) => {
215
+ const id = String(e.id);
216
+ const tag = artboardOf.get(id);
217
+ return tag ? { ...e, artboard: tag } : e;
218
+ }),
219
+ artboards: design.artboards.map((a) => {
220
+ const { id: _id, x: _x, y: _y, elementIds: _ids, backgroundType: _bt, backgroundTexture: _tx, previewBackgroundColor: _pv, ...rest } = a;
221
+ return rest;
222
+ }),
223
+ ...active ? { activeArtboard: active.name } : {},
224
+ ...design.customFonts?.length ? { customFonts: design.customFonts } : {}
225
+ };
226
+ }
227
+
228
+ exports.GOLDEN_DESIGNS = GOLDEN_DESIGNS;
229
+ exports.GOLDEN_EFFECTS = GOLDEN_EFFECTS;
230
+ exports.GOLDEN_ELEMENT_TYPES = GOLDEN_ELEMENT_TYPES;
231
+ exports.GOLDEN_IMAGE_URL = GOLDEN_IMAGE_URL;
232
+ exports.toSavedDesign = toSavedDesign;
233
+ //# sourceMappingURL=index.cjs.map
234
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../mockup-url/src/index.ts","../../src/conformance/index.ts"],"names":[],"mappings":";;;AAiCO,IAAM,cAAA,GAAiB;AAAA,EAsBpB;AAAA,EAER,OAAA,EAAS;AACX,CAAA;AAwKA,IAAM,QAAA,GAAW,CAAC,IAAA,EAAc,EAAA,EAAY,IAAA,KAAiB,KAAA,CAAM,IAAA,CAAK,EAAE,MAAA,EAAQ,IAAA,CAAK,KAAA,CAAA,CAAO,EAAA,GAAK,IAAA,IAAQ,IAAI,CAAA,GAAI,CAAA,EAAE,EAAG,CAAC,CAAA,EAAG,CAAA,KAAM,IAAA,CAAK,KAAA,CAAA,CAAO,IAAA,GAAO,CAAA,GAAI,IAAA,IAAQ,GAAI,CAAA,GAAI,GAAI,CAAA;AAExH,QAAA,CAAS,GAAA,EAAK,GA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AAA,EAAK,CAAA,EAAG,EAAA,EAAI,GAAG,EAAA,EAAI,UAAA,EAAY,IAAA,EAAM,cAAA,EAAgB,KAAK,iBAAA,EAAmB,GAAA,EAAK,wBAAwB,GAAA,EAAK,GAAG,MAAK,GAAI,CAAA;AACvI,MAAA,OAAO,IAAA;AAAA,IACT,CAAC,CAAA;AAAA,IACD,GAAI,MAAA,GAAS,EAAE,gBAAgB,MAAA,CAAO,IAAA,KAAS,EAAC;AAAA,IAChD,GAAI,OAAO,WAAA,EAAa,MAAA,GAAS,EAAE,WAAA,EAAa,MAAA,CAAO,WAAA,EAAY,GAAI;AAAC,GAC1E;AACF","file":"index.cjs","sourcesContent":["// @snowcone-app/mockup-url — the canonical (UNSIGNED) mockup-URL builder.\n//\n// SINGLE SOURCE OF TRUTH for the mockup URL shape. Both the SDK\n// (`packages/sdk/src/mockup/urlGenerator.ts`) and the edge resolve/sign worker\n// (`workers/mockup-resolver/src/index.ts`) import `buildMockupUrl` from here, so they\n// can never drift. A signed mockup URL is a deterministic CDN cache key\n// (ADR-0073 §10): the signature is HMAC over the URL string, so if the two\n// sides ever produced different bytes for the same inputs, signatures would\n// fail to validate and the CDN cache would be silently poisoned. One builder,\n// no drift test required.\n//\n// Zero runtime dependencies. Edge-safe and browser-safe: only `btoa`,\n// `encodeURIComponent`, and `JSON` — no Node/Cloudflare-specific imports — so it\n// runs identically in a Worker, a browser, and Node (vitest).\n\n// ── Hosts ── the ONE place Snowcone's public hostnames live.\n//\n// Every published integration (@snowcone-app/sdk, /mcp, /canvas, /ui) reads\n// its default host from here — the SDK and MCP bundle this module, canvas and\n// ui import it through `@snowcone-app/sdk`. So if a hostname ever has to move\n// (forced domain change, new region, a host split), it is an edit to this\n// block plus a version bump — integrators upgrade the package and nothing they\n// wrote changes. Code that hardcodes `https://api.snowcone.app` breaks instead.\n//\n// Guarded by `.github/scripts/check-sdk-hosts.mjs`: a `*.snowcone.app` URL\n// literal anywhere else in a published package's source fails CI. Lives in\n// this file (not a sibling module) because apps/backend runs this package as\n// raw TS, where an extensionless relative import crashes boot.\n\n/**\n * Snowcone's public hosts, keyed by role. Origins only — no trailing slash,\n * no path. Read these instead of writing the hostname yourself.\n */\nexport const SNOWCONE_HOSTS = {\n /** REST API: shops, orders, AI generation, realtime grants. */\n api: \"https://api.snowcone.app\",\n /** Public mockup-image resolver (`/{productCode}?shop=…&asset=…`). */\n img: \"https://img.snowcone.app\",\n /** Hosted buy page (same grammar as `img`, opens checkout). */\n buy: \"https://buy.snowcone.app\",\n /** Public product / designs catalog (Meilisearch-compatible). */\n search: \"https://search.snowcone.app\",\n /** Render CDN — signed render URLs and the realtime socket. */\n cdn: \"https://cdn.snowcone.app\",\n /** Legacy URL signer. */\n sign: \"https://s.snowcone.app\",\n /** Content-addressed artwork store (ingest handles). */\n raws: \"https://raws.snowcone.app\",\n /** Developer docs. */\n docs: \"https://developers.snowcone.app\",\n /** The storefront site; `/api/launch` says whether orders are open yet. */\n site: \"https://snowcone.app\",\n /** The hosted MCP endpoint; it also serves the photo upload page (`/upload/<token>`). */\n mcp: \"https://mcp.snowcone.app\",\n /** Where draft designs made for a search are stored (a draft's `image_url`). */\n drafts: \"https://agentdraft.storage.snowcone.app\",\n /** Public asset storage: the design conformance kit's golden images and fonts (`/goldens/v1/…`). */\n storage: \"https://2e2c853b83.storage.snowcone.app\",\n} as const;\n\n/** A role in {@link SNOWCONE_HOSTS}. */\nexport type SnowconeHostRole = keyof typeof SNOWCONE_HOSTS;\n\n/** Realtime render socket — derived from the `cdn` host. */\nexport const SNOWCONE_REALTIME_WS_URL = `${SNOWCONE_HOSTS.cdn.replace(/^http/, \"ws\")}/realtime`;\n\n/** Image alignment values. Mirrors the SDK's product art alignment union. */\nexport type ImageAlignment =\n | \"center\"\n | \"top\"\n | \"far-top\"\n | \"bottom\"\n | \"far-bottom\"\n | \"left\"\n | \"far-left\"\n | \"right\"\n | \"far-right\";\n\nexport interface DesignElement {\n type?: \"image\" | \"color\";\n imageUrl?: string;\n text?: string;\n hex?: string;\n placement?: string;\n position?: { x: number; y: number };\n size?: { width: number; height: number };\n alignment?: ImageAlignment;\n tiles?: 0.25 | 0.5 | 1 | 2 | 4;\n width?: number;\n height?: number;\n /**\n * How the design is made: `\"print\"` (the default when absent) or `\"embroidery\"` (thread on the cloth: the mockup\n * keeps the cloth's folds and light over it, not its weave). Any other value is refused (`E_RENDER_PARAM_INVALID`,\n * param `finish`).\n */\n finish?: \"print\" | \"embroidery\";\n}\n\n/**\n * The mockup URL grammar — every query-param NAME lives here ONCE, so the\n * builders, the resolver parser, and both edge workers (`mockup-resolver`,\n * `edge-cache`) can never disagree on what a param is called. `signature` is the\n * developer's L3 sig (on the public/resolver URL); `seal` is the relay sig (on\n * the render URL).\n *\n * NOTE: the render server's own parser mirrors these names and is pinned\n * by its cache-key tests. It stays self-contained (no dependency on\n * this package) so the service can build standalone — this object is the\n * human-facing source of truth both sides follow.\n */\nexport const PARAMS = {\n shop: \"shop\",\n asset: \"asset\",\n assets: \"assets\",\n /**\n * Render a catalog design by reference (ADR-0086): `design=<pairingId|slug>`.\n * The resolver looks the design up in the public `snowcone-designs` index\n * (membership = license) and injects its asset components server-side, so no\n * raw asset URL crosses the wire and no origin allowlisting is involved.\n * Catalog renders are FREE — mutually exclusive with `asset`/`asset.<key>`/\n * `color.<key>` (free = the design as published).\n */\n design: \"design\",\n placement: \"placement\",\n /**\n * Album page selector (ADR-0086 §5): `page=N` (positive integer) picks which\n * page/spread of an album product a mockup renders. Only valid on products\n * whose catalog entry carries an `album` block — the edge resolver maps page\n * N onto the repeating page placement (`page_N` → the geometry of\n * `album.pagePlacement`); the catalog never enumerates `page_1…page_100` and\n * the render server is unchanged.\n */\n page: \"page\",\n variant: \"variant\",\n mockup: \"mockup\",\n width: \"width\",\n grain: \"grain\",\n aspect: \"aspect\",\n /**\n * `view=<r>@<f>`: a crop of a plate's 8:3 strip, for a page hero that shows only part of it ({@link canonicalMockupView}).\n * Goes with `aspect=8:3` only. Without `width=` the crop is delivered at its own pixels; with `width=` at that width when\n * smaller (the box only ever downscales: a page asks crop width x DPR, capped at the crop).\n */\n view: \"view\",\n /**\n * Background color (6-hex, no '#') painted behind the mockup — visible only\n * where the mockup itself has transparency (clean studio shots) — or the\n * reserved `transparent` token: on a mockup whose picture has real\n * transparency it returns a see-through PNG (alpha kept, the product's own\n * shadow as semi-transparent black); on an opaque photo it returns the normal\n * picture. Absent = the shop's configured default, else the render's default.\n * File weight: a see-through 2:3 PNG is a few MB — for downloads and your own\n * compositing; for a page, set the shop colour or pass `bg=<hex>` (a light AVIF).\n */\n bg: \"bg\",\n /**\n * Output format override: only `png`, and only with `bg=transparent` (a\n * see-through PNG). Not required — `bg=transparent` alone already returns the\n * PNG where the picture has transparency; `format=png` makes it a contract:\n * a mockup with nothing see-through is refused (E_ALPHA_SCENE_OPAQUE) instead\n * of answered with an opaque picture.\n */\n format: \"format\",\n /** Live preview/calibration mask overrides (not cached). */\n maskOverrides: \"maskOverrides\",\n /**\n * Render-only option picks (the `affectsCombinations:false` attributes), as a\n * base64 JSON map `{ attributeName: choiceLabel }`. The render server already parses\n * this and resolves per-choice underlays from it; the builder emits it so the\n * edge resolver can forward render-only picks (e.g. a cap's Crown/Strap color)\n * without changing the server grammar.\n */\n optionSelections: \"optionSelections\",\n signature: \"signature\",\n seal: \"seal\",\n} as const;\n\n/**\n * The reserved `bg=` token that explicitly SUPPRESSES the shop's configured\n * default background for one render: on a picture with real transparency the\n * render is a see-through PNG (the product and its own shadow, alpha kept); on\n * an opaque photo it is the normal picture. Precedence is URL `bg` > shop\n * default > white, so without the token there is no per-URL way to a\n * see-through picture.\n */\nexport const BG_TRANSPARENT = \"transparent\";\n\n/** Every value `format=` accepts (the render server refuses anything else: E_FORMAT_UNKNOWN). */\nexport const MOCKUP_FORMATS = [\"png\"] as const;\nexport type MockupFormat = (typeof MOCKUP_FORMATS)[number];\n\n/** Throwing check for the URL builders: `format` is `png` and comes with `bg=transparent`, or the build fails HERE. */\nfunction requireFormat(format: string, bg: string | undefined): MockupFormat {\n if (!(MOCKUP_FORMATS as readonly string[]).includes(format)) {\n throw new Error(`[snowcone] format must be one of ${MOCKUP_FORMATS.join(\", \")} (a see-through PNG with bg=transparent), got \"${format}\"`);\n }\n if ((bg === undefined ? undefined : normalizeBgColor(bg)) !== BG_TRANSPARENT) {\n throw new Error(`[snowcone] format=png returns a see-through picture, so it needs bg: \"transparent\" (got bg ${bg === undefined ? \"absent\" : `\"${bg}\"`})`);\n }\n return format as MockupFormat;\n}\n\n/**\n * Every value `aspect=` accepts. SSOT for the clients (builders, the edge\n * resolver, sdk, www); the render server's own list is rendercenter\n * `shared/src/types.ts` ASPECT_RATIOS and must hold the same values.\n * `16:9` = the mockup's whole frame (omitted from built URLs).\n */\nexport const MOCKUP_ASPECTS = [\"16:9\", \"2:3\", \"3:4\", \"4:5\", \"1:1\", \"1.91:1\", \"9:16\", \"21:9\", \"8:3\", \"app-header\"] as const;\nexport type MockupAspect = (typeof MOCKUP_ASPECTS)[number];\n\n/** A render param outside its valid set (#5519): the same code the edge\n * cache and the render server answer with, so one code means one fix. */\nexport const E_RENDER_PARAM_INVALID = \"E_RENDER_PARAM_INVALID\";\n\nexport function isMockupAspect(value: string): value is MockupAspect {\n return (MOCKUP_ASPECTS as readonly string[]).includes(value);\n}\n\n/**\n * `view=<r>@<f>` (lane shapes #5520, the hero-crop design): a crop of a plate's 8:3 strip that a page asks for when it shows\n * only part of the strip. `r` = the visible window's width / height, rounded UP to 0.1 (1.3 … 2.6; 2.7 = the whole strip at its own px); `f` = the product's\n * centre from the window's left edge as a share of its width, rounded to 0.025 (0.25 … 0.475 with the info panel on the\n * right, 0.525 … 0.75 with it on the left). Only grid values: a page asks one of 14 x 20 crops per mockup. The render box and\n * the edge parse it with the same grid (services/rendercenter/shared/src/view.ts; the vectors in view.test.ts pin both).\n */\nconst viewGrid = (from: number, to: number, step: number) => Array.from({ length: Math.round((to - from) / step) + 1 }, (_, i) => Math.round((from + i * step) * 1000) / 1000);\n/** 1.3 … 2.6, and 2.7 = the WHOLE strip at its own px (f ignored; keyed once as `2.7@0.25`; lead 2026-11-18). */\nexport const MOCKUP_VIEW_SHAPES: readonly number[] = viewGrid(1.3, 2.7, 0.1);\nexport const MOCKUP_VIEW_WHOLE_STRIP: MockupView = \"2.7@0.25\";\nexport const MOCKUP_VIEW_PLACES: readonly number[] = [...viewGrid(0.25, 0.475, 0.025), ...viewGrid(0.525, 0.75, 0.025)];\n/** A canonical view, `'<r>@<f>'` (r with one decimal: `\"1.9@0.375\"`, `\"2.0@0.4\"`). */\nexport type MockupView = `${number}@${number}`;\n\n/** The canonical spelling of a view on the grid, else null (not a view). */\nexport function canonicalMockupView(raw: string): MockupView | null {\n const m = /^\\s*(\\d+(?:\\.\\d+)?)@(\\d+(?:\\.\\d+)?)\\s*$/.exec(String(raw));\n if (!m) return null;\n const r = MOCKUP_VIEW_SHAPES.find((x) => Math.abs(x - Number(m[1])) < 1e-9);\n const f = MOCKUP_VIEW_PLACES.find((x) => Math.abs(x - Number(m[2])) < 1e-9);\n if (r === undefined || f === undefined) return null;\n return r === 2.7 ? MOCKUP_VIEW_WHOLE_STRIP : (`${r.toFixed(1)}@${String(f)}` as MockupView);\n}\n\n/** The bucket a page's window falls in: r rounded UP to 0.1, f to the nearest 0.025 on its side; null past 2.6 (the whole strip: ask {@link MOCKUP_VIEW_WHOLE_STRIP}) or for an empty window. */\nexport function mockupViewFor(windowWidth: number, windowHeight: number, productCentreX: number): MockupView | null {\n if (!(windowWidth > 0 && windowHeight > 0)) return null;\n const rawR = windowWidth / windowHeight;\n const r = MOCKUP_VIEW_SHAPES.find((x) => x >= rawR - 1e-9);\n // wider than 2.6: null = the whole strip. A page asks MOCKUP_VIEW_WHOLE_STRIP for it once the box and the resolver serve 2.7\n // (rendercenter rc#900); until then null keeps today's whole-strip request, so no live page asks a value not yet served.\n if (r === undefined || r === 2.7) return null;\n const rawF = productCentreX / windowWidth;\n const f = MOCKUP_VIEW_PLACES.reduce((best, x) => (Math.abs(x - rawF) < Math.abs(best - rawF) ? x : best), MOCKUP_VIEW_PLACES[0]);\n return `${r.toFixed(1)}@${String(f)}` as MockupView;\n}\n\n/** Throws (typed, the fix in the message) unless `view` is on the grid and goes with aspect 8:3 (and no preset). A width is a\n * downscale (the box never enlarges past the crop's own pixels). */\nexport function requireMockupView(view: string, ctx: { aspect?: string; width?: number; preset?: string }): MockupView {\n const v = canonicalMockupView(view);\n if (!v) throw new Error(`[snowcone] E_VIEW_PARAM_INVALID: view \"${view}\" is not on the grid: <r>@<f>, r one of ${MOCKUP_VIEW_SHAPES.join(\", \")} and f one of ${MOCKUP_VIEW_PLACES.join(\", \")} (mockupViewFor computes it); a scene is mockup=<sceneId>, not view`);\n if (ctx.aspect !== \"8:3\") throw new Error(`[snowcone] E_VIEW_PARAM_INVALID: view is a crop of a plate's 8:3 strip and goes with aspect \"8:3\" only (got ${ctx.aspect === undefined ? \"no aspect\" : `\"${ctx.aspect}\"`})`);\n if (ctx.preset !== undefined) throw new Error(`[snowcone] E_VIEW_PARAM_INVALID: view takes no preset (a preset sets its own aspect); drop preset`);\n if (ctx.width !== undefined && !(Number.isFinite(ctx.width) && ctx.width > 0)) throw new Error(`[snowcone] E_VIEW_PARAM_INVALID: width ${ctx.width} beside view must be a positive number of px (or omit it: the crop's own px)`);\n return v;\n}\n\n/**\n * Platform presets (lane shapes, #5520): \"the perfect size for <platform>\" by name. Pure sugar: a preset becomes\n * `aspect` + `width` in the URL and never appears in it, so two presets of one shape share one cache entry. Widths are\n * the smallest render width (the renderer snaps DOWN to 400, 600, … 2000, 2500, 3000, 4000) at or above the platform's\n * own size, so the picture is never smaller than the platform asks for. Which shapes a given mockup gives is the\n * mockup's (16:9 + 2:3 for every mockup without a plate); asking another is a loud E_MOCKUP_SHAPE_UNAVAILABLE.\n */\nexport const MOCKUP_PRESETS = {\n tiktok: { aspect: \"9:16\", width: 1200 }, // 1080x1920\n \"instagram-story\": { aspect: \"9:16\", width: 1200 }, // 1080x1920 (and Reels)\n \"youtube-shorts\": { aspect: \"9:16\", width: 1200 }, // 1080x1920\n \"instagram-feed\": { aspect: \"4:5\", width: 1200 }, // 1080x1350\n \"instagram-square\": { aspect: \"1:1\", width: 1200 }, // 1080x1080\n \"facebook-feed\": { aspect: \"4:5\", width: 1200 }, // 1080x1350\n \"facebook-link\": { aspect: \"1.91:1\", width: 1200 }, // 1200x628\n \"linkedin-link\": { aspect: \"1.91:1\", width: 1200 }, // 1200x627\n pinterest: { aspect: \"2:3\", width: 1000 }, // 1000x1500\n \"youtube-thumbnail\": { aspect: \"16:9\", width: 1400 },// 1280x720\n \"x-post\": { aspect: \"16:9\", width: 1600 }, // 1600x900\n amazon: { aspect: \"1:1\", width: 2000 }, // 2000x2000 main image\n etsy: { aspect: \"1:1\", width: 2000 }, // 2000x2000\n shopify: { aspect: \"1:1\", width: 2000 }, // 2048x2048 product image, nearest rung\n \"site-hero\": { aspect: \"16:9\", width: 2500 }, // 2560x1440\n \"web-banner\": { aspect: \"21:9\", width: 2500 }, // ultra-wide banner\n \"app-header\": { aspect: \"app-header\", width: 1200 }, // the hero under a phone's status bar (8:9)\n} as const satisfies Record<string, { aspect: MockupAspect; width: number }>;\nexport type MockupPreset = keyof typeof MOCKUP_PRESETS;\nexport const MOCKUP_PRESET_NAMES = Object.keys(MOCKUP_PRESETS) as MockupPreset[];\n\n/** A preset's aspect/width merged with the caller's own: an explicit width wins (a named intent: bigger than the\n * platform's), an explicit aspect that is NOT the preset's is a contradiction and throws (never one silently wins). */\nexport function resolvePreset(preset: string, aspect?: MockupAspect, width?: number): { aspect: MockupAspect; width: number } {\n const p = (MOCKUP_PRESETS as Record<string, { aspect: MockupAspect; width: number }>)[preset];\n if (!p) throw new Error(`[snowcone] E_PRESET_UNKNOWN: preset ${JSON.stringify(preset)}; the presets: ${MOCKUP_PRESET_NAMES.join(\", \")}`);\n if (aspect !== undefined && aspect !== p.aspect) {\n throw new Error(`[snowcone] E_PRESET_ASPECT_CONFLICT: preset \"${preset}\" is aspect ${p.aspect}, but aspect \"${aspect}\" was also given; drop one`);\n }\n return { aspect: p.aspect, width: width ?? p.width };\n}\n\n/**\n * Normalize a background color to its canonical wire form: lowercase 6-hex,\n * no `#` (the `bg=` value, the DB `mockup_bg_color` shape, and the render\n * cache-key spelling are all this one form), or the reserved\n * {@link BG_TRANSPARENT} token. Accepts an optional leading `#` and any case;\n * returns `null` for anything else.\n *\n * SSOT: the builders, the edge resolver, and the buy worker all validate and\n * normalize through this one function so the grammar can never drift.\n */\nexport function normalizeBgColor(raw: string): string | null {\n const value = raw.trim().replace(/^#/, \"\").toLowerCase();\n if (value === BG_TRANSPARENT) return BG_TRANSPARENT;\n return /^[0-9a-f]{6}$/.test(value) ? value : null;\n}\n\n/** Throwing form of {@link normalizeBgColor}, for the URL builders: an invalid\n * `bg` fails at BUILD time, in the caller's stack, not as a later edge 400. */\nfunction requireBgColor(raw: string): string {\n const bg = normalizeBgColor(raw);\n if (bg === null) {\n throw new Error(\n `[snowcone] bg must be a 6-digit hex color ('#' optional, e.g. \"f5f0ea\") or \"transparent\", got \"${raw}\"`\n );\n }\n return bg;\n}\n\ninterface BuildMockupUrlBase {\n productId: string;\n mockupId: string;\n variantId: string;\n design: DesignElement[];\n effects?: { grain?: 1 | 2 };\n /** Background color (6-hex, '#' optional) — see PARAMS.bg. */\n bg?: string;\n /** `png` with `bg: \"transparent\"`: a see-through PNG, refused where nothing is see-through — see PARAMS.format. */\n format?: MockupFormat;\n aspect?: MockupAspect;\n /**\n * Render-only option picks (`affectsCombinations:false` attributes) as\n * `{ attributeName: choiceLabel }`. Emitted as the base64 `optionSelections=`\n * param. These never select the variant; the server uses them to resolve\n * per-choice underlays. Omit when there are none.\n */\n optionSelections?: Record<string, string>;\n /** Mask overrides for live preview/calibration (not cached). */\n maskOverrides?: unknown[];\n}\n\n/** A render width, or a `view` crop of a plate's 8:3 strip (aspect \"8:3\"; at its own px, or at `width` when smaller). */\nexport type BuildMockupUrlOptions = BuildMockupUrlBase & ({ width: number; view?: undefined } | { view: MockupView; aspect: \"8:3\"; width?: number });\n\nexport interface BuildMockupUrlConfig {\n /** Base of the renderer/CDN, e.g. https://cdn.snowcone.app */\n mockupBaseUrl: string;\n /** The shop's public Shop ID (= shop.id). */\n shop: string;\n}\n\n/**\n * The RENDER-URL serializer's readable-vs-base64 picker for a single image. This\n * builds the signed render URL (the bytes the signer↔rendercenter contract pins,\n * shared with the edge resolver) — its `design` is already FULLY RESOLVED into\n * explicit per-placement elements, so base/override broadcast does NOT happen\n * here. Broadcast lives entirely on the PUBLIC builder (`buildPublicMockupUrl`),\n * where ADR-0089 §3 ensures positioning never decides whether the broadcast\n * `asset=` rides; the base64 `assets=` here is purely the lossless serialization\n * for anything the readable form can't carry (positioning/tiling/alignment).\n *\n * Returns `{ imageUrl, placement? }` when the single element fits the readable\n * `asset=` (+ optional `placement=`) form, else null (caller uses `assets=`).\n * Placement geometry is resolved server-side from the catalog, so width/height\n * are irrelevant here.\n */\nfunction asSimpleAsset(\n design: DesignElement[]\n): { imageUrl: string; placement?: string } | null {\n if (design.length !== 1) return null;\n const el = design[0];\n if (el.type === \"color\" || el.hex) return null;\n if (!el.imageUrl) return null;\n if (el.position || el.size || el.tiles != null) return null;\n if (el.alignment && el.alignment !== \"center\") return null;\n return { imageUrl: el.imageUrl, placement: el.placement };\n}\n\n/**\n * Allowed widths — must match the server's allowed list. The server snaps\n * requested widths down to\n * the nearest value in this list; we do the same so URLs are deterministic\n * cache keys.\n */\nexport const ALLOWED_WIDTHS = [\n 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000, 2500, 3000, 4000,\n];\n\n/**\n * Design elements per render — the URL-grammar cap. ONE number, three\n * enforcers: the public resolver (`workers/mockup-resolver`, 400\n * E_TOO_MANY_PLACEMENTS), the buy worker (`workers/buy`, \"Too many\n * placements\") and the render box (`services/rendercenter/shared/src/types.ts`\n * `CACHE_LIMITS.MAX_ELEMENTS`, E_TOO_MANY_ELEMENTS). The box copy cannot\n * import this package (the rendercenter repo builds standalone), so each\n * side pins the literal and names the other in a test — change BOTH.\n * A saved design (`design=<reference>`) is not subject to this cap: its\n * surfaces are fulfilled placement-by-placement, not through one URL.\n */\n// 24: a cut-and-sew garment is one element per printed piece — LA Sublimation's zip hoodie (AFOOES) sends 17\n// (14 front pieces + back + 2 back waistband segments); at 10 its sample-order thumbnail and any all-over design were\n// refused (rendercenter rc#708 raised the box's copy with this one).\nexport const MAX_DESIGN_ELEMENTS = 24;\n\n/**\n * Ceiling on the ASSEMBLED render URL (path + query the resolver seals and\n * hands to the render edge), in characters. The render boxes run Node 22\n * with its default 16 KiB `--max-http-header-size`, and an oversize request\n * line dies there as a bare `431 Request Header Fields Too Large` from the\n * HTTP parser before any code runs — no E_ code, no hint (prod probe\n * 2026-09-06: 7 placements × 1.9 KB asset URLs). 12 KiB leaves headroom for\n * the seal, `pv=`, `debug=`, the relay's own headers and cookies. Checked\n * BEFORE the seal is minted (`renderUrlLengthError`).\n */\nexport const MAX_RENDER_URL_LENGTH = 12 * 1024;\n\n/** Error code the resolver answers with when the assembled render URL exceeds {@link MAX_RENDER_URL_LENGTH}. */\nexport const E_RENDER_URL_TOO_LONG = \"E_RENDER_URL_TOO_LONG\";\n\n/**\n * ADR-0099 D3 / ADR-0095: a short, first-party asset HANDLE. Every artwork\n * URL that went through the ingest chokepoint lives at\n * `art-ingest/<sha256(sourceUrl)>` on the first-party raws origin, so the\n * public grammar accepts `asset…=ingest:<sha256>` — a fixed ~72-character\n * element in place of a third-party URL near the 2048-char per-asset cap.\n * The resolver expands it before building the render URL; cache keys stay\n * on the expanded URL, and it is platform-provenance (no origin allowlist\n * check), like the `default` token.\n */\nexport const INGEST_HANDLE_PREFIX = \"ingest:\";\nexport const INGEST_HANDLE_BASE = `${SNOWCONE_HOSTS.raws}/art-ingest/`;\nexport const E_INGEST_HANDLE_INVALID = \"E_INGEST_HANDLE_INVALID\";\nconst SHA256_HEX = /^[0-9a-f]{64}$/;\n\n/** Is this asset value an `ingest:` handle (well-formed or not)? */\nexport function isIngestHandle(value: unknown): value is string {\n return typeof value === \"string\" && value.startsWith(INGEST_HANDLE_PREFIX);\n}\n\n/**\n * The first-party URL an `ingest:<sha256>` handle names, or null when the\n * handle is malformed (not 64 lowercase hex chars) — reject with\n * {@link E_INGEST_HANDLE_INVALID}; never guess.\n */\nexport function expandIngestHandle(value: string): string | null {\n if (!isIngestHandle(value)) return null;\n const sha = value.slice(INGEST_HANDLE_PREFIX.length);\n return SHA256_HEX.test(sha) ? `${INGEST_HANDLE_BASE}${sha}` : null;\n}\n\n/**\n * The E_RENDER_URL_TOO_LONG message for an assembled render URL, or null\n * when it fits. Names the fix: reference a saved design (`design=`) or send\n * fewer / shorter asset URLs — each placement's asset URL rides the sealed\n * URL base64-encoded (≈ 4/3 of its length), so ten near-cap (2048-char)\n * asset URLs are ~27 KB before the seal.\n */\nexport function renderUrlLengthError(\n relativeRenderUrl: string,\n placementCount?: number\n): string | null {\n const len = relativeRenderUrl.length;\n if (len <= MAX_RENDER_URL_LENGTH) return null;\n const placements =\n placementCount !== undefined ? ` (${placementCount} placement${placementCount === 1 ? \"\" : \"s\"})` : \"\";\n return (\n `Render URL is ${len} characters${placements}; the render service accepts at most ` +\n `${MAX_RENDER_URL_LENGTH}. Each asset URL is embedded in the sealed render URL. ` +\n `Fix: reference a saved design with design=<reference> instead of inline asset URLs, ` +\n `or send fewer placements / shorter asset URLs (drop long query strings and tokens).`\n );\n}\n\n/** Snaps a width down to the nearest ALLOWED_WIDTHS value. */\nexport function normalizeWidth(width: number): number {\n for (let i = ALLOWED_WIDTHS.length - 1; i >= 0; i--) {\n if (ALLOWED_WIDTHS[i] <= width) return ALLOWED_WIDTHS[i];\n }\n return ALLOWED_WIDTHS[0];\n}\n\n/**\n * Normalizes design elements for consistent URL generation:\n * - sorts keys alphabetically,\n * - drops the rendering-irrelevant keys (width, height, type),\n * - drops alignment when it's \"center\" (the default).\n */\nexport function normalizeDesignElements(\n design: DesignElement[]\n): Record<string, unknown>[] {\n return design.map((element) => {\n const normalized: Record<string, unknown> = {};\n const keys = Object.keys(element).sort();\n for (const key of keys) {\n if (key === \"width\" || key === \"height\" || key === \"type\") continue;\n if (\n key === \"alignment\" &&\n (element as Record<string, unknown>)[key] === \"center\"\n ) {\n continue;\n }\n const value = (element as Record<string, unknown>)[key];\n if (value !== undefined && value !== null) normalized[key] = value;\n }\n return normalized;\n });\n}\n\n/**\n * Pure, deterministic, edge-safe builder for the canonical (UNSIGNED) mockup\n * URL. Returns the URL string the signer then HMAC-signs.\n */\nexport function buildMockupUrl(\n options: BuildMockupUrlOptions,\n cfg: BuildMockupUrlConfig\n): string {\n for (const element of options.design) {\n if (element.type === \"image\" && element.imageUrl?.startsWith(\"blob:\")) {\n throw new Error(\n `[snowcone] Cannot generate mockup: design element for placement \"${element.placement}\" ` +\n `uses a blob URL (\"${element.imageUrl.slice(0, 60)}...\"). ` +\n `Blob URLs are local to this browser tab and cannot be downloaded by the mockup rendering server. ` +\n `Upload the image to a publicly accessible URL or convert it to a data URL before requesting a mockup.`\n );\n }\n }\n\n const view = options.view !== undefined ? requireMockupView(options.view, { aspect: options.aspect, width: options.width }) : undefined;\n const width = view ? (options.width !== undefined ? normalizeWidth(options.width) : undefined) : normalizeWidth(options.width as number);\n const base = cfg.mockupBaseUrl.replace(/\\/+$/, \"\");\n const path = `/${encodeURIComponent(options.productId)}`;\n\n // Canonical order, shared with the resolver URL: shop, asset|assets,\n // placement, variant, mockup, width, [optionSelections], [grain], [aspect],\n // [maskOverrides].\n let queryString = `${PARAMS.shop}=${encodeURIComponent(cfg.shop)}`;\n\n // Artwork (ADR-0089 base+override). The readable broadcast `asset=` form is\n // used for a single BASE image; the base64 `assets=` form carries anything the\n // readable form can't express (multi-placement, color, OR a positioned base).\n // Broadcast is a property of one base asset, not one *unpositioned* asset\n // (§3): a positioned single base still emits the broadcast `asset=` AND the\n // `assets=` serialization, so positioning never silently drops broadcast.\n //\n // An EMPTY design is the \"blank item\" case (a bare product with no artwork\n // applied — e.g. a catalog PDP before the shopper customizes). The resolver\n // has a reserved `asset=default` token for exactly this (it substitutes a\n // transparent placeholder server-side → just the product photo). Emitting the\n // old `assets=W10%3D` (base64 `[]`) here 400s at the edge resolver, which\n // rejects `assets` as an unknown param — that shipped as imageless blank\n // PDPs in prod.\n const simple =\n options.design.length === 0\n ? { imageUrl: \"default\" }\n : asSimpleAsset(options.design);\n if (simple) {\n queryString += `&${PARAMS.asset}=${encodeURIComponent(simple.imageUrl)}`;\n if (simple.placement) {\n queryString += `&${PARAMS.placement}=${encodeURIComponent(simple.placement)}`;\n }\n } else {\n const encodedAssets = encodeURIComponent(\n btoa(JSON.stringify(normalizeDesignElements(options.design)))\n );\n queryString += `&${PARAMS.assets}=${encodedAssets}`;\n }\n\n queryString += `&${PARAMS.variant}=${encodeURIComponent(options.variantId)}`;\n queryString += `&${PARAMS.mockup}=${encodeURIComponent(options.mockupId)}`;\n if (width !== undefined) queryString += `&${PARAMS.width}=${width}`;\n\n // Render-only option picks. Keys are sorted so the same selection always\n // produces the same bytes (the URL is the seal input + CDN cache key).\n if (\n options.optionSelections &&\n Object.keys(options.optionSelections).length > 0\n ) {\n const sorted: Record<string, string> = {};\n for (const k of Object.keys(options.optionSelections).sort()) {\n sorted[k] = options.optionSelections[k];\n }\n const optionSelectionsBase64 = btoa(JSON.stringify(sorted));\n queryString += `&${PARAMS.optionSelections}=${encodeURIComponent(\n optionSelectionsBase64\n )}`;\n }\n\n if (options.effects?.grain) {\n queryString += `&${PARAMS.grain}=${options.effects.grain}`;\n }\n if (options.bg) {\n queryString += `&${PARAMS.bg}=${requireBgColor(options.bg)}`;\n }\n if (options.format) {\n queryString += `&${PARAMS.format}=${requireFormat(options.format, options.bg)}`;\n }\n if (options.aspect && options.aspect !== \"16:9\") {\n queryString += `&${PARAMS.aspect}=${encodeURIComponent(options.aspect)}`;\n }\n if (view) queryString += `&${PARAMS.view}=${encodeURIComponent(view)}`;\n if (options.maskOverrides && options.maskOverrides.length > 0) {\n const maskOverridesBase64 = btoa(JSON.stringify(options.maskOverrides));\n queryString += `&${PARAMS.maskOverrides}=${encodeURIComponent(maskOverridesBase64)}`;\n }\n\n return `${base}${path}?${queryString}`;\n}\n\n// ───────────────────────────────────────────────────────────────────────────\n// Public image-CDN URL (ADR-0075 §1) + the developer L3 signature (ADR-0076).\n//\n// This is the BROWSER-FACING surface — the bare URL you drop into `<img src>`.\n// It is intentionally separate from `buildMockupUrl` above (which builds the\n// render URL that the render server verifies with the relay `seal`). The two must\n// never be conflated: the public URL carries the developer's `shop`/`signature`;\n// the render URL carries only the relay `seal`. See ADR-0076 \"Signing & auth\".\n// ───────────────────────────────────────────────────────────────────────────\n\n// ─── Public design grammar (multi-placement) ────────────────────────────────\n// A design is a map of placement key → fill, serialized as per-placement params\n// `asset.<key>` / `color.<key>` / `tile.<key>` / `align.<key>`. Variant picks ride\n// as `opt.<attr>`. These extend the single `asset=` shorthand; the edge resolver\n// translates them into the internal render URL (it never reaches the render server raw).\n\n/** The dotted param families on the public URL: `<prefix><key>`. */\nexport const PARAM_PREFIX = {\n asset: \"asset.\",\n color: \"color.\",\n tile: \"tile.\",\n align: \"align.\",\n opt: \"opt.\",\n /** ADR-0099 bundles: `variant.<role>=<gvid>` — one SKU per member slot. */\n variant: \"variant.\",\n /** ADR-0099 bundles: `pick.<role>=<productCode>` — which alternative fills a slot. */\n pick: \"pick.\",\n} as const;\n\n/** What fills one placement. A bare string is shorthand for `{ src }`. */\nexport type PublicFill =\n | string\n | { src: string; align?: ImageAlignment; tile?: 0.25 | 0.5 | 1 | 2 | 4 }\n | { color: string };\n\n/** A design = placement key → fill. */\nexport type PublicDesign = Record<string, PublicFill>;\n\n/** Variant option picks = attribute → choice (emitted as `opt.<attr>`). */\nexport type PublicOptions = Record<string, string>;\n\n/** Normalized fill returned by {@link parsePublicUrl} (flat, all optional). */\nexport interface ParsedFill {\n /** Image URL (`asset.<key>`). */\n src?: string;\n /** Solid color hex (`color.<key>`). */\n color?: string;\n /** Tile scale (`tile.<key>`). */\n tile?: number;\n /** Alignment (`align.<key>`). */\n align?: string;\n}\n\nexport interface PublicMockupUrlOptions {\n /** The catalog product code, e.g. \"hoodie-black\". Becomes the path. */\n productCode: string;\n /**\n * Single default-placement image — the get-started shorthand (`asset=`).\n * Optional when {@link PublicMockupUrlOptions.design} is provided.\n */\n assetUrl?: string;\n /**\n * Catalog design reference (`design=<pairingId|slug>`, ADR-0086) — renders a\n * published catalog design as-is, for free. Mutually exclusive with\n * `assetUrl`/`design` (the resolver 400s on the combination).\n */\n designRef?: string;\n /**\n * Per-placement OVERRIDES: placement key → fill. Emitted as `asset.<key>` /\n * `color.<key>` / `tile.<key>` / `align.<key>`. Composes WITH `assetUrl`\n * (ADR-0089): the base `asset=` seeds every placement and each entry here\n * overrides that one placement. `design` is the legacy alias for this map.\n * Either name may be supplied; both merge (override wins on key collision).\n */\n design?: PublicDesign;\n /**\n * Alias of {@link PublicMockupUrlOptions.design} reading as the override side\n * of base+override (ADR-0089). Merges with `design` if both are given.\n */\n placements?: PublicDesign;\n /** Variant option picks: attribute → choice. Emitted as `opt.<attr>`. */\n options?: PublicOptions;\n /** The publishable **Shop ID** (= shop.id by default). ADR-0075 §3. */\n shop: string;\n /** Optional render width override. */\n width?: number;\n /**\n * The picture's shape ({@link MOCKUP_ASPECTS}). `\"16:9\"` (or omitting it) is the mockup's default picture (its whole\n * frame, or a plate's 16:9 window) and is omitted from the URL so default URLs stay byte-stable; `\"2:3\"` is the\n * centre portrait. The other shapes come only from mockups made for them (a plate); a mockup that doesn't hold the\n * shape answers E_MOCKUP_SHAPE_UNAVAILABLE with the shapes it holds. See also `preset`.\n */\n aspect?: MockupAspect;\n /**\n * A platform preset ({@link MOCKUP_PRESETS}: `\"tiktok\"`, `\"instagram-feed\"`, `\"pinterest\"`, `\"app-header\"`, …):\n * sets `aspect` and `width` for that platform. An explicit `width` wins; an `aspect` that disagrees throws.\n */\n preset?: MockupPreset;\n /**\n * `view=<r>@<f>` ({@link canonicalMockupView}, {@link mockupViewFor}): a crop of a plate's 8:3 strip for a page that shows\n * only part of it. Needs `aspect: \"8:3\"`; refuses `preset`. Without `width` it is delivered at its own pixels; a `width`\n * smaller than the crop is a downscale (ask crop width x DPR, capped at the crop).\n */\n view?: MockupView;\n /**\n * Background color painted behind the mockup (`bg=`, 6-hex, '#' optional —\n * normalized to lowercase no-'#' so URLs stay byte-stable cache keys), or\n * the reserved `\"transparent\"` token, which suppresses the shop's default\n * for this one render. Visible only where the mockup scene itself has\n * transparency (studio-cutout shots). Omit to fall back to the shop's\n * configured default (`mockup_bg_color` in shop settings), else white.\n * `\"transparent\"` on a picture with real transparency returns a see-through PNG.\n */\n bg?: string;\n /** `\"png\"` with `bg: \"transparent\"`: a see-through PNG, refused where nothing is see-through (see PARAMS.format). */\n format?: MockupFormat;\n /** Optional resolved-default overrides. */\n mockup?: string;\n variant?: string;\n placement?: string;\n /**\n * Album page/spread to render (`page=N`, positive integer, ADR-0086 §5).\n * Only meaningful for products with a catalog `album` block; mutually\n * exclusive with `placement` (the resolver 400s on the combination).\n */\n page?: number;\n}\n\nexport interface PublicMockupUrlConfig {\n /**\n * The public resolver host (no trailing slash). Defaults to\n * `SNOWCONE_HOSTS.img`.\n */\n baseUrl?: string;\n}\n\nconst DEFAULT_PUBLIC_BASE_URL = SNOWCONE_HOSTS.img;\n\n/**\n * Build the public image-CDN mockup URL per the ADR-0075 contract:\n *\n * https://img.snowcone.app/{productCode}?asset={encodeURIComponent(assetUrl)}&shop={shop}\n * [&w=][&mockup=][&variant=][&placement=]\n *\n * Param ORDER here is fixed and human-readable, but the L3 signature is computed\n * over the params SORTED alphabetically (see `canonicalForSig`), so order does\n * not affect signing. This returns the UNSIGNED public URL; to lock down to L3,\n * append `&signature=` via `signDevSig(canonicalForSig(url), secret)`.\n *\n * Pure string assembly — no secret, no `await`, edge/browser/Node safe.\n */\nexport function buildPublicMockupUrl(\n options: PublicMockupUrlOptions,\n cfg: PublicMockupUrlConfig = {}\n): string {\n const base = (cfg.baseUrl ?? DEFAULT_PUBLIC_BASE_URL).replace(/\\/+$/, \"\");\n const path = `/${encodeURIComponent(options.productCode)}`;\n\n // Order here is human-readable; the L3 signature sorts params (see\n // canonicalForSig), so emit order never affects signing. Design/option keys are\n // sorted so the unsigned URL is byte-stable regardless of object key order.\n const enc = encodeURIComponent;\n const parts: string[] = [];\n parts.push(`${PARAMS.shop}=${enc(options.shop)}`);\n\n // Artwork (ADR-0089 base+override): a catalog `design=` reference stands\n // alone (free, mutually exclusive with developer artwork). Otherwise the\n // scalar `asset=` is the BASE that every placement inherits, and the\n // `design`/`placements` map is the per-placement OVERRIDE — BOTH emit\n // together, so a base + a single override is one honest URL. The resolver\n // broadcasts the base across all placements and replaces it where a key\n // overrides; emitting only the map (no base) leaves un-keyed placements blank.\n if (options.designRef !== undefined) {\n parts.push(`${PARAMS.design}=${enc(options.designRef)}`);\n } else {\n if (options.assetUrl !== undefined) {\n parts.push(`${PARAMS.asset}=${enc(options.assetUrl)}`);\n }\n // Merge `design` + `placements` (alias) into one override map; both are the\n // override side of base+override, so a key present in both takes `placements`.\n const overrides: PublicDesign | undefined =\n options.design || options.placements\n ? { ...(options.design ?? {}), ...(options.placements ?? {}) }\n : undefined;\n if (overrides) {\n for (const key of Object.keys(overrides).sort()) {\n const fill = overrides[key];\n const k = enc(key);\n if (typeof fill === \"string\") {\n parts.push(`${PARAM_PREFIX.asset}${k}=${enc(fill)}`);\n } else if (\"color\" in fill) {\n parts.push(`${PARAM_PREFIX.color}${k}=${enc(fill.color)}`);\n } else {\n parts.push(`${PARAM_PREFIX.asset}${k}=${enc(fill.src)}`);\n if (fill.tile !== undefined) {\n parts.push(`${PARAM_PREFIX.tile}${k}=${fill.tile}`);\n }\n if (fill.align !== undefined) {\n parts.push(`${PARAM_PREFIX.align}${k}=${enc(fill.align)}`);\n }\n }\n }\n }\n }\n\n if (options.placement !== undefined) {\n parts.push(`${PARAMS.placement}=${enc(options.placement)}`);\n }\n if (options.page !== undefined) {\n parts.push(`${PARAMS.page}=${options.page}`);\n }\n // Variant option picks.\n if (options.options) {\n for (const attr of Object.keys(options.options).sort()) {\n parts.push(`${PARAM_PREFIX.opt}${enc(attr)}=${enc(options.options[attr])}`);\n }\n }\n if (options.variant !== undefined) {\n parts.push(`${PARAMS.variant}=${enc(options.variant)}`);\n }\n if (options.mockup !== undefined) {\n parts.push(`${PARAMS.mockup}=${enc(options.mockup)}`);\n }\n const view = options.view !== undefined ? requireMockupView(options.view, { aspect: options.aspect, width: options.width, preset: options.preset }) : undefined;\n const shape = options.preset !== undefined ? resolvePreset(options.preset, options.aspect, options.width) : { aspect: options.aspect, width: options.width };\n if (shape.width !== undefined) parts.push(`${PARAMS.width}=${shape.width}`);\n // Aspect: emitted only when non-default (16:9), so default URLs are byte-stable.\n if (shape.aspect !== undefined && shape.aspect !== \"16:9\") {\n parts.push(`${PARAMS.aspect}=${enc(shape.aspect)}`);\n }\n if (view) parts.push(`${PARAMS.view}=${enc(view)}`);\n // Background: validated + canonicalized at build time so the same color\n // always produces the same bytes (URL = CDN cache key) and a bad value\n // fails HERE, in the caller's stack, not as a later edge 400.\n if (options.bg) {\n parts.push(`${PARAMS.bg}=${requireBgColor(options.bg)}`);\n }\n if (options.format) {\n parts.push(`${PARAMS.format}=${requireFormat(options.format, options.bg)}`);\n }\n\n return `${base}${path}?${parts.join(\"&\")}`;\n}\n\n/** The structured parts of a public/resolver URL — the inverse of\n * {@link buildPublicMockupUrl} and the read-side the `mockup-resolver` worker\n * uses so it never hand-rolls `searchParams.get(\"…\")` for the grammar. */\nexport interface ParsedPublicUrl {\n /** Product code from the path (`/{productCode}`). */\n productCode: string;\n /** Shop ID (`shop=`). Null if absent. */\n shop: string | null;\n /** Artwork URL (`asset=`). Null if absent. */\n asset: string | null;\n width?: number;\n /** Mockup canvas aspect ratio (`aspect=`), if present. */\n aspect?: string;\n /** A crop of a plate's 8:3 strip (`view=`), as written (validate with {@link requireMockupView}). */\n view?: string;\n /** Background color behind the mockup (`bg=`), if present — canonical\n * lowercase 6-hex when valid; an invalid wire value is returned VERBATIM so\n * the consumer can reject it loudly. */\n bg?: string;\n /** Output format (`format=`), as written (only `png` is valid; validate before use). */\n format?: string;\n mockup?: string;\n variant?: string;\n placement?: string;\n /** Album page selector (`page=`, ADR-0086 §5), if present and a positive integer. */\n page?: number;\n /** Multi-placement design (`asset.`/`color.`/`tile.`/`align.<key>`), if present. */\n design?: Record<string, ParsedFill>;\n /** Catalog design reference (`design=`, ADR-0086), if present. */\n designRef?: string;\n /** Variant option picks (`opt.<attr>`), if present. On a bundle the keys\n * are role-qualified (`opt.<role>.<attr>` → `\"<role>.<attr>\"`). */\n options?: PublicOptions;\n /** ADR-0099 bundles: per-slot SKU picks (`variant.<role>=<gvid>`), if present. */\n variants?: Record<string, string>;\n /** ADR-0099 bundles: per-slot product picks (`pick.<role>=<productCode>`), if present. */\n picks?: Record<string, string>;\n /** Developer L3 signature (`signature=`), if present. */\n signature?: string;\n}\n\n/**\n * Parse a public/resolver URL — `img.snowcone.app/{productCode}?shop=&asset=…`\n * — into its parts. Pure; accepts an absolute URL string or a `URL`. (For L3\n * verification use the raw string with {@link canonicalForSig}, not this.)\n */\nexport function parsePublicUrl(url: string | URL): ParsedPublicUrl {\n const u = typeof url === \"string\" ? new URL(url) : url;\n const q = u.searchParams;\n const productCode = decodeURIComponent(\n u.pathname.split(\"/\").filter(Boolean)[0] || \"\"\n );\n const widthRaw = q.get(PARAMS.width);\n const width =\n widthRaw != null && Number.isFinite(Number(widthRaw))\n ? Number(widthRaw)\n : undefined;\n const out: ParsedPublicUrl = {\n productCode,\n shop: q.get(PARAMS.shop),\n asset: q.get(PARAMS.asset),\n };\n if (width !== undefined) out.width = width;\n const aspect = q.get(PARAMS.aspect);\n if (aspect) out.aspect = aspect;\n const view = q.get(PARAMS.view);\n if (view !== null) out.view = view;\n const bg = q.get(PARAMS.bg);\n if (bg) out.bg = normalizeBgColor(bg) ?? bg;\n const format = q.get(PARAMS.format);\n if (format) out.format = format;\n const mockup = q.get(PARAMS.mockup);\n if (mockup) out.mockup = mockup;\n const variant = q.get(PARAMS.variant);\n if (variant) out.variant = variant;\n const placement = q.get(PARAMS.placement);\n if (placement) out.placement = placement;\n const pageRaw = q.get(PARAMS.page);\n if (pageRaw != null) {\n const page = Number(pageRaw);\n if (Number.isInteger(page) && page >= 1) out.page = page;\n }\n const signature = q.get(PARAMS.signature);\n if (signature) out.signature = signature;\n const designRef = q.get(PARAMS.design);\n if (designRef) out.designRef = designRef;\n\n // Multi-placement design + variant option picks (the dotted param families).\n // `asset.<key>` / `tile.<key>` / `align.<key>` accumulate into one fill per key.\n const design: Record<string, ParsedFill> = {};\n const opts: PublicOptions = {};\n const variants: Record<string, string> = {};\n const picks: Record<string, string> = {};\n const ensure = (k: string): ParsedFill => {\n let f = design[k];\n if (!f) {\n f = {};\n design[k] = f;\n }\n return f;\n };\n q.forEach((value, rawKey) => {\n if (rawKey.startsWith(PARAM_PREFIX.asset)) {\n ensure(rawKey.slice(PARAM_PREFIX.asset.length)).src = value;\n } else if (rawKey.startsWith(PARAM_PREFIX.color)) {\n ensure(rawKey.slice(PARAM_PREFIX.color.length)).color = value;\n } else if (rawKey.startsWith(PARAM_PREFIX.tile)) {\n const n = Number(value);\n if (Number.isFinite(n)) ensure(rawKey.slice(PARAM_PREFIX.tile.length)).tile = n;\n } else if (rawKey.startsWith(PARAM_PREFIX.align)) {\n ensure(rawKey.slice(PARAM_PREFIX.align.length)).align = value;\n } else if (rawKey.startsWith(PARAM_PREFIX.opt)) {\n opts[rawKey.slice(PARAM_PREFIX.opt.length)] = value;\n } else if (rawKey.startsWith(PARAM_PREFIX.variant)) {\n variants[rawKey.slice(PARAM_PREFIX.variant.length)] = value;\n } else if (rawKey.startsWith(PARAM_PREFIX.pick)) {\n picks[rawKey.slice(PARAM_PREFIX.pick.length)] = value;\n }\n });\n if (Object.keys(design).length > 0) out.design = design;\n if (Object.keys(opts).length > 0) out.options = opts;\n if (Object.keys(variants).length > 0) out.variants = variants;\n if (Object.keys(picks).length > 0) out.picks = picks;\n\n return out;\n}\n\n// ─── Strict public-param validation ─────────────────────────────────────────\n// The resolver used to silently IGNORE unknown query params — a hand-edited\n// `view=<sceneId>` (the MCP tool's option name; the wire param is `mockup=`)\n// rendered the default scene with zero feedback. (`view=` is now the 8:3 crop,\n// `<r>@<f>`; a scene id there is refused by requireMockupView, naming mockup=.) Pre-launch we fail loudly\n// instead: any unknown key 400s at the edge. The predicate lives HERE (the\n// grammar SSOT) so the resolver — and later the buy worker — can never drift\n// from the param names above.\n\n/**\n * Every EXACT param name the public resolver URL accepts. Enumerated from\n * {@link buildPublicMockupUrl} / {@link parsePublicUrl} and the resolver's\n * `handlePublicResolve` — the dotted families (`asset.` / `color.` / `tile.` /\n * `align.` / `opt.`) are handled by {@link PARAM_PREFIX}, not listed here.\n */\nexport const PUBLIC_PARAM_NAMES: readonly string[] = [\n PARAMS.asset,\n PARAMS.design,\n PARAMS.shop,\n PARAMS.placement,\n PARAMS.page,\n PARAMS.variant,\n PARAMS.mockup,\n PARAMS.width,\n PARAMS.aspect,\n PARAMS.view,\n PARAMS.bg,\n PARAMS.format,\n PARAMS.signature,\n];\n\n/** Human-readable allowed grammar, for 400 error messages. */\nexport const PUBLIC_PARAM_GRAMMAR =\n \"asset, asset.<placement>, color.<placement>, tile.<placement>, \" +\n \"align.<placement>, opt.<attribute>, design, shop, variant, mockup, \" +\n \"placement, page, width, aspect, view (<r>@<f>, with aspect=8:3; width optional, a downscale), bg, format (png, with bg=transparent), signature; on a bundle product: \" +\n \"asset.<role>, asset.<role>.<placement>, color.<role>.<placement>, \" +\n \"opt.<role>.<attribute>, variant.<role>, pick.<role>. \" +\n \"Any asset value may be a first-party handle ingest:<sha256>\";\n\n/** Redirect hints for the unknown keys people actually reach for. */\nconst PUBLIC_PARAM_HINTS: Record<string, string> = {\n key: \"use shop=<shopId>\",\n accountId: \"use shop=<shopId>\",\n w: \"use width=<px>\",\n s: \"use signature=<hex>\",\n background: \"use bg=<6-hex> (no '#')\",\n backgroundColor: \"use bg=<6-hex> (no '#')\",\n};\n\n/**\n * Is `key` part of the public resolver URL grammar? Exact names per\n * {@link PUBLIC_PARAM_NAMES}; dotted families count when they carry a\n * non-empty suffix (`asset.front` yes, bare `asset.` no).\n */\nexport function isKnownPublicParam(key: string): boolean {\n if (PUBLIC_PARAM_NAMES.includes(key)) return true;\n for (const prefix of Object.values(PARAM_PREFIX)) {\n if (key.startsWith(prefix) && key.length > prefix.length) return true;\n }\n return false;\n}\n\n/**\n * The query keys of `query` that are NOT part of the public grammar, deduped,\n * in first-seen order. Empty array = the URL is clean.\n */\nexport function unknownPublicParams(\n query: URLSearchParams | URL | string\n): string[] {\n const q =\n query instanceof URLSearchParams\n ? query\n : (typeof query === \"string\" ? new URL(query) : query).searchParams;\n const unknown: string[] = [];\n const seen = new Set<string>();\n // forEach (not .keys()) — matches parsePublicUrl; this package's tsconfig lib\n // has no iterable URLSearchParams.\n q.forEach((_value, key) => {\n if (seen.has(key)) return;\n seen.add(key);\n if (!isKnownPublicParam(key)) unknown.push(key);\n });\n return unknown;\n}\n\n/**\n * Human-facing 400 message for {@link unknownPublicParams} output: names the\n * offending key(s), lists the allowed grammar, and appends a redirect hint for\n * common mistakes (`key=` → `shop=`, `w=` → `width=`, …).\n */\nexport function unknownPublicParamsMessage(unknownKeys: string[]): string {\n const noun = unknownKeys.length === 1 ? \"parameter\" : \"parameters\";\n const quoted = unknownKeys.map((k) => `\"${k}\"`).join(\", \");\n let message = `Unknown query ${noun} ${quoted}. Allowed: ${PUBLIC_PARAM_GRAMMAR}.`;\n for (const k of unknownKeys) {\n const hint = PUBLIC_PARAM_HINTS[k];\n if (hint) message += ` For \"${k}\": ${hint}.`;\n }\n return message;\n}\n\n/**\n * Compute the canonical string an L3 developer signature is taken over\n * (ADR-0076 \"Signing & auth\"; the spec lives here as the single source of truth\n * so the SDK and the worker verifier can never drift):\n *\n * canonical = pathname + \"?\" +\n * (all query params EXCEPT `signature`, sorted alphabetically by key,\n * each \"key=value\" with value EXACTLY as it appears URL-encoded in the URL,\n * joined by \"&\")\n *\n * Crucially, values are taken VERBATIM from the raw query string — we do NOT\n * decode-then-re-encode (which `URLSearchParams.toString()` would do and could\n * change `%20`↔`+`, casing of percent-escapes, etc.). Both signer and verifier\n * must read the bytes the URL already carries.\n */\nexport function canonicalForSig(url: string): string {\n // Split off the path and the raw query. Accept absolute or relative URLs.\n const hashIdx = url.indexOf(\"#\");\n const noHash = hashIdx === -1 ? url : url.slice(0, hashIdx);\n const qIdx = noHash.indexOf(\"?\");\n const beforeQuery = qIdx === -1 ? noHash : noHash.slice(0, qIdx);\n const rawQuery = qIdx === -1 ? \"\" : noHash.slice(qIdx + 1);\n\n // Derive the pathname. For an absolute URL strip scheme://host; for a\n // relative URL the path is everything before the query.\n let pathname: string;\n const schemeMatch = beforeQuery.match(/^[a-zA-Z][a-zA-Z0-9+.-]*:\\/\\//);\n if (schemeMatch) {\n const afterScheme = beforeQuery.slice(schemeMatch[0].length);\n const slashIdx = afterScheme.indexOf(\"/\");\n pathname = slashIdx === -1 ? \"/\" : afterScheme.slice(slashIdx);\n } else {\n pathname = beforeQuery;\n }\n\n // Parse the raw query into [key, rawValue] pairs WITHOUT decoding the value.\n const pairs: { key: string; raw: string }[] = [];\n if (rawQuery.length > 0) {\n for (const segment of rawQuery.split(\"&\")) {\n if (segment.length === 0) continue;\n const eq = segment.indexOf(\"=\");\n const rawKey = eq === -1 ? segment : segment.slice(0, eq);\n const rawValue = eq === -1 ? \"\" : segment.slice(eq + 1);\n // Keys are simple ASCII (asset/shop/width/mockup/variant/placement/\n // signature); decode the key so sorting is by the logical name, keep the\n // value verbatim.\n const key = decodeURIComponent(rawKey);\n if (key === \"signature\") continue; // the signature itself is never signed over\n // `debug` is operator transport (RENDER_DEBUG_SECRET waterfalls), never\n // part of the developer contract — a signer cannot know it will be\n // appended, so it must not participate in signature canonicalization\n // (ADR-0096: waterfall replays append it to already-signed urls).\n if (key === \"debug\") continue;\n pairs.push({ key, raw: rawValue });\n }\n }\n\n pairs.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));\n\n const canonicalQuery = pairs.map((p) => `${p.key}=${p.raw}`).join(\"&\");\n return `${pathname}?${canonicalQuery}`;\n}\n\n/** Hex-encode a byte array. */\nfunction toHex(bytes: Uint8Array): string {\n let out = \"\";\n for (let i = 0; i < bytes.length; i++) {\n out += bytes[i].toString(16).padStart(2, \"0\");\n }\n return out;\n}\n\n/**\n * Produce the developer L3 signature `signature` for a canonical string:\n *\n * s = hex(HMAC_SHA256(secret, canonical)).slice(0, 16)\n *\n * Uses Web Crypto (`crypto.subtle`), available in Workers, browsers, and Node\n * 18+ — so the SDK and the worker compute byte-identical signatures.\n */\nexport async function signDevSig(\n canonical: string,\n secret: string\n): Promise<string> {\n const encoder = new TextEncoder();\n const key = await crypto.subtle.importKey(\n \"raw\",\n encoder.encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"]\n );\n const sigBuf = await crypto.subtle.sign(\"HMAC\", key, encoder.encode(canonical));\n return toHex(new Uint8Array(sigBuf)).slice(0, 16);\n}\n\n/**\n * Verify the developer L3 signature on a public URL. Reads `signature` from the\n * URL, recomputes over `canonicalForSig(url)`, and compares constant-time.\n * Returns false if `signature` is missing or malformed.\n */\nexport async function verifyDevSig(url: string, secret: string): Promise<boolean> {\n // Pull `signature` from the raw query (verbatim — it is hex, so decoding is a no-op,\n // but we stay consistent with canonicalForSig's raw parsing).\n const qIdx = url.indexOf(\"?\");\n if (qIdx === -1) return false;\n const hashIdx = url.indexOf(\"#\");\n const rawQuery =\n hashIdx === -1 ? url.slice(qIdx + 1) : url.slice(qIdx + 1, hashIdx);\n let provided: string | null = null;\n for (const segment of rawQuery.split(\"&\")) {\n const eq = segment.indexOf(\"=\");\n const rawKey = eq === -1 ? segment : segment.slice(0, eq);\n if (decodeURIComponent(rawKey) === \"signature\") {\n provided = eq === -1 ? \"\" : segment.slice(eq + 1);\n break;\n }\n }\n if (!provided) return false;\n\n const expected = await signDevSig(canonicalForSig(url), secret);\n if (expected.length !== provided.length) return false;\n let result = 0;\n for (let i = 0; i < expected.length; i++) {\n result |= expected.charCodeAt(i) ^ provided.charCodeAt(i);\n }\n return result === 0;\n}\n","/**\n * The conformance kit's golden designs (ADR-0115 part 1): one small design per element type and per effect, each a\n * valid design of the current version. An editor that wants its output read by the server checks it the way these\n * are checked: `validateDesign(design).success`, and (next step of the kit) a render on the server's lane that matches\n * the golden's render.\n *\n * Each golden is named for what it exercises. `GOLDEN_ELEMENT_TYPES` lists the element types the format has; the\n * kit's own test fails when a type has no golden, so a new element type cannot land without one.\n */\nimport type { CanvasStateV1 } from \"../schema\";\nimport type { SavedDesign } from \"../saved\";\nimport { SNOWCONE_HOSTS } from \"@snowcone-app/mockup-url\";\n\n/** Every `transformType` the format has (the discriminator of an element). */\nexport const GOLDEN_ELEMENT_TYPES = [\n \"custom\",\n \"distort\",\n \"circle\",\n \"lean\",\n \"arch\",\n \"ascend\",\n \"wave\",\n \"flag\",\n \"image\",\n \"group\",\n \"shape\",\n \"path\",\n] as const;\nexport type GoldenElementType = (typeof GOLDEN_ELEMENT_TYPES)[number];\n\n/** Every effect a golden exercises (beyond the element types). */\nexport const GOLDEN_EFFECTS = [\n \"stroke\",\n \"knockout\",\n \"mask-clip\",\n \"mask-alpha\",\n \"distress\",\n \"rich-text\",\n \"opentype\",\n \"gradient-fill\",\n \"clip-shape\",\n \"artboard-distress\",\n \"custom-font\",\n \"hidden-layer\",\n \"clipping-layer\",\n \"shadow\",\n \"engrave\",\n \"masked-crop\",\n \"artboard-image-mask\",\n \"two-placements\",\n] as const;\nexport type GoldenEffect = (typeof GOLDEN_EFFECTS)[number];\n\nexport interface GoldenDesign {\n /** Stable name: `element/<type>` or `effect/<effect>`. */\n name: string;\n /** What it exercises, so a failing golden says what broke. */\n covers: { elements: GoldenElementType[]; effects: GoldenEffect[] };\n design: CanvasStateV1;\n}\n\nconst ARTBOARD = { id: \"ab-1\", name: \"Front\", x: 0, y: 0, width: 1000, height: 1000, backgroundColor: \"#ffffff\" };\nconst BASE = { x: 500, y: 500, rotation: 0, opacity: 1 };\nconst TEXT = { text: \"SNOWCONE\", fontSize: 96, fontFamily: \"Anton\", color: \"#111111\", textAlign: \"center\" as const };\n/** A public image URL the goldens draw (a 1000 x 1000 test grid). */\nexport const GOLDEN_IMAGE_URL = `${SNOWCONE_HOSTS.storage}/goldens/v1/grid-1000.png`;\n\nfunction one(name: string, covers: GoldenDesign[\"covers\"], elements: Array<Record<string, unknown>>, artboard: Record<string, unknown> = {}, extra: Partial<CanvasStateV1> = {}): GoldenDesign {\n return {\n name,\n covers,\n design: {\n version: 1,\n artboards: [{ ...ARTBOARD, ...artboard, elementIds: elements.map((e) => String(e.id)) }],\n elements,\n activeArtboardId: ARTBOARD.id,\n ...extra,\n } as CanvasStateV1,\n };\n}\n\nconst text = (id: string, transformType: GoldenElementType, transformData?: Record<string, unknown>, more: Record<string, unknown> = {}) => ({\n id,\n ...BASE,\n ...TEXT,\n transformType,\n ...(transformData ? { transformData } : {}),\n ...more,\n});\nconst image = (id: string, more: Record<string, unknown> = {}) => ({\n id,\n ...BASE,\n transformType: \"image\",\n imageUrl: GOLDEN_IMAGE_URL,\n imageAspectRatio: 1,\n transformData: { type: \"image\", width: 600, height: 600, cropX: 0, cropY: 0, cropWidth: 1, cropHeight: 1, flipHorizontal: false, flipVertical: false, borderRadius: 0 },\n ...more,\n});\nconst shape = (id: string, more: Record<string, unknown> = {}, data: Record<string, unknown> = {}) => ({\n id,\n ...BASE,\n transformType: \"shape\",\n transformData: { type: \"shape\", shapeType: \"rectangle\", width: 400, height: 300, fillColor: \"#e4572e\", ...data },\n ...more,\n});\n\nexport const GOLDEN_DESIGNS: readonly GoldenDesign[] = [\n one(\"element/custom\", { elements: [\"custom\"], effects: [] }, [text(\"t-1\", \"custom\", { type: \"custom\", controlPoints: [] })]),\n one(\"element/distort\", { elements: [\"distort\"], effects: [] }, [text(\"t-1\", \"distort\", { type: \"distort\" })]),\n one(\"element/circle\", { elements: [\"circle\"], effects: [] }, [text(\"t-1\", \"circle\", { type: \"circle\", radius: 300, scale: 1, reverse: false })]),\n one(\"element/lean\", { elements: [\"lean\"], effects: [] }, [text(\"t-1\", \"lean\", { type: \"lean\", leanAmount: 20 })]),\n one(\"element/arch\", { elements: [\"arch\"], effects: [] }, [text(\"t-1\", \"arch\", { type: \"arch\", archHeight: 80 })]),\n one(\"element/ascend\", { elements: [\"ascend\"], effects: [] }, [text(\"t-1\", \"ascend\", { type: \"ascend\", ascendAngle: 15 })]),\n one(\"element/wave\", { elements: [\"wave\"], effects: [] }, [text(\"t-1\", \"wave\", { type: \"wave\", amplitude: 30, frequency: 2 })]),\n one(\"element/flag\", { elements: [\"flag\"], effects: [] }, [text(\"t-1\", \"flag\", { type: \"flag\", amplitude: 20, frequency: 1.5 })]),\n one(\"element/image\", { elements: [\"image\"], effects: [] }, [image(\"i-1\")]),\n one(\"element/group\", { elements: [\"group\", \"shape\"], effects: [] }, [\n {\n id: \"g-1\",\n ...BASE,\n transformType: \"group\",\n transformData: { type: \"group\" },\n // children in artboard coordinates, placed symmetrically: the editor sets a group's centre from its children\n children: [shape(\"s-1\", { x: 400, y: 500 }, { width: 100, height: 100 }), shape(\"s-2\", { x: 600, y: 500 }, { width: 100, height: 100 })],\n },\n ]),\n one(\"element/shape\", { elements: [\"shape\"], effects: [] }, [shape(\"s-1\", {}, { shapeType: \"star\", points: 5, innerRadius: 0.5 })]),\n one(\"element/path\", { elements: [\"path\"], effects: [] }, [\n {\n id: \"p-1\",\n ...BASE,\n transformType: \"path\",\n transformData: {\n type: \"path\",\n closed: true,\n width: 400,\n height: 400,\n fillEnabled: true,\n fillColor: \"#2e86ab\",\n points: [\n { id: \"a\", x: 0, y: 0, type: \"corner\" },\n { id: \"b\", x: 400, y: 0, type: \"smooth\", handleIn: { x: 300, y: -50 }, handleOut: { x: 450, y: 50 } },\n { id: \"c\", x: 200, y: 400, type: \"bezier\", handleIn: { x: 300, y: 400 }, handleOut: { x: 100, y: 400 } },\n ],\n },\n },\n ]),\n\n one(\"effect/stroke\", { elements: [\"custom\"], effects: [\"stroke\"] }, [\n text(\"t-1\", \"custom\", undefined, { stroke: { enabled: true, color: \"#000000\", width: 8, lineCap: \"round\", lineJoin: \"round\" } }),\n ]),\n one(\"effect/knockout\", { elements: [\"shape\", \"custom\"], effects: [\"knockout\"] }, [\n shape(\"s-1\", {}, { width: 800, height: 400 }),\n text(\"t-1\", \"custom\", undefined, { blendMode: \"knockout\", knockoutParts: { fill: true, scope: \"artboard\" } }),\n ]),\n one(\"effect/mask-clip\", { elements: [\"image\", \"custom\"], effects: [\"mask-clip\"] }, [\n image(\"i-1\", { masks: [{ id: \"m-1\", type: \"clip\", maskElement: text(\"mt-1\", \"custom\", undefined, { x: 0, y: 0, fontSize: 200 }) }] }),\n ]),\n one(\"effect/mask-alpha\", { elements: [\"image\", \"shape\"], effects: [\"mask-alpha\"] }, [\n image(\"i-1\", { masks: [{ id: \"m-1\", type: \"alpha\", feather: 12, inverted: false, maskElement: shape(\"ms-1\", { x: 0, y: 0 }, { shapeType: \"circle\", width: 400, height: 400 }) }] }),\n ]),\n one(\"effect/distress\", { elements: [\"custom\"], effects: [\"distress\"] }, [\n text(\"t-1\", \"custom\", undefined, { distressEffect: { enabled: true, style: \"worn\", intensity: 60, seed: 12345 } }),\n ]),\n one(\"effect/rich-text\", { elements: [\"custom\"], effects: [\"rich-text\"] }, [\n text(\"t-1\", \"custom\", undefined, {\n richText: { spans: [{ text: \"SNOW\", style: { color: \"#e4572e\", bold: true } }, { text: \"CONE\", style: { italic: true } }] },\n }),\n ]),\n one(\"effect/opentype\", { elements: [\"custom\"], effects: [\"opentype\"] }, [\n text(\"t-1\", \"custom\", undefined, { openTypeFeatures: { liga: true, ss01: true }, letterSpacing: 4, lineHeight: 1.1 }),\n ]),\n one(\"effect/gradient-fill\", { elements: [\"shape\"], effects: [\"gradient-fill\"] }, [\n shape(\"s-1\", {}, { fillColor: undefined, fill: { type: \"linear\", angle: 45, stops: [{ offset: 0, color: \"#e4572e\" }, { offset: 1, color: \"#2e86ab\" }] } }),\n ]),\n one(\"effect/clip-shape\", { elements: [\"image\"], effects: [\"clip-shape\"] }, [image(\"i-1\")], { clipShape: { type: \"rounded\", radius: 120 } }),\n one(\"effect/artboard-distress\", { elements: [\"custom\"], effects: [\"artboard-distress\"] }, [text(\"t-1\", \"custom\")], {\n distressTexture: { enabled: true, textureUrl: \"builtin:grunge-heavy\", intensity: 50 },\n }),\n one(\"effect/custom-font\", { elements: [\"custom\"], effects: [\"custom-font\"] }, [text(\"t-1\", \"custom\", undefined, { fontFamily: \"Golden Brand\" })], {}, {\n customFonts: [{ family: \"Golden Brand\", url: `${SNOWCONE_HOSTS.storage}/goldens/v1/brand.woff2`, weight: 400, style: \"normal\" }],\n }),\n one(\"effect/hidden-layer\", { elements: [\"custom\", \"shape\"], effects: [\"hidden-layer\"] }, [shape(\"s-1\"), text(\"t-1\", \"custom\", undefined, { visible: false })]),\n one(\"effect/shadow\", { elements: [\"custom\"], effects: [\"shadow\"] }, [\n text(\"t-1\", \"custom\", undefined, { shadow: { enabled: true, color: \"#000000\", blur: 12, offsetX: 6, offsetY: 6, opacity: 0.5 } }),\n ]),\n one(\"effect/engrave\", { elements: [\"image\"], effects: [\"engrave\"] }, [\n image(\"i-1\", {\n transformData: {\n type: \"image\", width: 600, height: 600, cropX: 0, cropY: 0, cropWidth: 1, cropHeight: 1, flipHorizontal: false, flipVertical: false, borderRadius: 0,\n maskedCrop: \"frame\",\n engrave: { style: \"photo\", amount: 0, invert: false, sourceUrl: GOLDEN_IMAGE_URL, cutLight: false },\n },\n }),\n ]),\n one(\"effect/masked-crop\", { elements: [\"image\", \"shape\"], effects: [\"masked-crop\", \"mask-clip\"] }, [\n image(\"i-1\", {\n transformData: { type: \"image\", width: 600, height: 600, cropX: 0.25, cropY: 0.25, cropWidth: 0.5, cropHeight: 0.5, flipHorizontal: true, flipVertical: false, borderRadius: 0, maskedCrop: \"frame\" },\n masks: [{ id: \"m-1\", type: \"clip\", maskElement: shape(\"ms-1\", { x: 0, y: 0 }, { shapeType: \"circle\", width: 400, height: 400 }) }],\n }),\n ]),\n one(\"effect/artboard-image-mask\", { elements: [\"image\"], effects: [\"artboard-image-mask\"] }, [image(\"i-1\")], {\n imageMask: { enabled: true, imageUrl: GOLDEN_IMAGE_URL, maskType: \"alpha\", opacity: 100, inverted: false },\n }),\n {\n name: \"effect/two-placements\",\n covers: { elements: [\"custom\", \"shape\"], effects: [\"two-placements\"] },\n design: {\n version: 1,\n artboards: [\n { ...ARTBOARD, id: \"ab-front\", name: \"Front\", elementIds: [\"t-front\"] },\n { ...ARTBOARD, id: \"ab-back\", name: \"Back\", width: 800, height: 1200, elementIds: [\"s-back\"] },\n ],\n elements: [text(\"t-front\", \"custom\"), shape(\"s-back\")],\n activeArtboardId: \"ab-front\",\n } as CanvasStateV1,\n },\n one(\"effect/clipping-layer\", { elements: [\"shape\", \"image\"], effects: [\"clipping-layer\"] }, [shape(\"s-1\", { isClipping: true }), image(\"i-1\")]),\n];\n\n/**\n * A golden as a SAVED design (the editor's change-event shape, what a design's stateUrl stores): elements in one list,\n * each tagged with its artboard's name; the artboards by name. Feed it to `toRenderWire` for the render wire.\n */\nexport function toSavedDesign(design: CanvasStateV1): SavedDesign {\n const artboardOf = new Map<string, string>();\n for (const a of design.artboards) for (const id of a.elementIds) artboardOf.set(id, a.name);\n const active = design.artboards.find((a) => a.id === design.activeArtboardId);\n return {\n elements: design.elements.map((e) => {\n const id = String((e as { id?: unknown }).id);\n const tag = artboardOf.get(id);\n return tag ? { ...(e as object), artboard: tag } : e;\n }),\n artboards: design.artboards.map((a) => {\n const { id: _id, x: _x, y: _y, elementIds: _ids, backgroundType: _bt, backgroundTexture: _tx, previewBackgroundColor: _pv, ...rest } = a;\n return rest;\n }),\n ...(active ? { activeArtboard: active.name } : {}),\n ...(design.customFonts?.length ? { customFonts: design.customFonts } : {}),\n };\n}\n"]}
@@ -0,0 +1,39 @@
1
+ import { a as CanvasStateV1, j as SavedDesign } from '../saved-BOsUdd8W.cjs';
2
+ import 'zod';
3
+
4
+ /**
5
+ * The conformance kit's golden designs (ADR-0115 part 1): one small design per element type and per effect, each a
6
+ * valid design of the current version. An editor that wants its output read by the server checks it the way these
7
+ * are checked: `validateDesign(design).success`, and (next step of the kit) a render on the server's lane that matches
8
+ * the golden's render.
9
+ *
10
+ * Each golden is named for what it exercises. `GOLDEN_ELEMENT_TYPES` lists the element types the format has; the
11
+ * kit's own test fails when a type has no golden, so a new element type cannot land without one.
12
+ */
13
+
14
+ /** Every `transformType` the format has (the discriminator of an element). */
15
+ declare const GOLDEN_ELEMENT_TYPES: readonly ["custom", "distort", "circle", "lean", "arch", "ascend", "wave", "flag", "image", "group", "shape", "path"];
16
+ type GoldenElementType = (typeof GOLDEN_ELEMENT_TYPES)[number];
17
+ /** Every effect a golden exercises (beyond the element types). */
18
+ declare const GOLDEN_EFFECTS: readonly ["stroke", "knockout", "mask-clip", "mask-alpha", "distress", "rich-text", "opentype", "gradient-fill", "clip-shape", "artboard-distress", "custom-font", "hidden-layer", "clipping-layer", "shadow", "engrave", "masked-crop", "artboard-image-mask", "two-placements"];
19
+ type GoldenEffect = (typeof GOLDEN_EFFECTS)[number];
20
+ interface GoldenDesign {
21
+ /** Stable name: `element/<type>` or `effect/<effect>`. */
22
+ name: string;
23
+ /** What it exercises, so a failing golden says what broke. */
24
+ covers: {
25
+ elements: GoldenElementType[];
26
+ effects: GoldenEffect[];
27
+ };
28
+ design: CanvasStateV1;
29
+ }
30
+ /** A public image URL the goldens draw (a 1000 x 1000 test grid). */
31
+ declare const GOLDEN_IMAGE_URL: string;
32
+ declare const GOLDEN_DESIGNS: readonly GoldenDesign[];
33
+ /**
34
+ * A golden as a SAVED design (the editor's change-event shape, what a design's stateUrl stores): elements in one list,
35
+ * each tagged with its artboard's name; the artboards by name. Feed it to `toRenderWire` for the render wire.
36
+ */
37
+ declare function toSavedDesign(design: CanvasStateV1): SavedDesign;
38
+
39
+ export { GOLDEN_DESIGNS, GOLDEN_EFFECTS, GOLDEN_ELEMENT_TYPES, GOLDEN_IMAGE_URL, type GoldenDesign, type GoldenEffect, type GoldenElementType, toSavedDesign };
@@ -0,0 +1,39 @@
1
+ import { a as CanvasStateV1, j as SavedDesign } from '../saved-BOsUdd8W.js';
2
+ import 'zod';
3
+
4
+ /**
5
+ * The conformance kit's golden designs (ADR-0115 part 1): one small design per element type and per effect, each a
6
+ * valid design of the current version. An editor that wants its output read by the server checks it the way these
7
+ * are checked: `validateDesign(design).success`, and (next step of the kit) a render on the server's lane that matches
8
+ * the golden's render.
9
+ *
10
+ * Each golden is named for what it exercises. `GOLDEN_ELEMENT_TYPES` lists the element types the format has; the
11
+ * kit's own test fails when a type has no golden, so a new element type cannot land without one.
12
+ */
13
+
14
+ /** Every `transformType` the format has (the discriminator of an element). */
15
+ declare const GOLDEN_ELEMENT_TYPES: readonly ["custom", "distort", "circle", "lean", "arch", "ascend", "wave", "flag", "image", "group", "shape", "path"];
16
+ type GoldenElementType = (typeof GOLDEN_ELEMENT_TYPES)[number];
17
+ /** Every effect a golden exercises (beyond the element types). */
18
+ declare const GOLDEN_EFFECTS: readonly ["stroke", "knockout", "mask-clip", "mask-alpha", "distress", "rich-text", "opentype", "gradient-fill", "clip-shape", "artboard-distress", "custom-font", "hidden-layer", "clipping-layer", "shadow", "engrave", "masked-crop", "artboard-image-mask", "two-placements"];
19
+ type GoldenEffect = (typeof GOLDEN_EFFECTS)[number];
20
+ interface GoldenDesign {
21
+ /** Stable name: `element/<type>` or `effect/<effect>`. */
22
+ name: string;
23
+ /** What it exercises, so a failing golden says what broke. */
24
+ covers: {
25
+ elements: GoldenElementType[];
26
+ effects: GoldenEffect[];
27
+ };
28
+ design: CanvasStateV1;
29
+ }
30
+ /** A public image URL the goldens draw (a 1000 x 1000 test grid). */
31
+ declare const GOLDEN_IMAGE_URL: string;
32
+ declare const GOLDEN_DESIGNS: readonly GoldenDesign[];
33
+ /**
34
+ * A golden as a SAVED design (the editor's change-event shape, what a design's stateUrl stores): elements in one list,
35
+ * each tagged with its artboard's name; the artboards by name. Feed it to `toRenderWire` for the render wire.
36
+ */
37
+ declare function toSavedDesign(design: CanvasStateV1): SavedDesign;
38
+
39
+ export { GOLDEN_DESIGNS, GOLDEN_EFFECTS, GOLDEN_ELEMENT_TYPES, GOLDEN_IMAGE_URL, type GoldenDesign, type GoldenEffect, type GoldenElementType, toSavedDesign };