@usethrottle/builder-react 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/dist/index.js ADDED
@@ -0,0 +1,2320 @@
1
+ "use client";
2
+ var __defProp = Object.defineProperty;
3
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
+
6
+ // src/renderer.tsx
7
+ import { Fragment } from "react";
8
+ import {
9
+ COMMON_WIDGET_SETTINGS as COMMON_WIDGET_SETTINGS2,
10
+ resolveResponsive as resolveResponsive2,
11
+ safeUrl as safeUrl2,
12
+ upgradeNodes,
13
+ walkNodes as walkNodes2
14
+ } from "@usethrottle/builder-schema";
15
+
16
+ // src/budget.ts
17
+ import { MAX_TEMPLATE_WEIGHT, templateWeight } from "@usethrottle/builder-schema";
18
+ var MAX_RENDERED_NODES = MAX_TEMPLATE_WEIGHT;
19
+ var RenderBudget = class {
20
+ constructor(limit = MAX_RENDERED_NODES) {
21
+ this.limit = limit;
22
+ __publicField(this, "spent", 0);
23
+ }
24
+ /** Takes `count` nodes. False, and nothing taken, when that would pass the limit. */
25
+ take(count = 1) {
26
+ if (this.spent + count > this.limit) return false;
27
+ this.spent += count;
28
+ return true;
29
+ }
30
+ get used() {
31
+ return this.spent;
32
+ }
33
+ get exhausted() {
34
+ return this.spent >= this.limit;
35
+ }
36
+ };
37
+ var fitsBudget = (ast, limit = MAX_RENDERED_NODES) => templateWeight(ast) <= limit;
38
+
39
+ // src/css-compiler.ts
40
+ import {
41
+ COMMON_WIDGET_SETTINGS,
42
+ resolveColumnProps,
43
+ resolveColumnWidths,
44
+ resolveResponsive,
45
+ safeUrl,
46
+ wrapColumnRows
47
+ } from "@usethrottle/builder-schema";
48
+
49
+ // src/warn.ts
50
+ var seen = /* @__PURE__ */ new Set();
51
+ function warnOnce(key, message) {
52
+ if (seen.has(key)) return;
53
+ seen.add(key);
54
+ console.warn(`[throttle-builder] ${message}`);
55
+ }
56
+ var isDevelopment = () => typeof process === "undefined" || process.env?.NODE_ENV !== "production";
57
+
58
+ // src/css-compiler.ts
59
+ var TABLET_QUERY = "(max-width:1024px)";
60
+ var PHONE_QUERY = "(max-width:767px)";
61
+ var SAFE_VALUE = /^[A-Za-z0-9#%.,()\-+*/_: ]{1,200}$/;
62
+ var URL_QUOTE_SAFE = /^[^\s"'\\()<>{};]+$/;
63
+ var ID_RE = /^[a-z0-9]{8,24}$/;
64
+ var PROPERTY_RE = /^--(?:b|w|tb)-[A-Za-z][A-Za-z0-9-]{0,39}$/;
65
+ var COLOR_TOKEN = /* @__PURE__ */ new Set([
66
+ "primary",
67
+ "primary-foreground",
68
+ "background",
69
+ "surface",
70
+ "foreground",
71
+ "muted",
72
+ "muted-foreground",
73
+ "border",
74
+ "border-control",
75
+ "accent",
76
+ "sale",
77
+ "success",
78
+ "warning",
79
+ "danger"
80
+ ]);
81
+ var SPACING_TOKEN = /* @__PURE__ */ new Set(["xs", "s", "m", "l", "xl", "2xl"]);
82
+ var SIZE_TOKEN = /* @__PURE__ */ new Set(["xs", "s", "m", "l", "xl", "2xl", "3xl"]);
83
+ var ALIGN = /* @__PURE__ */ new Set(["left", "center", "right", "justify"]);
84
+ var SELECT_OPTION = /^[a-z0-9][a-z0-9:-]{0,39}$/;
85
+ var px = (value) => `${String(Math.round(value * 100) / 100)}px`;
86
+ function colour(value) {
87
+ if (typeof value !== "string") return null;
88
+ if (value.startsWith("token:")) {
89
+ const name = value.slice(6);
90
+ return COLOR_TOKEN.has(name) ? `var(--tb-color-${name})` : null;
91
+ }
92
+ return /^#[0-9a-fA-F]{6}(?:[0-9a-fA-F]{2})?$/.test(value) ? value : null;
93
+ }
94
+ function spacing(value) {
95
+ if (value === "none") return "0px";
96
+ if (typeof value === "string") return SPACING_TOKEN.has(value) ? `var(--tb-space-${value})` : null;
97
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 400 ? px(value) : null;
98
+ }
99
+ function fontSize(value) {
100
+ if (typeof value === "string") return SIZE_TOKEN.has(value) ? `var(--tb-text-${value})` : null;
101
+ return typeof value === "number" && Number.isFinite(value) && value >= 8 && value <= 200 ? px(value) : null;
102
+ }
103
+ function cssValue(control, value) {
104
+ switch (control) {
105
+ case "color":
106
+ return colour(value);
107
+ case "spacing":
108
+ return spacing(value);
109
+ case "font-size":
110
+ return fontSize(value);
111
+ case "alignment":
112
+ return typeof value === "string" && ALIGN.has(value) ? value : null;
113
+ case "number":
114
+ return typeof value === "number" && Number.isFinite(value) ? String(value) : null;
115
+ case "toggle":
116
+ return typeof value === "boolean" ? value ? "1" : "0" : null;
117
+ case "select":
118
+ return typeof value === "string" && SELECT_OPTION.test(value) ? value : null;
119
+ default:
120
+ return null;
121
+ }
122
+ }
123
+ function put(out, property, value) {
124
+ if (value === null) return;
125
+ if (!PROPERTY_RE.test(property) || !SAFE_VALUE.test(value)) {
126
+ if (isDevelopment()) warnOnce(`css:${property}`, `Dropped an unsafe value for ${property}`);
127
+ return;
128
+ }
129
+ out.set(property, value);
130
+ }
131
+ var COMMON_BY_KEY = new Map(COMMON_WIDGET_SETTINGS.map((field) => [field.key, field]));
132
+ function widgetDecls(node, device, registry) {
133
+ const out = /* @__PURE__ */ new Map();
134
+ const def = registry.widget(node.type, node.v);
135
+ if (def === void 0) return out;
136
+ const fields = new Map([...COMMON_BY_KEY, ...def.settings.map((f) => [f.key, f])]);
137
+ const defaults = {};
138
+ for (const field of fields.values()) if (field.output === "css") defaults[field.key] = field.default;
139
+ const resolved = resolveResponsive({ ...defaults, ...node.props }, node.responsive, device);
140
+ const prefix = node.type.startsWith("custom.") ? "--w-" : "--b-";
141
+ for (const field of fields.values()) {
142
+ if (field.output !== "css") continue;
143
+ const value = resolved[field.key];
144
+ if (value === null || value === void 0) continue;
145
+ if (field.key === "hidden") {
146
+ if (value === true) put(out, "--tb-hide", "none");
147
+ continue;
148
+ }
149
+ put(out, `${prefix}${field.key}`, cssValue(field.control, value));
150
+ }
151
+ return out;
152
+ }
153
+ var ALIGN_ITEMS = { top: "flex-start", center: "center", bottom: "flex-end", stretch: "stretch" };
154
+ var BG_POSITION = /* @__PURE__ */ new Set(["center", "top", "bottom", "left", "right", "top left", "top right", "bottom left", "bottom right"]);
155
+ var BG_SIZE = /* @__PURE__ */ new Set(["cover", "contain", "auto"]);
156
+ function backgroundDecls(out, bg, assets, mediaOrigin) {
157
+ if (bg === void 0) return;
158
+ put(out, "--tb-bg", bg.color === void 0 ? null : colour(bg.color));
159
+ put(out, "--tb-overlay", bg.overlay === void 0 ? null : colour(bg.overlay));
160
+ if (bg.position !== void 0 && BG_POSITION.has(bg.position)) put(out, "--tb-bgpos", bg.position);
161
+ if (bg.size !== void 0 && BG_SIZE.has(bg.size)) put(out, "--tb-bgsize", bg.size);
162
+ const asset = bg.image === void 0 || assets === void 0 || !Object.hasOwn(assets, bg.image) ? void 0 : assets[bg.image];
163
+ if (asset !== void 0 && safeUrl(asset.url, "src", { mediaOrigin }) !== null && URL_QUOTE_SAFE.test(asset.url)) {
164
+ out.set("--tb-bgimg", `url("${asset.url}")`);
165
+ }
166
+ }
167
+ function sectionDecls(section, device, assets, mediaOrigin) {
168
+ const out = /* @__PURE__ */ new Map();
169
+ const p = resolveResponsive(section.props, section.responsive, device);
170
+ if (p.hidden === true) put(out, "--tb-hide", "none");
171
+ const full = p.width === "full";
172
+ put(out, "--tb-maxw", full ? "none" : px(typeof p.contentWidth === "number" ? p.contentWidth : 1200));
173
+ put(out, "--tb-gap", p.gap === void 0 ? null : spacing(p.gap));
174
+ put(out, "--tb-pady", p.paddingY === void 0 ? null : spacing(p.paddingY));
175
+ put(out, "--tb-padx", p.paddingX === void 0 ? null : spacing(p.paddingX));
176
+ if (typeof p.minHeight === "number" && p.minHeight > 0 && p.minHeight <= 2e3) put(out, "--tb-minh", px(p.minHeight));
177
+ if (typeof p.verticalAlign === "string" && Object.hasOwn(ALIGN_ITEMS, p.verticalAlign)) put(out, "--tb-valign", ALIGN_ITEMS[p.verticalAlign]);
178
+ backgroundDecls(out, p.background, assets, mediaOrigin);
179
+ const widths = resolveColumnWidths(section, device);
180
+ const rows = wrapColumnRows(widths);
181
+ const stacked = rows.every((row) => row.length === 1);
182
+ put(out, "--tb-flow", stacked && p.stackOrder === "reverse" ? "column-reverse nowrap" : "row wrap");
183
+ return out;
184
+ }
185
+ function columnWidthDecls(section, device) {
186
+ const widths = resolveColumnWidths(section, device);
187
+ const result = section.columns.map(() => /* @__PURE__ */ new Map());
188
+ for (const row of wrapColumnRows(widths)) {
189
+ for (const index of row) {
190
+ put(result[index], "--tb-cw", String(Math.round(widths[index] / 100 * 1e4) / 1e4));
191
+ put(result[index], "--tb-cn", String(row.length - 1));
192
+ }
193
+ }
194
+ return result;
195
+ }
196
+ function columnDecls(section, index, device, assets, mediaOrigin, widths) {
197
+ const column = section.columns[index];
198
+ const out = new Map(widths);
199
+ const p = resolveColumnProps(column.props, column.responsive, device);
200
+ if (p.hidden === true) put(out, "--tb-hide", "none");
201
+ if (typeof p.verticalAlign === "string" && Object.hasOwn(ALIGN_ITEMS, p.verticalAlign)) put(out, "--tb-self", ALIGN_ITEMS[p.verticalAlign]);
202
+ put(out, "--tb-pad", p.padding === void 0 ? null : spacing(p.padding));
203
+ backgroundDecls(out, p.background, assets, mediaOrigin);
204
+ return out;
205
+ }
206
+ function collect(doc, registry, assets, mediaOrigin) {
207
+ const nodes = [];
208
+ const widget = (node) => {
209
+ if (!ID_RE.test(node.id)) return;
210
+ nodes.push({
211
+ id: node.id,
212
+ decls: {
213
+ desktop: widgetDecls(node, "desktop", registry),
214
+ tablet: widgetDecls(node, "tablet", registry),
215
+ phone: widgetDecls(node, "phone", registry)
216
+ }
217
+ });
218
+ };
219
+ const section = (node) => {
220
+ if (ID_RE.test(node.id)) {
221
+ nodes.push({
222
+ id: node.id,
223
+ decls: {
224
+ desktop: sectionDecls(node, "desktop", assets, mediaOrigin),
225
+ tablet: sectionDecls(node, "tablet", assets, mediaOrigin),
226
+ phone: sectionDecls(node, "phone", assets, mediaOrigin)
227
+ }
228
+ });
229
+ }
230
+ const widths = { desktop: columnWidthDecls(node, "desktop"), tablet: columnWidthDecls(node, "tablet"), phone: columnWidthDecls(node, "phone") };
231
+ node.columns.forEach((column, index) => {
232
+ if (ID_RE.test(column.id)) {
233
+ nodes.push({
234
+ id: column.id,
235
+ decls: {
236
+ desktop: columnDecls(node, index, "desktop", assets, mediaOrigin, widths.desktop[index]),
237
+ tablet: columnDecls(node, index, "tablet", assets, mediaOrigin, widths.tablet[index]),
238
+ phone: columnDecls(node, index, "phone", assets, mediaOrigin, widths.phone[index])
239
+ }
240
+ });
241
+ }
242
+ for (const child of column.children) {
243
+ if (child.type === "inner-section") section(child);
244
+ else widget(child);
245
+ }
246
+ });
247
+ };
248
+ doc.sections.forEach(section);
249
+ return nodes;
250
+ }
251
+ var block = (id, decls) => {
252
+ const body = [...decls].map(([property, value]) => `${property}:${value}`).join(";");
253
+ return body === "" ? "" : `[data-b-id="${id}"]{${body}}`;
254
+ };
255
+ function changed(prev, next) {
256
+ const out = [...next].filter(([property, value]) => prev.get(property) !== value);
257
+ for (const property of prev.keys()) if (!next.has(property)) out.push([property, "initial"]);
258
+ return out;
259
+ }
260
+ function compileResponsiveCss(doc, registry, assets = doc.assets, mediaOrigin = "") {
261
+ const nodes = collect(doc, registry, assets, mediaOrigin);
262
+ const base = nodes.map((n) => block(n.id, n.decls.desktop)).join("");
263
+ const tablet = nodes.map((n) => block(n.id, changed(n.decls.desktop, n.decls.tablet))).join("");
264
+ const phone = nodes.map((n) => block(n.id, changed(n.decls.tablet, n.decls.phone))).join("");
265
+ return base + (tablet === "" ? "" : `@media ${TABLET_QUERY}{${tablet}}`) + (phone === "" ? "" : `@media ${PHONE_QUERY}{${phone}}`);
266
+ }
267
+
268
+ // src/data.ts
269
+ import { walkNodes } from "@usethrottle/builder-schema";
270
+ function stable(value) {
271
+ if (Array.isArray(value)) return `[${value.map(stable).join(",")}]`;
272
+ if (typeof value === "object" && value !== null) {
273
+ const entries2 = Object.entries(value).filter(([, item]) => item !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
274
+ return `{${entries2.map(([k, v]) => `${JSON.stringify(k)}:${stable(v)}`).join(",")}}`;
275
+ }
276
+ return JSON.stringify(value) ?? "null";
277
+ }
278
+ function bindingKey(binding) {
279
+ return "params" in binding ? `${binding.source}?${stable(binding.params)}` : binding.source;
280
+ }
281
+ var isContextBinding = (binding) => binding.source.startsWith("context.");
282
+ function bindingsOf(node, registry) {
283
+ const def = registry.widget(node.type, node.v);
284
+ const out = {};
285
+ for (const [name, input] of Object.entries(def?.data ?? {})) {
286
+ if (input.default !== void 0) out[name] = input.default;
287
+ }
288
+ return { ...out, ...node.data ?? {} };
289
+ }
290
+ function collectBindings(doc, registry) {
291
+ const found = /* @__PURE__ */ new Map();
292
+ walkNodes(doc, (node) => {
293
+ if (node.type === "section" || node.type === "inner-section" || node.type === "column") return;
294
+ for (const binding of Object.values(bindingsOf(node, registry))) {
295
+ const key = bindingKey(binding);
296
+ if (!found.has(key)) found.set(key, binding);
297
+ }
298
+ });
299
+ return found;
300
+ }
301
+ async function resolveBindings(bindings, registry, ctx, options) {
302
+ const jobs = [];
303
+ for (const [key, binding] of bindings) {
304
+ if (isContextBinding(binding) || !("params" in binding)) continue;
305
+ const descriptor = registry.source(binding.source);
306
+ const resolve = registry.resolver(binding.source);
307
+ if (descriptor === void 0 || resolve === void 0) continue;
308
+ if (options.include === "static" && descriptor.perShopper) continue;
309
+ if (options.include === "shopper" && !descriptor.perShopper) continue;
310
+ jobs.push(
311
+ resolve(binding.params, ctx).then(
312
+ (value) => [key, value],
313
+ (error) => {
314
+ warnOnce(`resolve:${binding.source}`, `Data source ${binding.source} failed (${String(error)}); its widgets render without data`);
315
+ return null;
316
+ }
317
+ )
318
+ );
319
+ }
320
+ const settled = await Promise.all(jobs);
321
+ return Object.fromEntries(settled.filter((entry) => entry !== null));
322
+ }
323
+
324
+ // src/node-wrapper.tsx
325
+ import { ANCHOR_RE } from "@usethrottle/builder-schema";
326
+ import { jsx } from "react/jsx-runtime";
327
+ var CUSTOM_WIDGET_CONTAINMENT = {
328
+ contain: "layout paint",
329
+ isolation: "isolate",
330
+ overflow: "clip"
331
+ };
332
+ var PART_NAME = {
333
+ section: "builder-section",
334
+ column: "builder-column",
335
+ widget: "builder-widget"
336
+ };
337
+ function NodeWrapper(props) {
338
+ const { id, part, type, className, anchor, custom, missing, edit, children } = props;
339
+ const Tag = props.as ?? "div";
340
+ const handlers = edit === void 0 ? {} : {
341
+ onClickCapture: (event) => {
342
+ const target = event.target;
343
+ if (target?.closest?.("a[href]") != null) event.preventDefault();
344
+ },
345
+ onClick: (event) => {
346
+ event.stopPropagation();
347
+ edit.onSelect(id);
348
+ },
349
+ onMouseOver: (event) => {
350
+ event.stopPropagation();
351
+ edit.onHover(id);
352
+ },
353
+ onMouseLeave: () => edit.onHover(null)
354
+ };
355
+ return /* @__PURE__ */ jsx(
356
+ Tag,
357
+ {
358
+ className,
359
+ "data-b-id": id,
360
+ "data-throttle-part": PART_NAME[part],
361
+ ...type === void 0 ? {} : { "data-b-type": type },
362
+ ...custom === true && type !== void 0 ? { "data-b-w": type } : {},
363
+ ...missing === true ? { "data-b-missing": "" } : {},
364
+ ...typeof anchor === "string" && ANCHOR_RE.test(anchor) ? { id: anchor } : {},
365
+ ...custom === true ? { style: CUSTOM_WIDGET_CONTAINMENT } : {},
366
+ ...handlers,
367
+ children
368
+ }
369
+ );
370
+ }
371
+
372
+ // src/styles.ts
373
+ var BASE_CSS = `@layer throttle{
374
+ :root{--tb-scale:1;--tb-space-xs:calc(.25rem*var(--tb-scale));--tb-space-s:calc(.5rem*var(--tb-scale));--tb-space-m:calc(1rem*var(--tb-scale));--tb-space-l:calc(1.5rem*var(--tb-scale));--tb-space-xl:calc(2.5rem*var(--tb-scale));--tb-space-2xl:calc(4rem*var(--tb-scale));
375
+ --tb-text-xs:.75rem;--tb-text-s:.875rem;--tb-text-m:1rem;--tb-text-l:1.25rem;--tb-text-xl:1.5rem;--tb-text-2xl:2rem;--tb-text-3xl:2.75rem}
376
+ .tb-root{display:block;inline-size:100%}
377
+ .tb-section,.tb-col,.tb-w{--tb-hide:initial}
378
+ .tb-section,.tb-col{--tb-bg:initial;--tb-bgimg:initial;--tb-bgpos:initial;--tb-bgsize:initial;--tb-overlay:initial}
379
+ .tb-section{--tb-valign:initial;--tb-minh:initial;--tb-pady:initial;--tb-padx:initial;--tb-gap:initial;--tb-maxw:initial;--tb-flow:initial}
380
+ .tb-col{--tb-pad:initial;--tb-self:initial}
381
+ .tb-section{box-sizing:border-box;position:relative;display:var(--tb-hide,flex);flex-direction:column;justify-content:var(--tb-valign,flex-start);min-block-size:var(--tb-minh,0px);padding-block:var(--tb-pady,0px);padding-inline:var(--tb-padx,0px);background-color:var(--tb-bg,transparent);background-image:var(--tb-bgimg,none);background-position:var(--tb-bgpos,center);background-size:var(--tb-bgsize,cover);background-repeat:no-repeat}
382
+ .tb-section::before{content:"";position:absolute;inset:0;background:var(--tb-overlay,transparent);pointer-events:none}
383
+ .tb-inner{box-sizing:border-box;position:relative;inline-size:100%;max-inline-size:var(--tb-maxw,1200px);margin-inline:auto}
384
+ .tb-row{display:flex;flex-flow:var(--tb-flow,row wrap);gap:var(--tb-gap,0px);align-items:stretch}
385
+ .tb-col{box-sizing:border-box;display:var(--tb-hide,flex);flex-direction:column;flex:0 0 auto;inline-size:calc((100% - var(--tb-cn,0)*var(--tb-gap,0px))*var(--tb-cw,1));min-inline-size:0;align-self:var(--tb-self,stretch);padding:var(--tb-pad,0px);background-color:var(--tb-bg,transparent);background-image:var(--tb-bgimg,none);background-position:var(--tb-bgpos,center);background-size:var(--tb-bgsize,cover);background-repeat:no-repeat}
386
+ .tb-w{display:var(--tb-hide,block);min-inline-size:0;margin-block-start:var(--b-spacingTop,var(--w-spacingTop,0px));margin-block-end:var(--b-spacingBottom,var(--w-spacingBottom,0px))}
387
+ .tb-missing{padding:var(--tb-space-s);border:1px dashed var(--tb-color-border-control,currentColor);font-size:var(--tb-text-s)}
388
+ @media (min-width:1025px){.tb-v:not(.tb-only-desktop){display:none!important}}
389
+ @media (min-width:768px) and (max-width:1024px){.tb-v:not(.tb-only-tablet){display:none!important}}
390
+ @media (max-width:767px){.tb-v:not(.tb-only-phone){display:none!important}}
391
+ }`;
392
+
393
+ // src/renderer.tsx
394
+ import { jsx as jsx2, jsxs } from "react/jsx-runtime";
395
+ var DEVICES = ["desktop", "tablet", "phone"];
396
+ var COMMON_BY_KEY2 = new Map(COMMON_WIDGET_SETTINGS2.map((f) => [f.key, f]));
397
+ var withCustomCache = /* @__PURE__ */ new WeakMap();
398
+ function registryFor(doc, base) {
399
+ const snapshots = doc.customWidgets;
400
+ if (snapshots === void 0) return base;
401
+ let perDocument = withCustomCache.get(base);
402
+ if (perDocument === void 0) {
403
+ perDocument = /* @__PURE__ */ new WeakMap();
404
+ withCustomCache.set(base, perDocument);
405
+ }
406
+ let registry = perDocument.get(snapshots);
407
+ if (registry === void 0) {
408
+ try {
409
+ registry = base.withCustom(Object.values(snapshots));
410
+ } catch (error) {
411
+ warnOnce("custom-registry", `Could not register the document's custom widgets: ${String(error)}`);
412
+ registry = base;
413
+ }
414
+ perDocument.set(snapshots, registry);
415
+ }
416
+ return registry;
417
+ }
418
+ var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
419
+ function pickLocale(value, locale) {
420
+ const lang = locale.split("-")[0] ?? locale;
421
+ for (const key of [locale, lang, "en"]) {
422
+ const text = Object.hasOwn(value, key) ? value[key] : void 0;
423
+ if (typeof text === "string" && text !== "") return text;
424
+ }
425
+ for (const text of Object.values(value)) if (typeof text === "string" && text !== "") return text;
426
+ return "";
427
+ }
428
+ function onOrigin(asset, mediaOrigin) {
429
+ if (safeUrl2(asset.url, "src", { mediaOrigin }) === null) return null;
430
+ return { ...asset, variants: asset.variants.filter((v) => safeUrl2(v.url, "src", { mediaOrigin }) !== null) };
431
+ }
432
+ function prepare(field, value, ctx) {
433
+ if (field === void 0 || value === null) return value;
434
+ if (field.translatable === true && isRecord(value)) return pickLocale(value, ctx.locale);
435
+ if (field.control === "image" && typeof value === "string") {
436
+ const asset = Object.hasOwn(ctx.assets, value) ? ctx.assets[value] : void 0;
437
+ return asset === void 0 ? null : onOrigin(asset, ctx.mediaOrigin);
438
+ }
439
+ if (field.control === "link" && isRecord(value) && typeof value.kind === "string") {
440
+ const target = value;
441
+ const raw = ctx.resolveLink?.(target) ?? (target.kind === "url" ? target.href : null);
442
+ return { ...value, href: safeUrl2(raw, "href", { mediaOrigin: ctx.mediaOrigin }) };
443
+ }
444
+ return value;
445
+ }
446
+ function settingsAt(node, fields, device, ctx) {
447
+ const base = {};
448
+ for (const field of fields.values()) base[field.key] = field.default;
449
+ const resolved = resolveResponsive2({ ...base, ...node.props }, node.responsive, device);
450
+ const out = {};
451
+ for (const [key, value] of Object.entries(resolved)) out[key] = prepare(fields.get(key), value, ctx);
452
+ return out;
453
+ }
454
+ function variantsOf(node, def, fields, ctx) {
455
+ const markup = [...fields.values()].filter((f) => f.output === "markup").map((f) => f.key);
456
+ const groups = /* @__PURE__ */ new Map();
457
+ for (const device of DEVICES) {
458
+ const props = settingsAt(node, fields, device, ctx);
459
+ const signature = stable(markup.map((key) => props[key] ?? null));
460
+ const group = groups.get(signature);
461
+ if (group === void 0) groups.set(signature, { devices: [device], props });
462
+ else group.devices.push(device);
463
+ }
464
+ void def;
465
+ return [...groups.values()];
466
+ }
467
+ function hiddenEverywhere(props, responsive) {
468
+ return DEVICES.every(
469
+ (device) => resolveResponsive2({ hidden: props.hidden ?? false }, responsive, device).hidden === true
470
+ );
471
+ }
472
+ var variantClass = (variant) => `tb-v ${variant.devices.map((d) => `tb-only-${d}`).join(" ")}`;
473
+ function renderWidget(node, ctx, registry) {
474
+ const def = registry.widget(node.type, node.v);
475
+ const Component2 = def === void 0 ? void 0 : registry.component(node);
476
+ if (def === void 0 || Component2 === void 0) {
477
+ if (isDevelopment()) {
478
+ warnOnce(`missing:${node.type}@${String(node.v)}`, `Unknown widget ${node.type} v${String(node.v)}; rendering nothing for it`);
479
+ }
480
+ return /* @__PURE__ */ jsx2(NodeWrapper, { id: node.id, part: "widget", type: node.type, className: "tb-w", missing: true, children: ctx.edit !== void 0 && /* @__PURE__ */ jsx2("div", { className: "tb-missing", children: "Widget unavailable: update @usethrottle/storefront-react" }) });
481
+ }
482
+ if (ctx.edit === void 0 && hiddenEverywhere(node.props, node.responsive)) return null;
483
+ const fields = new Map([...COMMON_BY_KEY2, ...def.settings.map((f) => [f.key, f])]);
484
+ const variants = variantsOf(node, def, fields, ctx);
485
+ const data = {};
486
+ for (const [name, binding] of Object.entries(bindingsOf(node, registry))) {
487
+ const key = bindingKey(binding);
488
+ const value = Object.hasOwn(ctx.data, key) ? ctx.data[key] : void 0;
489
+ if (value !== void 0) data[name] = value;
490
+ }
491
+ const custom = node.type.startsWith("custom.");
492
+ const edit = ctx.edit;
493
+ return variants.map((variant, index) => {
494
+ const anchor = variant.props.anchor;
495
+ return /* @__PURE__ */ jsx2(
496
+ NodeWrapper,
497
+ {
498
+ id: node.id,
499
+ part: "widget",
500
+ type: node.type,
501
+ custom,
502
+ edit,
503
+ className: variants.length > 1 ? `tb-w ${variantClass(variant)}` : "tb-w",
504
+ anchor: index === 0 && typeof anchor === "string" && anchor !== "" ? anchor : void 0,
505
+ children: /* @__PURE__ */ jsx2(
506
+ Component2,
507
+ {
508
+ node,
509
+ props: variant.props,
510
+ data,
511
+ editMode: edit !== void 0,
512
+ locale: ctx.locale,
513
+ mediaOrigin: ctx.mediaOrigin,
514
+ resolveLink: ctx.resolveLink,
515
+ inlineEdit: edit === void 0 ? void 0 : (key) => edit.inlineEdit(node.id, key),
516
+ budget: custom ? new RenderBudget() : void 0
517
+ }
518
+ )
519
+ },
520
+ variant.devices.join("-")
521
+ );
522
+ });
523
+ }
524
+ function renderColumn(column, ctx, registry) {
525
+ if (ctx.edit === void 0 && hiddenEverywhere(column.props, column.responsive)) return null;
526
+ return /* @__PURE__ */ jsx2(
527
+ NodeWrapper,
528
+ {
529
+ id: column.id,
530
+ part: "column",
531
+ className: "tb-col",
532
+ anchor: column.props.anchor,
533
+ edit: ctx.edit,
534
+ children: column.children.map(
535
+ (child) => child.type === "inner-section" ? /* @__PURE__ */ jsx2(Fragment, { children: renderSection(child, ctx, registry, true) }, child.id) : /* @__PURE__ */ jsx2(Fragment, { children: renderWidget(child, ctx, registry) }, child.id)
536
+ )
537
+ },
538
+ column.id
539
+ );
540
+ }
541
+ function renderSection(section, ctx, registry, nested = false) {
542
+ if (ctx.edit === void 0 && hiddenEverywhere(section.props, section.responsive)) return null;
543
+ return /* @__PURE__ */ jsx2(
544
+ NodeWrapper,
545
+ {
546
+ id: section.id,
547
+ part: "section",
548
+ as: nested ? "div" : "section",
549
+ className: nested ? "tb-section tb-nested" : "tb-section",
550
+ anchor: section.props.anchor,
551
+ edit: ctx.edit,
552
+ children: /* @__PURE__ */ jsx2("div", { className: "tb-inner", children: /* @__PURE__ */ jsx2("div", { className: "tb-row", children: section.columns.map((column) => renderColumn(column, ctx, registry)) }) })
553
+ }
554
+ );
555
+ }
556
+ function BuilderRenderer(props) {
557
+ const { document: source, registry: base, data, editMode, locale, assets, resolveLink } = props;
558
+ const registry = registryFor(source, base);
559
+ const { doc } = upgradeNodes(source, registry);
560
+ const mediaOrigin = props.mediaOrigin ?? "";
561
+ const ctx = { registry, data, locale, assets, mediaOrigin, resolveLink, edit: editMode };
562
+ const css = compileResponsiveCss(doc, registry, assets, mediaOrigin);
563
+ return /* @__PURE__ */ jsxs("div", { className: "tb-root", "data-throttle-part": "builder-root", children: [
564
+ /* @__PURE__ */ jsx2("style", { href: "tb-base", precedence: "throttle", children: BASE_CSS }),
565
+ css === "" ? null : /* @__PURE__ */ jsx2("style", { children: css }),
566
+ doc.sections.map((section) => /* @__PURE__ */ jsx2(Fragment, { children: renderSection(section, ctx, registry) }, section.id))
567
+ ] });
568
+ }
569
+ function validateRender(doc) {
570
+ const h1 = [];
571
+ walkNodes2(doc, (node) => {
572
+ if (node.type === "basic.heading" && node.props.level === "h1") h1.push(node.id);
573
+ });
574
+ return h1.length > 1 ? [{ code: "MULTIPLE_H1", message: `The page has ${String(h1.length)} level 1 headings; use one`, nodeIds: h1 }] : [];
575
+ }
576
+
577
+ // src/asset-image.tsx
578
+ import { safeUrl as safeUrl3 } from "@usethrottle/builder-schema";
579
+ import { jsx as jsx3 } from "react/jsx-runtime";
580
+ function isFrozenAsset(value) {
581
+ if (typeof value !== "object" || value === null) return false;
582
+ const v = value;
583
+ return typeof v.url === "string" && typeof v.width === "number" && typeof v.height === "number" && Array.isArray(v.variants);
584
+ }
585
+ function AssetImage(props) {
586
+ const { asset, alt, sizes, className, loading = "lazy", style, mediaOrigin } = props;
587
+ const href = (url) => safeUrl3(url, "src", { mediaOrigin });
588
+ if (!isFrozenAsset(asset)) return null;
589
+ const src = href(asset.url);
590
+ if (src === null) return null;
591
+ const srcSet = asset.variants.flatMap((variant) => {
592
+ const url = href(variant.url);
593
+ return url === null || url.includes(",") ? [] : [`${url} ${String(variant.width)}w`];
594
+ }).join(", ");
595
+ return /* @__PURE__ */ jsx3(
596
+ "img",
597
+ {
598
+ src,
599
+ ...srcSet === "" ? {} : { srcSet, sizes: sizes ?? "100vw" },
600
+ width: asset.width,
601
+ height: asset.height,
602
+ alt,
603
+ loading,
604
+ decoding: "async",
605
+ ...className === void 0 ? {} : { className },
606
+ style: { aspectRatio: `${String(asset.width)} / ${String(asset.height)}`, ...style }
607
+ }
608
+ );
609
+ }
610
+
611
+ // src/widget-style.tsx
612
+ import { jsx as jsx4 } from "react/jsx-runtime";
613
+ function WidgetStyle({ css }) {
614
+ if (css === "" || css.includes("<")) return null;
615
+ return /* @__PURE__ */ jsx4("style", { children: css });
616
+ }
617
+
618
+ // src/provider.tsx
619
+ import { Suspense as Suspense4, useCallback, useMemo, useRef as useRef2 } from "react";
620
+ import { createBuilderClient } from "@usethrottle/builder";
621
+ import { SiteDesignProvider, SlotOutletProvider, ThrottleUIProvider } from "@usethrottle/ui";
622
+
623
+ // src/context.ts
624
+ import { createContext, useContext } from "react";
625
+ var BuilderContext = createContext(null);
626
+ var useBuilder = () => useContext(BuilderContext);
627
+
628
+ // src/page.tsx
629
+ import { useEffect as useEffect2 } from "react";
630
+ import { BuilderUnavailableError } from "@usethrottle/builder";
631
+
632
+ // src/load.ts
633
+ function pageOf(raw, initialData) {
634
+ const { document, id: _id, slug, title, path, generation, pageType: _type, updatedAt: _updated, ...meta } = raw;
635
+ return {
636
+ kind: "page",
637
+ slug,
638
+ title,
639
+ path,
640
+ generation,
641
+ document,
642
+ assets: document.assets ?? {},
643
+ initialData,
644
+ meta
645
+ };
646
+ }
647
+ var isRedirect = (raw) => typeof raw.redirectTo === "string";
648
+
649
+ // src/safe-path.ts
650
+ import { safeUrl as safeUrl4 } from "@usethrottle/builder-schema";
651
+ var UNSAFE = /[\x00-\x20\x7f-\xa0\\\u1680\u2000-\u200f\u2028\u2029\u202f\u205f\u3000\ufeff]/;
652
+ var LEADING = /^\/(?![/\\])/;
653
+ function plainPath(path) {
654
+ return !UNSAFE.test(path) && (path === "/" || LEADING.test(path));
655
+ }
656
+ function sitePath(to) {
657
+ if (typeof to !== "string" || !plainPath(to)) return null;
658
+ let decoded;
659
+ try {
660
+ decoded = decodeURIComponent(to);
661
+ } catch {
662
+ return null;
663
+ }
664
+ if (!plainPath(decoded)) return null;
665
+ return safeUrl4(to, "href", { mediaOrigin: "" });
666
+ }
667
+
668
+ // src/shopper-data.ts
669
+ import { useEffect, useState } from "react";
670
+ function useResolvedData(document, registry, locale, include, context) {
671
+ const [data, setData] = useState({});
672
+ useEffect(() => {
673
+ const controller = new AbortController();
674
+ const bindings = collectBindings(document, registry);
675
+ if (bindings.size === 0) return void 0;
676
+ void resolveBindings(
677
+ bindings,
678
+ registry,
679
+ { locale, preview: false, context, signal: controller.signal },
680
+ { include }
681
+ ).then((resolved) => {
682
+ if (!controller.signal.aborted && Object.keys(resolved).length > 0) setData(resolved);
683
+ });
684
+ return () => controller.abort();
685
+ }, [document, registry, locale, include, context]);
686
+ return data;
687
+ }
688
+
689
+ // src/page.tsx
690
+ import { jsx as jsx5 } from "react/jsx-runtime";
691
+ function BuilderPageView({ page, resolve = "shopper" }) {
692
+ const builder = useBuilder();
693
+ if (builder === null) throw new Error("A Builder page needs a BuilderProvider above it");
694
+ return /* @__PURE__ */ jsx5(PageBody, { page, resolve, builder });
695
+ }
696
+ function PageBody({
697
+ page,
698
+ resolve,
699
+ builder
700
+ }) {
701
+ const resolved = useResolvedData(page.document, builder.registry, builder.locale, resolve);
702
+ return /* @__PURE__ */ jsx5(
703
+ BuilderRenderer,
704
+ {
705
+ document: page.document,
706
+ registry: builder.registry,
707
+ data: { ...page.initialData, ...resolved },
708
+ locale: builder.locale,
709
+ assets: page.assets,
710
+ mediaOrigin: builder.mediaOrigin,
711
+ resolveLink: builder.resolveLink
712
+ }
713
+ );
714
+ }
715
+ var entries = /* @__PURE__ */ new WeakMap();
716
+ var ENTRY_MS = 5e3;
717
+ function read(client, slug, locale) {
718
+ let perClient = entries.get(client);
719
+ if (perClient === void 0) {
720
+ perClient = /* @__PURE__ */ new Map();
721
+ entries.set(client, perClient);
722
+ }
723
+ const key = `${locale}|${slug}`;
724
+ let entry = perClient.get(key);
725
+ if (entry === void 0) {
726
+ const made = { status: "pending", promise: Promise.resolve() };
727
+ made.promise = client.pages.get(slug, { locale }).then(
728
+ (raw) => {
729
+ made.status = "done";
730
+ made.value = isRedirect(raw) ? raw : pageOf(raw, {});
731
+ },
732
+ (error) => {
733
+ made.status = "failed";
734
+ made.error = error;
735
+ }
736
+ );
737
+ entry = made;
738
+ const map = perClient;
739
+ map.set(key, made);
740
+ const timer = setTimeout(() => map.delete(key), ENTRY_MS);
741
+ timer.unref?.();
742
+ }
743
+ if (entry.status === "pending") throw entry.promise;
744
+ if (entry.status === "failed") throw entry.error;
745
+ return entry.value;
746
+ }
747
+ function BuilderPage({ slug, initial }) {
748
+ const builder = useBuilder();
749
+ if (builder === null) throw new Error("BuilderPage needs a BuilderProvider above it");
750
+ if (initial !== void 0) return /* @__PURE__ */ jsx5(BuilderPageView, { page: initial });
751
+ if (builder.site.status === "unavailable") {
752
+ throw new BuilderUnavailableError("network", "The Builder is unavailable and has no last good answer");
753
+ }
754
+ if (builder.client === null) {
755
+ throw new Error("BuilderPage reads the page itself: give BuilderProvider a builderKey or a client, or pass `initial`");
756
+ }
757
+ const found = read(builder.client, slug, builder.locale);
758
+ if ("redirectTo" in found) return /* @__PURE__ */ jsx5(Redirect, { to: found.redirectTo });
759
+ return /* @__PURE__ */ jsx5(BuilderPageView, { page: found, resolve: "all" });
760
+ }
761
+ function Redirect({ to }) {
762
+ useEffect2(() => {
763
+ const path = sitePath(to);
764
+ if (path !== null) window.location.replace(path);
765
+ }, [to]);
766
+ return null;
767
+ }
768
+
769
+ // src/part-view.tsx
770
+ import { Component } from "react";
771
+ import { jsx as jsx6 } from "react/jsx-runtime";
772
+ var BoundaryBase = Component ?? class {
773
+ };
774
+ var PartBoundary = class extends BoundaryBase {
775
+ constructor() {
776
+ super(...arguments);
777
+ __publicField(this, "state", { failed: false });
778
+ }
779
+ static getDerivedStateFromError() {
780
+ return { failed: true };
781
+ }
782
+ componentDidCatch(error, _info) {
783
+ warnOnce(`part:${this.props.label}`, `${this.props.label} failed to render (${String(error)}); rendering nothing for it`);
784
+ }
785
+ render() {
786
+ return this.state.failed ? null : this.props.children;
787
+ }
788
+ };
789
+ function contextData(context) {
790
+ if (typeof context !== "object" || context === null) return {};
791
+ return Object.fromEntries(Object.entries(context).map(([key, value]) => [`context.${key}`, value]));
792
+ }
793
+ function PartView({ part, context }) {
794
+ const builder = useBuilder();
795
+ if (builder === null) return null;
796
+ return /* @__PURE__ */ jsx6(PartBody, { part, context, builder });
797
+ }
798
+ function PartBody({
799
+ part,
800
+ context,
801
+ builder
802
+ }) {
803
+ const shopper = useResolvedData(part.document, builder.registry, builder.locale, "shopper", context);
804
+ return /* @__PURE__ */ jsx6(
805
+ BuilderRenderer,
806
+ {
807
+ document: part.document,
808
+ registry: builder.registry,
809
+ data: { ...part.initialData, ...contextData(context), ...shopper },
810
+ locale: builder.locale,
811
+ assets: part.assets,
812
+ mediaOrigin: builder.mediaOrigin,
813
+ resolveLink: builder.resolveLink
814
+ }
815
+ );
816
+ }
817
+
818
+ // src/registry.ts
819
+ import { createRegistry } from "@usethrottle/builder-schema";
820
+
821
+ // src/basics/index.ts
822
+ import { BASIC_WIDGET_DEFINITIONS as BASIC_WIDGET_DEFINITIONS2 } from "@usethrottle/builder-schema";
823
+
824
+ // src/basics/announcement.tsx
825
+ import { useEffect as useEffect3, useState as useState2 } from "react";
826
+ import { Icon, useSiteDesign } from "@usethrottle/ui";
827
+ import { SITE_STRING_DEFAULTS, safeUrl as safeUrl6 } from "@usethrottle/builder-schema";
828
+
829
+ // src/basics/util.tsx
830
+ import { BASIC_WIDGET_DEFINITIONS, resolveResponsive as resolveResponsive3, safeUrl as safeUrl5 } from "@usethrottle/builder-schema";
831
+
832
+ // src/basics/styles.ts
833
+ var BASICS_CSS = `@layer throttle{
834
+ .tb-b-heading{margin:0;text-align:var(--b-align,left);color:var(--b-color,inherit);font-size:var(--b-size,var(--tb-text-l));line-height:1.2;overflow-wrap:anywhere}
835
+ .tb-b-text{text-align:var(--b-align,left);color:var(--b-color,inherit);font-size:var(--b-size,var(--tb-text-m));line-height:1.6;overflow-wrap:anywhere}
836
+ .tb-b-text>:first-child{margin-block-start:0}
837
+ .tb-b-text>:last-child{margin-block-end:0}
838
+ .tb-b-text h2,.tb-b-text h3,.tb-b-text h4{line-height:1.25}
839
+ .tb-b-text blockquote{margin-inline:0;padding-inline-start:var(--tb-space-m);border-inline-start:3px solid var(--tb-color-border,currentColor)}
840
+ .tb-b-text code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.9em}
841
+ .tb-b-link{color:var(--tb-color-primary,currentColor);text-decoration:underline}
842
+ .tb-b-image{text-align:var(--b-align,left);line-height:0}
843
+ .tb-b-image-box{display:inline-block;max-inline-size:100%;inline-size:calc(var(--b-width,100)*1%);vertical-align:top}
844
+ .tb-b-image-box a{display:block}
845
+ .tb-b-img{display:block;inline-size:100%;max-inline-size:100%;block-size:calc(var(--b-height)*1px);object-fit:var(--bx-fit,cover);border-radius:var(--bx-radius,0)}
846
+ .tb-b-empty{padding:var(--tb-space-m);border:1px dashed var(--tb-color-border-control,currentColor);color:var(--tb-color-muted-foreground,inherit);font-size:var(--tb-text-s);line-height:1.4;text-align:center}
847
+ .tb-b-button-wrap{text-align:var(--b-align,left)}
848
+ .tb-b-button{display:inline-block;box-sizing:border-box;min-inline-size:calc(100%*var(--b-fullWidth,0));max-inline-size:100%;border:1px solid transparent;border-radius:var(--throttle-radius,8px);font:inherit;font-weight:600;line-height:1.2;text-align:center;text-decoration:none;cursor:pointer}
849
+ .tb-b-button--s{padding:.4rem .9rem;font-size:var(--tb-text-s)}
850
+ .tb-b-button--m{padding:.65rem 1.25rem;font-size:var(--tb-text-m)}
851
+ .tb-b-button--l{padding:.9rem 1.75rem;font-size:var(--tb-text-l)}
852
+ .tb-b-button--primary{background:var(--tb-color-primary,#111);color:var(--tb-color-primary-foreground,#fff)}
853
+ .tb-b-button--secondary{background:var(--tb-color-muted,#eee);color:var(--tb-color-foreground,#111)}
854
+ .tb-b-button--outline{background:transparent;border-color:var(--tb-color-border-control,currentColor);color:var(--tb-color-foreground,#111)}
855
+ .tb-b-button--link{padding-inline:0;background:transparent;color:var(--tb-color-primary,#111);text-decoration:underline}
856
+ .tb-b-button:hover{filter:brightness(.92)}
857
+ .tb-b-button:focus-visible,.tb-b-menu a:focus-visible,.tb-b-menu-toggle:focus-visible,.tb-b-play:focus-visible,.tb-b-dismiss:focus-visible{outline:2px solid var(--tb-color-primary,currentColor);outline-offset:2px}
858
+ .tb-b-spacer{block-size:var(--b-height,var(--tb-space-l))}
859
+ .tb-b-divider{box-sizing:border-box;inline-size:calc(var(--b-width,100)*1%);margin:0 auto;border:0;border-block-start:calc(var(--b-thickness,1)*1px) var(--bx-style,solid) var(--b-color,var(--tb-color-border,currentColor))}
860
+ .tb-b-video{position:relative;inline-size:100%;aspect-ratio:var(--bx-ratio,16/9);background:var(--tb-color-foreground,#111);border-radius:var(--throttle-radius,8px);overflow:hidden}
861
+ .tb-b-video iframe,.tb-b-play{position:absolute;inset:0;inline-size:100%;block-size:100%;border:0}
862
+ .tb-b-play{display:flex;align-items:center;justify-content:center;padding:0;background:transparent;color:var(--tb-color-background,#fff);cursor:pointer}
863
+ .tb-b-play span{display:grid;place-items:center;inline-size:4rem;block-size:4rem;border-radius:50%;background:rgba(0,0,0,.55)}
864
+ .tb-b-play:hover span{background:rgba(0,0,0,.75)}
865
+ .tb-b-logo{text-align:var(--b-align,left);line-height:0}
866
+ .tb-b-logo a{display:inline-block;color:inherit;text-decoration:none}
867
+ .tb-b-logo img{display:block;block-size:calc(var(--b-height,40)*1px);inline-size:auto;max-inline-size:100%}
868
+ .tb-b-logo-name{display:inline-block;font-size:var(--tb-text-xl);font-weight:700;line-height:calc(var(--b-height,40)*1px)}
869
+ .tb-b-menu{position:relative;text-align:var(--b-align,left);color:var(--b-color,inherit);font-size:var(--b-size,var(--tb-text-m))}
870
+ .tb-b-menu ul{margin:0;padding:0;list-style:none}
871
+ .tb-b-menu a{display:block;padding:var(--tb-space-xs) var(--tb-space-s);color:inherit;text-decoration:none}
872
+ .tb-b-menu a:hover{text-decoration:underline}
873
+ .tb-b-menu li{position:relative}
874
+ .tb-b-menu--vertical li li{padding-inline-start:var(--tb-space-m)}
875
+ .tb-b-menu--h>ul>li{display:inline-block}
876
+ .tb-b-menu--h li>ul{display:none;position:absolute;inset-block-start:100%;inset-inline-start:0;z-index:20;min-inline-size:12rem;padding:var(--tb-space-xs);text-align:start;background:var(--tb-color-background,#fff);color:var(--tb-color-foreground,#111);border:1px solid var(--tb-color-border,#ddd);border-radius:var(--throttle-radius,8px)}
877
+ .tb-b-menu--h li:hover>ul,.tb-b-menu--h li:focus-within>ul{display:block}
878
+ .tb-b-menu-toggle{display:none;align-items:center;justify-content:center;min-inline-size:44px;min-block-size:44px;padding:0;border:0;background:transparent;color:inherit;cursor:pointer}
879
+ @media (max-width:767px){
880
+ .tb-b-menu--drawer-on-phone .tb-b-menu-toggle{display:inline-flex;position:relative;z-index:61}
881
+ .tb-b-menu--drawer-on-phone[data-open=true] .tb-b-menu-toggle{position:fixed;inset-block-start:var(--tb-space-s);inset-inline-end:var(--tb-space-s)}
882
+ .tb-b-menu--drawer-on-phone>ul{display:none}
883
+ .tb-b-menu--drawer-on-phone[data-open=true]>ul{display:block;position:fixed;inset:0;z-index:60;overflow:auto;padding:4.5rem var(--tb-space-m) var(--tb-space-m);text-align:start;background:var(--tb-color-background,#fff);color:var(--tb-color-foreground,#111);font-size:var(--tb-text-l)}
884
+ .tb-b-menu--drawer-on-phone>ul>li{display:block}
885
+ .tb-b-menu--drawer-on-phone li>ul{display:block;position:static;min-inline-size:0;padding:0;border:0;padding-inline-start:var(--tb-space-m)}
886
+ }
887
+ .tb-b-announcement{display:flex;align-items:center;justify-content:center;gap:var(--tb-space-s);box-sizing:border-box;padding:var(--tb-space-s) var(--tb-space-m);text-align:var(--b-align,center);background:var(--b-background,var(--tb-color-primary,#111));color:var(--b-color,var(--tb-color-primary-foreground,#fff));font-size:var(--tb-text-s)}
888
+ .tb-b-announcement-text{flex:1 1 auto}
889
+ .tb-b-announcement a{color:inherit;text-decoration:underline}
890
+ .tb-b-dismiss{display:inline-grid;place-items:center;flex:0 0 auto;min-inline-size:32px;min-block-size:32px;padding:0;border:0;background:transparent;color:inherit;cursor:pointer}
891
+ .tb-b-copyright{margin:0;text-align:var(--b-align,center);color:var(--b-color,var(--tb-color-muted-foreground,inherit));font-size:var(--b-size,var(--tb-text-s))}
892
+ }`;
893
+
894
+ // src/basics/util.tsx
895
+ import { jsx as jsx7 } from "react/jsx-runtime";
896
+ function BasicStyles() {
897
+ return /* @__PURE__ */ jsx7("style", { href: "tb-basics", precedence: "throttle", children: BASICS_CSS });
898
+ }
899
+ var isRecord2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
900
+ var str = (v) => typeof v === "string" && v !== "" ? v : void 0;
901
+ function oneOf(value, allowed, fallback) {
902
+ return allowed.find((candidate) => candidate === value) ?? fallback;
903
+ }
904
+ function hrefOf(link, mediaOrigin) {
905
+ if (!isRecord2(link)) return null;
906
+ return safeUrl5(link.href, "href", { mediaOrigin });
907
+ }
908
+ function Placeholder({ editMode, children }) {
909
+ return editMode ? /* @__PURE__ */ jsx7("div", { className: "tb-b-empty", children }) : null;
910
+ }
911
+ var ID_RE2 = /^[a-z0-9]{8,24}$/;
912
+ var DEVICES2 = ["desktop", "tablet", "phone"];
913
+ function defaultOf(type, key) {
914
+ const def = BASIC_WIDGET_DEFINITIONS.find((d) => d.type === type);
915
+ return def?.settings.find((f) => f.key === key)?.default ?? null;
916
+ }
917
+ function enumCss(node, rules) {
918
+ if (!ID_RE2.test(node.id)) return "";
919
+ const per = { desktop: /* @__PURE__ */ new Map(), tablet: /* @__PURE__ */ new Map(), phone: /* @__PURE__ */ new Map() };
920
+ for (const device of DEVICES2) {
921
+ const settings = { ...Object.fromEntries(rules.map((r) => [r.key, defaultOf(node.type, r.key)])), ...node.props };
922
+ const resolved = resolveResponsive3(settings, node.responsive, device);
923
+ for (const rule of rules) {
924
+ const value = resolved[rule.key];
925
+ const fallback = defaultOf(node.type, rule.key);
926
+ const pick = typeof value === "string" && Object.hasOwn(rule.values, value) ? value : String(fallback);
927
+ const css = Object.hasOwn(rule.values, pick) ? rule.values[pick] : void 0;
928
+ if (css !== void 0) per[device].set(rule.property, css);
929
+ }
930
+ }
931
+ const block2 = (decls) => decls.length === 0 ? "" : `[data-b-id="${node.id}"]{${decls.map(([p, v]) => `${p}:${v}`).join(";")}}`;
932
+ const diff = (prev, next) => [...next].filter(([p, v]) => prev.get(p) !== v);
933
+ const tablet = block2(diff(per.desktop, per.tablet));
934
+ const phone = block2(diff(per.tablet, per.phone));
935
+ return block2([...per.desktop]) + (tablet === "" ? "" : `@media (max-width:1024px){${tablet}}`) + (phone === "" ? "" : `@media (max-width:767px){${phone}}`);
936
+ }
937
+
938
+ // src/basics/announcement.tsx
939
+ import { Fragment as Fragment2, jsx as jsx8, jsxs as jsxs2 } from "react/jsx-runtime";
940
+ var KEY = "tb-announcement-dismissed";
941
+ function read2(message) {
942
+ try {
943
+ return window.sessionStorage.getItem(KEY) === message;
944
+ } catch {
945
+ return false;
946
+ }
947
+ }
948
+ function write(message) {
949
+ try {
950
+ window.sessionStorage.setItem(KEY, message);
951
+ } catch {
952
+ }
953
+ }
954
+ function Announcement({ props, mediaOrigin, editMode }) {
955
+ const design = useSiteDesign();
956
+ const message = design?.announcement?.message;
957
+ const [dismissed, setDismissed] = useState2(false);
958
+ useEffect3(() => {
959
+ if (message !== void 0 && read2(message)) setDismissed(true);
960
+ }, [message]);
961
+ if (message === void 0) {
962
+ return /* @__PURE__ */ jsxs2(Fragment2, { children: [
963
+ /* @__PURE__ */ jsx8(BasicStyles, {}),
964
+ /* @__PURE__ */ jsx8(Placeholder, { editMode, children: "No announcement: turn one on in Site settings" })
965
+ ] });
966
+ }
967
+ if (dismissed && !editMode) return null;
968
+ const href = safeUrl6(design?.announcement?.href, "href", { mediaOrigin });
969
+ const strings = design?.strings;
970
+ const dismissLabel = (strings !== void 0 && Object.hasOwn(strings, "announcement.dismiss") ? str(strings["announcement.dismiss"]) : void 0) ?? SITE_STRING_DEFAULTS["announcement.dismiss"];
971
+ return /* @__PURE__ */ jsxs2(Fragment2, { children: [
972
+ /* @__PURE__ */ jsx8(BasicStyles, {}),
973
+ /* @__PURE__ */ jsxs2("div", { className: "tb-b-announcement", role: "region", "aria-label": message, children: [
974
+ /* @__PURE__ */ jsx8("span", { className: "tb-b-announcement-text", children: href === null ? message : /* @__PURE__ */ jsx8("a", { href, children: message }) }),
975
+ props.dismissible === true && /* @__PURE__ */ jsx8(
976
+ "button",
977
+ {
978
+ type: "button",
979
+ className: "tb-b-dismiss",
980
+ onClick: () => {
981
+ write(message);
982
+ setDismissed(true);
983
+ },
984
+ children: /* @__PURE__ */ jsx8(Icon, { name: "close", size: 16, label: dismissLabel })
985
+ }
986
+ )
987
+ ] })
988
+ ] });
989
+ }
990
+
991
+ // src/basics/button.tsx
992
+ import { Fragment as Fragment3, jsx as jsx9, jsxs as jsxs3 } from "react/jsx-runtime";
993
+ var STYLES = ["primary", "secondary", "outline", "link"];
994
+ var SIZES = ["s", "m", "l"];
995
+ function Button({ props, mediaOrigin, inlineEdit }) {
996
+ const href = hrefOf(props.link, mediaOrigin);
997
+ const className = `tb-b-button tb-b-button--${oneOf(props.style, STYLES, "primary")} tb-b-button--${oneOf(props.size, SIZES, "m")}`;
998
+ const label = inlineEdit?.("label") ?? str(props.label) ?? "";
999
+ return /* @__PURE__ */ jsxs3(Fragment3, { children: [
1000
+ /* @__PURE__ */ jsx9(BasicStyles, {}),
1001
+ /* @__PURE__ */ jsx9("div", { className: "tb-b-button-wrap", children: /* @__PURE__ */ jsx9("a", { className, ...href === null ? {} : { href }, children: label }) })
1002
+ ] });
1003
+ }
1004
+
1005
+ // src/basics/copyright.tsx
1006
+ import { useSiteDesign as useSiteDesign2 } from "@usethrottle/ui";
1007
+ import { SITE_STRING_DEFAULTS as SITE_STRING_DEFAULTS2 } from "@usethrottle/builder-schema";
1008
+ import { Fragment as Fragment4, jsx as jsx10, jsxs as jsxs4 } from "react/jsx-runtime";
1009
+ function Copyright(_) {
1010
+ const design = useSiteDesign2();
1011
+ const strings = design?.strings;
1012
+ const template = strings !== void 0 && Object.hasOwn(strings, "footer.copyright") ? str(strings["footer.copyright"]) : void 0;
1013
+ const line = (template ?? SITE_STRING_DEFAULTS2["footer.copyright"]).replace("{year}", () => String((/* @__PURE__ */ new Date()).getFullYear())).replace("{store}", () => str(design?.brand?.storeName) ?? "").replace(/\s{2,}/g, " ").replace(/\s+([.,])/g, "$1");
1014
+ return /* @__PURE__ */ jsxs4(Fragment4, { children: [
1015
+ /* @__PURE__ */ jsx10(BasicStyles, {}),
1016
+ /* @__PURE__ */ jsx10("p", { className: "tb-b-copyright", children: line })
1017
+ ] });
1018
+ }
1019
+
1020
+ // src/basics/divider.tsx
1021
+ import { Fragment as Fragment5, jsx as jsx11, jsxs as jsxs5 } from "react/jsx-runtime";
1022
+ var RULES = [{ key: "style", property: "--bx-style", values: { solid: "solid", dashed: "dashed", dotted: "dotted" } }];
1023
+ function Divider({ node }) {
1024
+ return /* @__PURE__ */ jsxs5(Fragment5, { children: [
1025
+ /* @__PURE__ */ jsx11(BasicStyles, {}),
1026
+ /* @__PURE__ */ jsx11(WidgetStyle, { css: enumCss(node, RULES) }),
1027
+ /* @__PURE__ */ jsx11("hr", { className: "tb-b-divider" })
1028
+ ] });
1029
+ }
1030
+
1031
+ // src/basics/heading.tsx
1032
+ import { Fragment as Fragment6, jsx as jsx12, jsxs as jsxs6 } from "react/jsx-runtime";
1033
+ var LEVELS = ["h1", "h2", "h3", "h4", "h5", "h6"];
1034
+ function Heading({ props, inlineEdit }) {
1035
+ const Tag = oneOf(props.level, LEVELS, "h2");
1036
+ return /* @__PURE__ */ jsxs6(Fragment6, { children: [
1037
+ /* @__PURE__ */ jsx12(BasicStyles, {}),
1038
+ /* @__PURE__ */ jsx12(Tag, { className: "tb-b-heading", children: inlineEdit?.("text") ?? str(props.text) ?? "" })
1039
+ ] });
1040
+ }
1041
+
1042
+ // src/basics/image.tsx
1043
+ import { safeUrl as safeUrl7 } from "@usethrottle/builder-schema";
1044
+ import { Fragment as Fragment7, jsx as jsx13, jsxs as jsxs7 } from "react/jsx-runtime";
1045
+ var RULES2 = [
1046
+ { key: "radius", property: "--bx-radius", values: { none: "0", s: "4px", m: "8px", l: "16px", full: "9999px" } },
1047
+ { key: "fit", property: "--bx-fit", values: { cover: "cover", contain: "contain" } }
1048
+ ];
1049
+ function Image({ node, props, mediaOrigin, editMode }) {
1050
+ const href = hrefOf(props.link, mediaOrigin);
1051
+ const decorative = props.decorative === true;
1052
+ const alt = decorative ? "" : typeof props.alt === "string" ? props.alt : "";
1053
+ const asset = isFrozenAsset(props.image) ? props.image : void 0;
1054
+ const image = /* @__PURE__ */ jsx13(AssetImage, { asset, mediaOrigin, alt, className: "tb-b-img", sizes: "(max-width: 767px) 100vw, 50vw" });
1055
+ const shown = asset !== void 0 && safeUrl7(asset.url, "src", { mediaOrigin }) !== null;
1056
+ return /* @__PURE__ */ jsxs7(Fragment7, { children: [
1057
+ /* @__PURE__ */ jsx13(BasicStyles, {}),
1058
+ /* @__PURE__ */ jsx13(WidgetStyle, { css: enumCss(node, RULES2) }),
1059
+ shown ? /* @__PURE__ */ jsx13("div", { className: "tb-b-image", children: /* @__PURE__ */ jsx13("div", { className: "tb-b-image-box", children: href === null ? image : /* @__PURE__ */ jsx13("a", { href, children: image }) }) }) : /* @__PURE__ */ jsx13(Placeholder, { editMode, children: asset === void 0 ? "Choose an image" : "Image unavailable" })
1060
+ ] });
1061
+ }
1062
+
1063
+ // src/basics/logo.tsx
1064
+ import { useSiteDesign as useSiteDesign3 } from "@usethrottle/ui";
1065
+ import { safeUrl as safeUrl8 } from "@usethrottle/builder-schema";
1066
+ import { Fragment as Fragment8, jsx as jsx14, jsxs as jsxs8 } from "react/jsx-runtime";
1067
+ function Logo({ props, mediaOrigin, editMode }) {
1068
+ const design = useSiteDesign3();
1069
+ const scheme = design?.theme?.colorScheme ?? "auto";
1070
+ const src = (url) => url === void 0 ? void 0 : safeUrl8(url, "src", { mediaOrigin }) ?? void 0;
1071
+ const light = src(design?.brand?.logo?.light);
1072
+ const dark = src(design?.brand?.logo?.dark);
1073
+ const main = scheme === "dark" ? dark ?? light : light ?? dark;
1074
+ const name = str(design?.brand?.storeName);
1075
+ const href = hrefOf(props.link, mediaOrigin) ?? "/";
1076
+ const alt = name ?? "";
1077
+ let content = null;
1078
+ if (main !== void 0) {
1079
+ const img = /* @__PURE__ */ jsx14("img", { src: main, alt, decoding: "async" });
1080
+ content = scheme === "auto" && light !== void 0 && dark !== void 0 ? /* @__PURE__ */ jsxs8("picture", { children: [
1081
+ /* @__PURE__ */ jsx14("source", { media: "(prefers-color-scheme: dark)", srcSet: dark }),
1082
+ img
1083
+ ] }) : img;
1084
+ } else if (name !== void 0) {
1085
+ content = /* @__PURE__ */ jsx14("span", { className: "tb-b-logo-name", children: name });
1086
+ }
1087
+ return /* @__PURE__ */ jsxs8(Fragment8, { children: [
1088
+ /* @__PURE__ */ jsx14(BasicStyles, {}),
1089
+ content === null ? /* @__PURE__ */ jsx14(Placeholder, { editMode, children: "Logo: add one in Site settings" }) : /* @__PURE__ */ jsx14("div", { className: "tb-b-logo", children: /* @__PURE__ */ jsx14("a", { href, children: content }) })
1090
+ ] });
1091
+ }
1092
+
1093
+ // src/basics/menu.tsx
1094
+ import { useId, useRef, useState as useState3 } from "react";
1095
+ import { Icon as Icon2, useSiteDesign as useSiteDesign4 } from "@usethrottle/ui";
1096
+ import { SITE_STRING_DEFAULTS as SITE_STRING_DEFAULTS3, safeUrl as safeUrl9 } from "@usethrottle/builder-schema";
1097
+ import { Fragment as Fragment9, jsx as jsx15, jsxs as jsxs9 } from "react/jsx-runtime";
1098
+ var LAYOUTS = ["horizontal", "vertical", "drawer-on-phone"];
1099
+ var MAX_DEPTH = 3;
1100
+ function List({ items, mediaOrigin, depth = 0, id, onNavigate }) {
1101
+ const shown = items.flatMap((item) => {
1102
+ const href = safeUrl9(item.href, "href", { mediaOrigin });
1103
+ return href === null ? [] : [{ item, href }];
1104
+ });
1105
+ if (shown.length === 0) return null;
1106
+ return /* @__PURE__ */ jsx15("ul", { ...id === void 0 ? {} : { id }, ...onNavigate === void 0 ? {} : { onClick: onNavigate }, children: shown.map(({ item, href }, index) => /* @__PURE__ */ jsxs9("li", { children: [
1107
+ /* @__PURE__ */ jsx15("a", { href, children: item.label }),
1108
+ depth + 1 < MAX_DEPTH && item.children !== void 0 && /* @__PURE__ */ jsx15(List, { items: item.children, mediaOrigin, depth: depth + 1 })
1109
+ ] }, `${String(index)}:${href}`)) });
1110
+ }
1111
+ function Menu({ props, mediaOrigin, editMode }) {
1112
+ const design = useSiteDesign4();
1113
+ const listId = useId();
1114
+ const toggle = useRef(null);
1115
+ const [open, setOpen] = useState3(false);
1116
+ const name = str(props.menu) ?? "header";
1117
+ const layout = oneOf(props.layout, LAYOUTS, "horizontal");
1118
+ const menus = design?.menus;
1119
+ const items = menus !== void 0 && Object.hasOwn(menus, name) ? menus[name] : void 0;
1120
+ const strings = design?.strings;
1121
+ const label = (strings !== void 0 && Object.hasOwn(strings, "nav.menu") ? str(strings["nav.menu"]) : void 0) ?? SITE_STRING_DEFAULTS3["nav.menu"];
1122
+ if (items === void 0 || items.length === 0) {
1123
+ return /* @__PURE__ */ jsxs9(Fragment9, { children: [
1124
+ /* @__PURE__ */ jsx15(BasicStyles, {}),
1125
+ /* @__PURE__ */ jsx15(Placeholder, { editMode, children: `Menu "${name}" is empty: add links in Site settings` })
1126
+ ] });
1127
+ }
1128
+ const drawer = layout === "drawer-on-phone";
1129
+ const onKeyDown = (event) => {
1130
+ if (event.key === "Escape" && open) {
1131
+ setOpen(false);
1132
+ toggle.current?.focus();
1133
+ }
1134
+ };
1135
+ return /* @__PURE__ */ jsxs9(Fragment9, { children: [
1136
+ /* @__PURE__ */ jsx15(BasicStyles, {}),
1137
+ /* @__PURE__ */ jsxs9(
1138
+ "nav",
1139
+ {
1140
+ className: `tb-b-menu tb-b-menu--${layout}${layout === "vertical" ? "" : " tb-b-menu--h"}`,
1141
+ "aria-label": label,
1142
+ "data-open": drawer ? String(open) : void 0,
1143
+ onKeyDown: drawer ? onKeyDown : void 0,
1144
+ children: [
1145
+ drawer && /* @__PURE__ */ jsx15(
1146
+ "button",
1147
+ {
1148
+ ref: toggle,
1149
+ type: "button",
1150
+ className: "tb-b-menu-toggle",
1151
+ "aria-expanded": open,
1152
+ "aria-controls": listId,
1153
+ onClick: () => setOpen((value) => !value),
1154
+ children: /* @__PURE__ */ jsx15(Icon2, { name: open ? "close" : "menu", size: 24, label })
1155
+ }
1156
+ ),
1157
+ /* @__PURE__ */ jsx15(List, { items, mediaOrigin, id: listId, ...drawer ? { onNavigate: () => setOpen(false) } : {} })
1158
+ ]
1159
+ }
1160
+ )
1161
+ ] });
1162
+ }
1163
+
1164
+ // src/basics/spacer.tsx
1165
+ import { Fragment as Fragment10, jsx as jsx16, jsxs as jsxs10 } from "react/jsx-runtime";
1166
+ function Spacer() {
1167
+ return /* @__PURE__ */ jsxs10(Fragment10, { children: [
1168
+ /* @__PURE__ */ jsx16(BasicStyles, {}),
1169
+ /* @__PURE__ */ jsx16("div", { className: "tb-b-spacer", "aria-hidden": "true" })
1170
+ ] });
1171
+ }
1172
+
1173
+ // src/basics/rich-text.tsx
1174
+ import { Fragment as Fragment11, createElement } from "react";
1175
+ import { safeUrl as safeUrl10 } from "@usethrottle/builder-schema";
1176
+ import { jsx as jsx17, jsxs as jsxs11 } from "react/jsx-runtime";
1177
+ var ALLOWED = /* @__PURE__ */ new Set(["p", "br", "strong", "em", "u", "s", "a", "ul", "ol", "li", "h2", "h3", "h4", "blockquote", "code"]);
1178
+ var ALIAS = { b: "strong", i: "em", strike: "s", del: "s" };
1179
+ var DROP_WITH_CONTENT = /* @__PURE__ */ new Set([
1180
+ "script",
1181
+ "style",
1182
+ "iframe",
1183
+ "object",
1184
+ "embed",
1185
+ "noscript",
1186
+ "template",
1187
+ "textarea",
1188
+ "title",
1189
+ "head",
1190
+ "xml",
1191
+ "svg",
1192
+ "math",
1193
+ "noembed",
1194
+ "noframes",
1195
+ "xmp"
1196
+ ]);
1197
+ var VOID = /* @__PURE__ */ new Set(["br"]);
1198
+ var BLOCK = /* @__PURE__ */ new Set(["p", "h2", "h3", "h4", "ul", "ol", "blockquote"]);
1199
+ var TEXT_BLOCK = /* @__PURE__ */ new Set(["p", "h2", "h3", "h4"]);
1200
+ var MAX_LENGTH = 2e4;
1201
+ var MAX_DEPTH2 = 24;
1202
+ var MAX_NODES = 4e3;
1203
+ var NAMED = {
1204
+ amp: "&",
1205
+ lt: "<",
1206
+ gt: ">",
1207
+ quot: '"',
1208
+ apos: "'",
1209
+ nbsp: "\xA0",
1210
+ copy: "\xA9",
1211
+ reg: "\xAE",
1212
+ trade: "\u2122",
1213
+ mdash: "\u2014",
1214
+ ndash: "\u2013",
1215
+ hellip: "\u2026",
1216
+ lsquo: "\u2018",
1217
+ rsquo: "\u2019",
1218
+ ldquo: "\u201C",
1219
+ rdquo: "\u201D",
1220
+ euro: "\u20AC",
1221
+ pound: "\xA3"
1222
+ };
1223
+ function decode(value) {
1224
+ return value.replace(/&(?:#x([0-9a-f]{1,6})|#(\d{1,7})|([a-z]{2,8}));/gi, (whole, hex, dec, name) => {
1225
+ if (name !== void 0) return Object.hasOwn(NAMED, name.toLowerCase()) ? NAMED[name.toLowerCase()] : whole;
1226
+ const code = hex !== void 0 ? Number.parseInt(hex, 16) : Number.parseInt(dec ?? "", 10);
1227
+ return code > 0 && code <= 1114111 && !(code >= 55296 && code <= 57343) ? String.fromCodePoint(code) : "";
1228
+ });
1229
+ }
1230
+ var TAG_NAME = /[a-z][a-z0-9:_-]*/iy;
1231
+ function readTag(html, start) {
1232
+ const attrs = /* @__PURE__ */ new Map();
1233
+ let i = start;
1234
+ for (; ; ) {
1235
+ while (i < html.length && /[\s/]/.test(html[i])) i += 1;
1236
+ if (i >= html.length) return null;
1237
+ if (html[i] === ">") return { attrs, end: i + 1, selfClosing: /\/\s*$/.test(html.slice(start, i)) };
1238
+ let name = "";
1239
+ while (i < html.length && !/[\s=/>]/.test(html[i])) name += html[i++];
1240
+ while (i < html.length && /\s/.test(html[i])) i += 1;
1241
+ let value = "";
1242
+ if (html[i] === "=") {
1243
+ i += 1;
1244
+ while (i < html.length && /\s/.test(html[i])) i += 1;
1245
+ const quote = html[i];
1246
+ if (quote === '"' || quote === "'") {
1247
+ const close = html.indexOf(quote, i + 1);
1248
+ if (close === -1) return null;
1249
+ value = html.slice(i + 1, close);
1250
+ i = close + 1;
1251
+ } else {
1252
+ while (i < html.length && !/[\s>]/.test(html[i])) value += html[i++];
1253
+ }
1254
+ }
1255
+ const key = name.toLowerCase();
1256
+ if (key !== "" && !attrs.has(key)) attrs.set(key, value);
1257
+ }
1258
+ }
1259
+ function parseRichText(source, mediaOrigin) {
1260
+ const html = source.slice(0, MAX_LENGTH);
1261
+ const root = { tag: "#root", children: [], ...source.length > MAX_LENGTH ? { truncated: true } : {} };
1262
+ const stack = [root];
1263
+ const top = () => stack[stack.length - 1];
1264
+ let nodes = 0;
1265
+ const text = (value) => {
1266
+ if (value === "" || nodes > MAX_NODES) return;
1267
+ nodes += 1;
1268
+ const parent = top();
1269
+ const last = parent.children[parent.children.length - 1];
1270
+ if (typeof last === "string") parent.children[parent.children.length - 1] = last + value;
1271
+ else parent.children.push(value);
1272
+ };
1273
+ const closeTo = (tag) => {
1274
+ const at = stack.map((e) => e.tag).lastIndexOf(tag);
1275
+ if (at > 0) stack.length = at;
1276
+ };
1277
+ let i = 0;
1278
+ while (i < html.length && nodes <= MAX_NODES) {
1279
+ const lt = html.indexOf("<", i);
1280
+ if (lt === -1) {
1281
+ text(decode(html.slice(i)));
1282
+ break;
1283
+ }
1284
+ text(decode(html.slice(i, lt)));
1285
+ i = lt;
1286
+ if (html.startsWith("<!--", i)) {
1287
+ const close = html.indexOf("-->", i + 4);
1288
+ i = close === -1 ? html.length : close + 3;
1289
+ continue;
1290
+ }
1291
+ const closing = html[i + 1] === "/";
1292
+ const nameStart = i + (closing ? 2 : 1);
1293
+ TAG_NAME.lastIndex = nameStart;
1294
+ const raw = TAG_NAME.exec(html)?.[0]?.toLowerCase();
1295
+ if (raw === void 0) {
1296
+ if (html[i + 1] === "!" || html[i + 1] === "?") {
1297
+ const close = html.indexOf(">", i);
1298
+ i = close === -1 ? html.length : close + 1;
1299
+ } else {
1300
+ text("<");
1301
+ i += 1;
1302
+ }
1303
+ continue;
1304
+ }
1305
+ const tag = readTag(html, nameStart + raw.length);
1306
+ if (tag === null) {
1307
+ root.truncated = true;
1308
+ break;
1309
+ }
1310
+ i = tag.end;
1311
+ const name = Object.hasOwn(ALIAS, raw) ? ALIAS[raw] : raw;
1312
+ if (closing) {
1313
+ if (ALLOWED.has(name)) closeTo(name);
1314
+ continue;
1315
+ }
1316
+ if (DROP_WITH_CONTENT.has(raw)) {
1317
+ if (!tag.selfClosing) {
1318
+ const close = new RegExp(`</${raw}\\s*>`, "ig");
1319
+ close.lastIndex = i;
1320
+ const found = close.exec(html);
1321
+ i = found === null ? html.length : found.index + found[0].length;
1322
+ }
1323
+ continue;
1324
+ }
1325
+ if (!ALLOWED.has(name)) continue;
1326
+ if (BLOCK.has(name)) {
1327
+ for (let at = stack.length - 1; at > 0; at -= 1) {
1328
+ if (TEXT_BLOCK.has(stack[at].tag)) {
1329
+ stack.length = at;
1330
+ break;
1331
+ }
1332
+ }
1333
+ }
1334
+ if (name === "li") {
1335
+ let list = stack.length - 1;
1336
+ while (list > 0 && stack[list].tag !== "ul" && stack[list].tag !== "ol") list -= 1;
1337
+ if (list === 0) list = -1;
1338
+ if (list === -1) continue;
1339
+ stack.length = list + 1;
1340
+ }
1341
+ if (name === "a") closeTo("a");
1342
+ const el = { tag: name, children: [] };
1343
+ if (name === "a") {
1344
+ const href = tag.attrs.get("href");
1345
+ el.href = href === void 0 ? null : safeUrl10(decode(href).trim(), "href", { mediaOrigin });
1346
+ }
1347
+ nodes += 1;
1348
+ top().children.push(el);
1349
+ if (!VOID.has(name) && stack.length < MAX_DEPTH2) stack.push(el);
1350
+ }
1351
+ if (nodes > MAX_NODES) root.truncated = true;
1352
+ return root;
1353
+ }
1354
+ function toReact(el, key) {
1355
+ const children = el.children.map((child, index) => typeof child === "string" ? child : toReact(child, index));
1356
+ if (el.tag === "br") return /* @__PURE__ */ jsx17("br", {}, key);
1357
+ if (el.tag === "a") {
1358
+ if (el.href === null || el.href === void 0) return /* @__PURE__ */ jsx17(Fragment11, { children }, key);
1359
+ return /* @__PURE__ */ jsx17("a", { href: el.href, rel: "noopener noreferrer", className: "tb-b-link", children }, key);
1360
+ }
1361
+ return createElement(el.tag, { key }, ...children);
1362
+ }
1363
+ function RichText({
1364
+ html,
1365
+ mediaOrigin,
1366
+ className,
1367
+ editMode = false
1368
+ }) {
1369
+ const tree = parseRichText(html, mediaOrigin);
1370
+ return /* @__PURE__ */ jsxs11("div", { className, children: [
1371
+ tree.children.map((child, index) => typeof child === "string" ? child : toReact(child, index)),
1372
+ editMode && tree.truncated === true && /* @__PURE__ */ jsx17("div", { className: "tb-b-empty", role: "alert", children: "Part of this text was not shown: a tag is not closed (check the quotes in links), or the text is too long." })
1373
+ ] });
1374
+ }
1375
+
1376
+ // src/basics/text.tsx
1377
+ import { Fragment as Fragment12, jsx as jsx18, jsxs as jsxs12 } from "react/jsx-runtime";
1378
+ function Text({ props, mediaOrigin, editMode, inlineEdit }) {
1379
+ const editor = inlineEdit?.("html") ?? null;
1380
+ return /* @__PURE__ */ jsxs12(Fragment12, { children: [
1381
+ /* @__PURE__ */ jsx18(BasicStyles, {}),
1382
+ editor === null ? /* @__PURE__ */ jsx18(RichText, { html: str(props.html) ?? "", mediaOrigin, className: "tb-b-text", editMode }) : /* @__PURE__ */ jsx18("div", { className: "tb-b-text", children: editor })
1383
+ ] });
1384
+ }
1385
+
1386
+ // src/basics/video.tsx
1387
+ import { useState as useState4 } from "react";
1388
+ import { Icon as Icon3 } from "@usethrottle/ui";
1389
+ import { Fragment as Fragment13, jsx as jsx19, jsxs as jsxs13 } from "react/jsx-runtime";
1390
+ var RULES3 = [
1391
+ { key: "ratio", property: "--bx-ratio", values: { "16:9": "16 / 9", "4:3": "4 / 3", "1:1": "1 / 1", "9:16": "9 / 16" } }
1392
+ ];
1393
+ var YOUTUBE_ID = /^[A-Za-z0-9_-]{11}$/;
1394
+ var VIMEO_ID = /^\d{5,12}$/;
1395
+ var YOUTUBE_HOSTS = /* @__PURE__ */ new Set(["youtube.com", "www.youtube.com", "m.youtube.com", "youtube-nocookie.com", "www.youtube-nocookie.com"]);
1396
+ var VIMEO_HOSTS = /* @__PURE__ */ new Set(["vimeo.com", "www.vimeo.com", "player.vimeo.com"]);
1397
+ function parseVideoUrl(input) {
1398
+ let url;
1399
+ try {
1400
+ url = new URL(input.trim());
1401
+ } catch {
1402
+ return null;
1403
+ }
1404
+ if (url.protocol !== "https:" || url.username !== "" || url.password !== "" || url.port !== "" && url.port !== "443") return null;
1405
+ const host = url.hostname.toLowerCase();
1406
+ const parts = url.pathname.split("/").filter((part) => part !== "");
1407
+ if (host === "youtu.be") {
1408
+ const id = parts[0];
1409
+ return parts.length === 1 && id !== void 0 && YOUTUBE_ID.test(id) ? { provider: "youtube", id } : null;
1410
+ }
1411
+ if (YOUTUBE_HOSTS.has(host)) {
1412
+ if (parts[0] === "watch" && parts.length === 1) {
1413
+ const id2 = url.searchParams.get("v");
1414
+ return id2 !== null && YOUTUBE_ID.test(id2) ? { provider: "youtube", id: id2 } : null;
1415
+ }
1416
+ const id = parts[1];
1417
+ return (parts[0] === "embed" || parts[0] === "shorts" || parts[0] === "live") && parts.length === 2 && id !== void 0 && YOUTUBE_ID.test(id) ? { provider: "youtube", id } : null;
1418
+ }
1419
+ if (VIMEO_HOSTS.has(host)) {
1420
+ const id = host === "player.vimeo.com" ? parts[0] === "video" && parts.length === 2 ? parts[1] : void 0 : parts.length === 1 ? parts[0] : void 0;
1421
+ return id !== void 0 && VIMEO_ID.test(id) ? { provider: "vimeo", id } : null;
1422
+ }
1423
+ return null;
1424
+ }
1425
+ function embedSrc(video, muted) {
1426
+ return video.provider === "youtube" ? `https://www.youtube-nocookie.com/embed/${video.id}?autoplay=1&rel=0&playsinline=1${muted ? "&mute=1" : ""}` : `https://player.vimeo.com/video/${video.id}?autoplay=1&dnt=1${muted ? "&muted=1" : ""}`;
1427
+ }
1428
+ function Video({ node, props, editMode }) {
1429
+ const [loaded, setLoaded] = useState4(false);
1430
+ const video = parseVideoUrl(str(props.url) ?? "");
1431
+ return /* @__PURE__ */ jsxs13(Fragment13, { children: [
1432
+ /* @__PURE__ */ jsx19(BasicStyles, {}),
1433
+ /* @__PURE__ */ jsx19(WidgetStyle, { css: enumCss(node, RULES3) }),
1434
+ video === null ? /* @__PURE__ */ jsx19(Placeholder, { editMode, children: "Paste a YouTube or Vimeo link" }) : /* @__PURE__ */ jsx19("div", { className: "tb-b-video", "data-provider": video.provider, children: loaded && !editMode ? /* @__PURE__ */ jsx19(
1435
+ "iframe",
1436
+ {
1437
+ src: embedSrc(video, props.autoplayMuted === true),
1438
+ title: "Video",
1439
+ allow: "autoplay; encrypted-media; picture-in-picture; fullscreen",
1440
+ referrerPolicy: "strict-origin-when-cross-origin",
1441
+ sandbox: "allow-scripts allow-same-origin allow-presentation allow-popups"
1442
+ }
1443
+ ) : /* @__PURE__ */ jsx19("button", { type: "button", className: "tb-b-play", "aria-label": "Play video", onClick: () => setLoaded(true), children: /* @__PURE__ */ jsx19("span", { children: /* @__PURE__ */ jsx19(Icon3, { name: "play", size: 28 }) }) }) })
1444
+ ] });
1445
+ }
1446
+
1447
+ // src/basics/index.ts
1448
+ var BASIC_COMPONENTS = {
1449
+ "basic.heading": Heading,
1450
+ "basic.text": Text,
1451
+ "basic.image": Image,
1452
+ "basic.button": Button,
1453
+ "basic.spacer": Spacer,
1454
+ "basic.divider": Divider,
1455
+ "basic.video": Video,
1456
+ "basic.logo": Logo,
1457
+ "basic.menu": Menu,
1458
+ "basic.announcement": Announcement,
1459
+ "basic.copyright": Copyright
1460
+ };
1461
+ var widgets = BASIC_WIDGET_DEFINITIONS2.flatMap(
1462
+ (definition) => Object.hasOwn(BASIC_COMPONENTS, definition.type) ? [{ ...definition, Component: BASIC_COMPONENTS[definition.type] }] : []
1463
+ );
1464
+ var basicPack = { id: "basic", version: "0.0.0", widgets, dataSources: [] };
1465
+
1466
+ // src/custom/factory.ts
1467
+ import { createElement as createElement3 } from "react";
1468
+
1469
+ // src/custom/composite-widget.tsx
1470
+ import { Suspense as Suspense2 } from "react";
1471
+ import { pageDocumentSchema, validateSettingValue } from "@usethrottle/builder-schema";
1472
+
1473
+ // src/custom/template-widget.tsx
1474
+ import { Suspense } from "react";
1475
+ import { MAX_TEMPLATE_WEIGHT as MAX_TEMPLATE_WEIGHT2, parseTemplate, templateWeight as templateWeight2, validateTemplate } from "@usethrottle/builder-schema";
1476
+
1477
+ // src/custom/custom-css.tsx
1478
+ import { sanitizeWidgetCss } from "@usethrottle/builder-schema";
1479
+ import { jsx as jsx20 } from "react/jsx-runtime";
1480
+ function scopedCss(source, type) {
1481
+ if (source === void 0 || source === "") return "";
1482
+ if (typeof source !== "string") return null;
1483
+ const result = sanitizeWidgetCss(source, type);
1484
+ return result.ok ? result.css : null;
1485
+ }
1486
+ function CustomCss({ css }) {
1487
+ return /* @__PURE__ */ jsx20(WidgetStyle, { css });
1488
+ }
1489
+
1490
+ // src/custom/interpreter.tsx
1491
+ import { Fragment as Fragment14, createElement as createElement2 } from "react";
1492
+ import {
1493
+ ALLOWED_ATTRS,
1494
+ ALLOWED_ELEMENTS,
1495
+ ALLOWED_ROLES,
1496
+ CLASS_TOKEN_RE,
1497
+ DATA_ATTR_RE,
1498
+ EACH_ITERATION_CAP,
1499
+ RESERVED_DATA_PREFIX,
1500
+ VOID_ELEMENTS,
1501
+ isReservedClass,
1502
+ safeUrl as safeUrl11
1503
+ } from "@usethrottle/builder-schema";
1504
+ import { jsx as jsx21 } from "react/jsx-runtime";
1505
+ var MAX_OUTPUT_CHARS = 1e6;
1506
+ var MAX_ATTR_CHARS = 2e3;
1507
+ var MAX_DEPTH3 = 24;
1508
+ function newEnv(env) {
1509
+ return { ...env, charsLeft: MAX_OUTPUT_CHARS, stopped: false };
1510
+ }
1511
+ var BLOCKED = /* @__PURE__ */ new Set([
1512
+ "__proto__",
1513
+ "constructor",
1514
+ "prototype",
1515
+ ...Object.getOwnPropertyNames(Object.prototype)
1516
+ ]);
1517
+ var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1518
+ function step(value, key) {
1519
+ if (BLOCKED.has(key) || !isPlainObject(value) || !Object.hasOwn(value, key)) return void 0;
1520
+ return value[key];
1521
+ }
1522
+ function lookup(path, env, scope) {
1523
+ const [root, ...rest] = path;
1524
+ if (root === void 0) return void 0;
1525
+ if (root === "locale") return rest.length === 0 ? env.locale : void 0;
1526
+ let value;
1527
+ if (root === "settings") value = rest.length === 0 ? void 0 : env.settings;
1528
+ else if (root === "data") value = rest.length === 0 ? void 0 : env.data;
1529
+ else if (scope.has(root)) value = scope.get(root);
1530
+ else return void 0;
1531
+ for (const key of rest) {
1532
+ value = step(value, key);
1533
+ if (value === void 0) return void 0;
1534
+ }
1535
+ return value;
1536
+ }
1537
+ function truthy(value) {
1538
+ if (value === null || value === void 0 || value === false || value === "") return false;
1539
+ if (typeof value === "number") return value !== 0 && !Number.isNaN(value);
1540
+ if (Array.isArray(value)) return value.length > 0;
1541
+ return true;
1542
+ }
1543
+ function asText(value) {
1544
+ if (typeof value === "string") return value;
1545
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
1546
+ return "";
1547
+ }
1548
+ function filtered(value, filters) {
1549
+ let text = asText(value);
1550
+ for (const filter of filters) {
1551
+ switch (filter.name) {
1552
+ case "upper":
1553
+ text = text.toUpperCase();
1554
+ break;
1555
+ case "lower":
1556
+ text = text.toLowerCase();
1557
+ break;
1558
+ case "truncate": {
1559
+ const chars = Array.from(text);
1560
+ if (chars.length > filter.n) text = `${chars.slice(0, filter.n).join("")}\u2026`;
1561
+ break;
1562
+ }
1563
+ case "default":
1564
+ if (text === "") text = filter.text;
1565
+ break;
1566
+ }
1567
+ }
1568
+ return text;
1569
+ }
1570
+ function spend(env, count) {
1571
+ if (count > env.charsLeft) {
1572
+ env.stopped = true;
1573
+ return false;
1574
+ }
1575
+ env.charsLeft -= count;
1576
+ return true;
1577
+ }
1578
+ var ELEMENTS = new Set(ALLOWED_ELEMENTS);
1579
+ var VOIDS = new Set(VOID_ELEMENTS);
1580
+ var ROLES = new Set(ALLOWED_ROLES);
1581
+ function attrAllowed(tag, name) {
1582
+ if (DATA_ATTR_RE.test(name)) return !name.startsWith(RESERVED_DATA_PREFIX);
1583
+ const own = Object.hasOwn(ALLOWED_ATTRS, tag) ? ALLOWED_ATTRS[tag] : void 0;
1584
+ return (ALLOWED_ATTRS["*"]?.includes(name) ?? false) || (own?.includes(name) ?? false);
1585
+ }
1586
+ function attrText(attr, env, scope) {
1587
+ return attr.value.map((part) => part.type === "text" ? part.value : filtered(lookup(part.path, env, scope), part.filters)).join("");
1588
+ }
1589
+ function urlSource(attr, env, scope) {
1590
+ const [only] = attr.value;
1591
+ if (attr.value.length !== 1 || only === void 0 || only.type !== "output") return attrText(attr, env, scope);
1592
+ const value = lookup(only.path, env, scope);
1593
+ if (isPlainObject(value)) {
1594
+ if (typeof value.href === "string") return value.href;
1595
+ if (typeof value.url === "string") return value.url;
1596
+ return null;
1597
+ }
1598
+ return value;
1599
+ }
1600
+ function attrProp(tag, attr, env, scope) {
1601
+ const { name } = attr;
1602
+ if (!attrAllowed(tag, name)) return null;
1603
+ if (name === "href" || name === "src") {
1604
+ const safe = safeUrl11(urlSource(attr, env, scope), name, { mediaOrigin: env.mediaOrigin });
1605
+ return safe === null || !spend(env, safe.length) ? null : [name, safe];
1606
+ }
1607
+ const text = attrText(attr, env, scope);
1608
+ if (text === "" || text.length > MAX_ATTR_CHARS) return null;
1609
+ let value = text;
1610
+ if (name === "class") {
1611
+ const tokens = text.split(/\s+/).filter((token) => CLASS_TOKEN_RE.test(token) && !isReservedClass(token));
1612
+ if (tokens.length === 0) return null;
1613
+ value = tokens.join(" ");
1614
+ } else if (name === "role") {
1615
+ if (!ROLES.has(text)) return null;
1616
+ } else if (name === "aria-hidden") {
1617
+ if (text !== "true" && text !== "false") return null;
1618
+ }
1619
+ if (!spend(env, value.length)) return null;
1620
+ return [name === "class" ? "className" : name, value];
1621
+ }
1622
+ function renderElement(node, env, scope, depth, key) {
1623
+ const tag = node.tag;
1624
+ if (!ELEMENTS.has(tag)) return null;
1625
+ const props = { key };
1626
+ for (const attr of node.attrs) {
1627
+ const prop = attrProp(tag, attr, env, scope);
1628
+ if (prop !== null) props[prop[0]] = prop[1];
1629
+ }
1630
+ if (VOIDS.has(tag)) return createElement2(tag, props);
1631
+ return createElement2(tag, props, renderNodes(node.children, env, scope, depth + 1));
1632
+ }
1633
+ function renderNodes(nodes, env, scope, depth) {
1634
+ const out = [];
1635
+ if (depth > MAX_DEPTH3) return out;
1636
+ for (const node of nodes) {
1637
+ if (env.stopped) break;
1638
+ if (!env.budget.take(1) || node.type === "element" && !env.budget.take(node.attrs.reduce((n, a) => n + a.value.length, 0))) {
1639
+ env.stopped = true;
1640
+ break;
1641
+ }
1642
+ switch (node.type) {
1643
+ case "text":
1644
+ if (spend(env, node.value.length)) out.push(node.value);
1645
+ break;
1646
+ case "output": {
1647
+ const text = filtered(lookup(node.path, env, scope), node.filters);
1648
+ if (text !== "" && spend(env, text.length)) out.push(text);
1649
+ break;
1650
+ }
1651
+ case "if": {
1652
+ const branch = truthy(lookup(node.path, env, scope)) ? node.then : node.else;
1653
+ out.push(/* @__PURE__ */ jsx21(Fragment14, { children: renderNodes(branch, env, scope, depth + 1) }, out.length));
1654
+ break;
1655
+ }
1656
+ case "unless":
1657
+ if (!truthy(lookup(node.path, env, scope))) {
1658
+ out.push(/* @__PURE__ */ jsx21(Fragment14, { children: renderNodes(node.body, env, scope, depth + 1) }, out.length));
1659
+ }
1660
+ break;
1661
+ case "each": {
1662
+ const list = lookup(node.path, env, scope);
1663
+ if (!Array.isArray(list)) break;
1664
+ const count = Math.min(list.length, EACH_ITERATION_CAP);
1665
+ for (let i = 0; i < count && !env.stopped; i += 1) {
1666
+ const inner = new Map(scope).set(node.as, list[i]);
1667
+ out.push(/* @__PURE__ */ jsx21(Fragment14, { children: renderNodes(node.body, env, inner, depth + 1) }, out.length));
1668
+ }
1669
+ break;
1670
+ }
1671
+ case "element":
1672
+ out.push(renderElement(node, env, scope, depth, out.length));
1673
+ break;
1674
+ }
1675
+ }
1676
+ return out;
1677
+ }
1678
+ function renderTemplate(ast, env) {
1679
+ return renderNodes(ast, env, /* @__PURE__ */ new Map(), 0);
1680
+ }
1681
+
1682
+ // src/custom/template-widget.tsx
1683
+ import { Fragment as Fragment15, jsx as jsx22, jsxs as jsxs14 } from "react/jsx-runtime";
1684
+ var componentWeights = /* @__PURE__ */ new WeakMap();
1685
+ var compiled = /* @__PURE__ */ new WeakMap();
1686
+ function compileTemplate(snapshot, registry) {
1687
+ let perRegistry = compiled.get(snapshot);
1688
+ if (perRegistry === void 0) {
1689
+ perRegistry = /* @__PURE__ */ new WeakMap();
1690
+ compiled.set(snapshot, perRegistry);
1691
+ }
1692
+ if (perRegistry.has(registry)) return perRegistry.get(registry) ?? null;
1693
+ const result = compile(snapshot, registry);
1694
+ perRegistry.set(registry, result);
1695
+ return result;
1696
+ }
1697
+ function compile(snapshot, registry) {
1698
+ const label = `${snapshot.type}@${String(snapshot.v)}`;
1699
+ const refuse = (why) => {
1700
+ warnOnce(`template:${label}`, `${label} was refused (${why}); rendering nothing for it`);
1701
+ return null;
1702
+ };
1703
+ if (snapshot.kind !== "template") return refuse("not a template widget");
1704
+ const source = snapshot.template;
1705
+ if (typeof source !== "string") return refuse("no template source");
1706
+ const parsed = parseTemplate(source);
1707
+ if (!parsed.ok) return refuse(`template does not parse: ${parsed.issues[0]?.message ?? "invalid"}`);
1708
+ const data = snapshot.data;
1709
+ const issues = validateTemplate(parsed.ast, {
1710
+ settings: snapshot.settings,
1711
+ data: typeof data === "object" && data !== null ? data : {},
1712
+ sources: registry.sources()
1713
+ });
1714
+ if (issues.length > 0) return refuse(`template does not validate: ${issues[0]?.message ?? "invalid"}`);
1715
+ if (!fitsBudget(parsed.ast)) return refuse(`it can render more than ${String(MAX_TEMPLATE_WEIGHT2)} nodes`);
1716
+ const css = scopedCss(snapshot.css, snapshot.type);
1717
+ if (css === null) return refuse("its css does not pass the sanitiser");
1718
+ return { ast: parsed.ast, css, weight: templateWeight2(parsed.ast) };
1719
+ }
1720
+ function TemplateBody({ snapshot, registry, props, data, locale, mediaOrigin, budget }) {
1721
+ const template = compileTemplate(snapshot, registry);
1722
+ if (template === null) return null;
1723
+ const env = newEnv({ settings: props, data, locale, mediaOrigin, budget: budget ?? new RenderBudget() });
1724
+ return /* @__PURE__ */ jsxs14(Fragment15, { children: [
1725
+ template.css === "" ? null : /* @__PURE__ */ jsx22(CustomCss, { css: template.css }),
1726
+ renderTemplate(template.ast, env)
1727
+ ] });
1728
+ }
1729
+ function TemplateWidget(props) {
1730
+ return /* @__PURE__ */ jsx22(PartBoundary, { label: `${props.snapshot.type}@${String(props.snapshot.v)}`, children: /* @__PURE__ */ jsx22(Suspense, { fallback: null, children: /* @__PURE__ */ jsx22(TemplateBody, { ...props }) }) });
1731
+ }
1732
+
1733
+ // src/custom/composite-widget.tsx
1734
+ import { jsx as jsx23 } from "react/jsx-runtime";
1735
+ var SETTING_KEY_RE = /^[a-z][A-Za-z0-9]{0,39}$/;
1736
+ var NODE_ID_RE = /^[a-z0-9]{8,24}$/;
1737
+ var WRAP = { section: "zzcompsec001", column: "zzcompcol001", inner: "zzcompinr001" };
1738
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1739
+ var compiled2 = /* @__PURE__ */ new WeakMap();
1740
+ function parseBody(raw) {
1741
+ if (!isRecord3(raw)) return null;
1742
+ const columns = Array.isArray(raw.columns) ? raw.columns : void 0;
1743
+ const stack = Array.isArray(raw.stack) ? raw.stack : void 0;
1744
+ if (columns === void 0 === (stack === void 0)) return null;
1745
+ const children = columns !== void 0 ? [{ id: WRAP.inner, type: "inner-section", props: {}, columns }] : stack ?? [];
1746
+ if (stack?.some((node) => isRecord3(node) && node.type === "inner-section")) return null;
1747
+ const parsed = pageDocumentSchema.safeParse({
1748
+ schemaVersion: 1,
1749
+ sections: [{ id: WRAP.section, type: "section", props: {}, columns: [{ id: WRAP.column, type: "column", props: { width: 100 }, children }] }]
1750
+ });
1751
+ if (!parsed.success) return null;
1752
+ const first = parsed.data.sections[0]?.columns[0]?.children ?? [];
1753
+ if (columns !== void 0) {
1754
+ const inner = first[0];
1755
+ return inner?.type === "inner-section" ? { columns: inner.columns } : null;
1756
+ }
1757
+ return { stack: first.filter((node) => node.type !== "inner-section") };
1758
+ }
1759
+ function compileComposite(snapshot) {
1760
+ if (compiled2.has(snapshot)) return compiled2.get(snapshot) ?? null;
1761
+ const result = compile2(snapshot);
1762
+ compiled2.set(snapshot, result);
1763
+ return result;
1764
+ }
1765
+ function compile2(snapshot) {
1766
+ const label = `${snapshot.type}@${String(snapshot.v)}`;
1767
+ const refuse = (why) => {
1768
+ warnOnce(`composite:${label}`, `${label} was refused (${why}); rendering nothing for it`);
1769
+ return null;
1770
+ };
1771
+ if (snapshot.kind !== "composite") return refuse("not a composite widget");
1772
+ const extra = snapshot;
1773
+ const body = parseBody(extra.body);
1774
+ if (body === null) return refuse("its body does not pass the document grammar");
1775
+ const bindings = [];
1776
+ if (extra.bindings !== void 0 && !Array.isArray(extra.bindings)) return refuse("bindings is not a list");
1777
+ for (const raw of extra.bindings ?? []) {
1778
+ if (!isRecord3(raw) || typeof raw.setting !== "string" || !SETTING_KEY_RE.test(raw.setting) || !Array.isArray(raw.targets)) {
1779
+ return refuse("a binding is malformed");
1780
+ }
1781
+ const targets = [];
1782
+ for (const target of raw.targets) {
1783
+ if (!isRecord3(target) || typeof target.node !== "string" || !NODE_ID_RE.test(target.node) || typeof target.prop !== "string" || !SETTING_KEY_RE.test(target.prop)) {
1784
+ return refuse("a binding target is malformed");
1785
+ }
1786
+ targets.push({ node: target.node, prop: target.prop });
1787
+ }
1788
+ bindings.push({ setting: raw.setting, targets });
1789
+ }
1790
+ const data = [];
1791
+ if (extra.data !== void 0 && !isRecord3(extra.data)) return refuse("data is not a record");
1792
+ for (const [name, raw] of Object.entries(extra.data ?? {})) {
1793
+ if (!SETTING_KEY_RE.test(name) || !isRecord3(raw) || !Array.isArray(raw.targets)) return refuse("a data input is malformed");
1794
+ const targets = [];
1795
+ for (const target of raw.targets) {
1796
+ if (!isRecord3(target) || typeof target.node !== "string" || !NODE_ID_RE.test(target.node) || typeof target.input !== "string" || !SETTING_KEY_RE.test(target.input)) {
1797
+ return refuse("a data target is malformed");
1798
+ }
1799
+ targets.push({ node: target.node, input: target.input });
1800
+ }
1801
+ data.push([name, { targets }]);
1802
+ }
1803
+ return { body, bindings, data };
1804
+ }
1805
+ var DEVICES3 = ["tablet", "phone"];
1806
+ function withoutAnchor(node) {
1807
+ delete node.props.anchor;
1808
+ const responsive = node.responsive;
1809
+ for (const device of DEVICES3) if (responsive?.[device] !== void 0) delete responsive[device].anchor;
1810
+ }
1811
+ function instanceId(outer, inner) {
1812
+ let a = 3735928559;
1813
+ let b = 1103547991;
1814
+ for (const char of `${outer}:${inner}`) {
1815
+ const code = char.charCodeAt(0);
1816
+ a = Math.imul(a ^ code, 2654435761);
1817
+ b = Math.imul(b ^ code, 1597334677);
1818
+ }
1819
+ a = Math.imul(a ^ a >>> 16, 2246822507) ^ Math.imul(b ^ b >>> 13, 3266489909);
1820
+ b = Math.imul(b ^ b >>> 16, 2246822507) ^ Math.imul(a ^ a >>> 13, 3266489909);
1821
+ return `i${(a >>> 0).toString(36).padStart(7, "0")}${(b >>> 0).toString(36).padStart(7, "0")}${(outer.length + inner.length).toString(36)}`;
1822
+ }
1823
+ function build(input) {
1824
+ const { snapshot, registry, node: outer, props, data } = input;
1825
+ const body = structuredClone(input.compiled.body);
1826
+ const assets = {};
1827
+ const hrefs = /* @__PURE__ */ new Map();
1828
+ const innerData = {};
1829
+ const keep = (child) => registry.widget(child.type, child.v)?.kind !== "composite";
1830
+ const columns = body.columns?.map((column2) => ({ ...column2, children: column2.children.filter(keep) }));
1831
+ const stack = body.stack?.filter(keep);
1832
+ const widgets2 = columns !== void 0 ? columns.flatMap((column2) => column2.children) : stack ?? [];
1833
+ for (const widget of widgets2) {
1834
+ withoutAnchor(widget);
1835
+ delete widget.data;
1836
+ }
1837
+ for (const column2 of columns ?? []) withoutAnchor(column2);
1838
+ const byId = new Map(widgets2.map((widget) => [widget.id, widget]));
1839
+ const fields = new Map(snapshot.settings.map((field) => [field.key, field]));
1840
+ let assetCount = 0;
1841
+ const convert = (field, value) => {
1842
+ if (value === null) return null;
1843
+ if (field.translatable === true) return typeof value === "string" ? { en: value } : null;
1844
+ if (field.control === "image") {
1845
+ if (!isFrozenAsset(value)) return null;
1846
+ assetCount += 1;
1847
+ const id = `bound${String(assetCount)}`;
1848
+ assets[id] = value;
1849
+ return id;
1850
+ }
1851
+ if (field.control === "link") {
1852
+ if (!isRecord3(value) || typeof value.kind !== "string") return null;
1853
+ const { href, ...target } = value;
1854
+ if (target.kind === "url") return typeof href === "string" ? { kind: "url", href } : null;
1855
+ hrefs.set(JSON.stringify(target), typeof href === "string" ? href : null);
1856
+ return target;
1857
+ }
1858
+ return value;
1859
+ };
1860
+ for (const binding of input.compiled.bindings) {
1861
+ const field = fields.get(binding.setting);
1862
+ if (field === void 0 || !Object.hasOwn(props, binding.setting)) continue;
1863
+ const value = props[binding.setting];
1864
+ for (const target of binding.targets) {
1865
+ const inner = byId.get(target.node);
1866
+ const innerField = inner === void 0 ? void 0 : registry.widget(inner.type, inner.v)?.settings.find((f) => f.key === target.prop);
1867
+ if (inner === void 0 || innerField === void 0 || innerField.control !== field.control) continue;
1868
+ const converted = convert(field, value);
1869
+ if (validateSettingValue(innerField, converted) !== null) continue;
1870
+ inner.props[target.prop] = converted;
1871
+ const responsive = inner.responsive;
1872
+ for (const device of DEVICES3) {
1873
+ if (responsive?.[device] !== void 0) delete responsive[device][target.prop];
1874
+ const raw = outer.responsive?.[device];
1875
+ const plain = field.output === "css" && field.translatable !== true && field.control !== "image" && field.control !== "link";
1876
+ if (plain && raw !== void 0 && Object.hasOwn(raw, binding.setting) && validateSettingValue(innerField, raw[binding.setting]) === null) {
1877
+ const target$ = inner.responsive ?? (inner.responsive = {});
1878
+ (target$[device] ?? (target$[device] = {}))[target.prop] = raw[binding.setting];
1879
+ }
1880
+ }
1881
+ }
1882
+ }
1883
+ for (const [name, input$] of input.compiled.data) {
1884
+ if (!Object.hasOwn(data, name) || data[name] === void 0) continue;
1885
+ const key = `composite.${name}`;
1886
+ for (const target of input$.targets) {
1887
+ const inner = byId.get(target.node);
1888
+ const def = inner === void 0 ? void 0 : registry.widget(inner.type, inner.v);
1889
+ if (inner === void 0 || def?.data === void 0 || !Object.hasOwn(def.data, target.input)) continue;
1890
+ inner.data = { ...inner.data ?? {}, [target.input]: { source: key } };
1891
+ innerData[key] = data[name];
1892
+ }
1893
+ }
1894
+ for (const widget of widgets2) widget.id = instanceId(outer.id, widget.id);
1895
+ for (const column2 of columns ?? []) column2.id = instanceId(outer.id, column2.id);
1896
+ const ids = { section: instanceId(outer.id, WRAP.section), column: instanceId(outer.id, WRAP.column), inner: instanceId(outer.id, WRAP.inner) };
1897
+ const column = {
1898
+ id: ids.column,
1899
+ type: "column",
1900
+ props: { width: 100 },
1901
+ children: columns !== void 0 ? [{ id: ids.inner, type: "inner-section", props: { width: "full" }, columns }] : stack ?? []
1902
+ };
1903
+ const document = {
1904
+ schemaVersion: 1,
1905
+ sections: [{ id: ids.section, type: "section", props: { width: "full" }, columns: [column] }]
1906
+ };
1907
+ let weight = 2 + (columns?.length ?? 0) + (columns === void 0 ? 0 : 1);
1908
+ for (const widget of widgets2) {
1909
+ const component = registry.component(widget);
1910
+ weight += 1 + (component === void 0 ? 0 : componentWeights.get(component) ?? 0);
1911
+ }
1912
+ return { document, assets, data: innerData, hrefs, weight };
1913
+ }
1914
+ function CompositeBody(props) {
1915
+ const { snapshot, registry, node, data, locale, mediaOrigin, budget, resolveLink } = props;
1916
+ const composite = compileComposite(snapshot);
1917
+ if (composite === null) return null;
1918
+ const built = build({ snapshot, compiled: composite, registry, node, props: props.props, data });
1919
+ if (!(budget ?? new RenderBudget()).take(built.weight)) {
1920
+ warnOnce(`composite-weight:${snapshot.type}@${String(snapshot.v)}`, `${snapshot.type} would render too many nodes; rendering nothing for it`);
1921
+ return null;
1922
+ }
1923
+ return /* @__PURE__ */ jsx23(
1924
+ BuilderRenderer,
1925
+ {
1926
+ document: built.document,
1927
+ registry,
1928
+ data: built.data,
1929
+ locale,
1930
+ assets: built.assets,
1931
+ mediaOrigin,
1932
+ resolveLink: (target) => built.hrefs.get(JSON.stringify(target)) ?? resolveLink?.(target) ?? null
1933
+ }
1934
+ );
1935
+ }
1936
+ function CompositeWidget(props) {
1937
+ return /* @__PURE__ */ jsx23(PartBoundary, { label: `${props.snapshot.type}@${String(props.snapshot.v)}`, children: /* @__PURE__ */ jsx23(Suspense2, { fallback: null, children: /* @__PURE__ */ jsx23(CompositeBody, { ...props }) }) });
1938
+ }
1939
+
1940
+ // src/custom/factory.ts
1941
+ var isDisabled = (snapshot) => snapshot.status === "disabled";
1942
+ var Disabled = ({ editMode }) => editMode ? createElement3("div", { className: "tb-missing" }, "This custom widget is disabled") : null;
1943
+ var customWidgetFactory = (snapshot, registry) => {
1944
+ if (isDisabled(snapshot)) return Disabled;
1945
+ if (snapshot.kind === "template") {
1946
+ const template = compileTemplate(snapshot, registry);
1947
+ if (template === null) return null;
1948
+ const Component2 = (props) => createElement3(TemplateWidget, { ...props, snapshot, registry });
1949
+ componentWeights.set(Component2, template.weight);
1950
+ return Component2;
1951
+ }
1952
+ if (compileComposite(snapshot) === null) return null;
1953
+ return (props) => createElement3(CompositeWidget, { ...props, snapshot, registry });
1954
+ };
1955
+
1956
+ // src/registry.ts
1957
+ var BUILTIN_PACKS = [basicPack];
1958
+ var DEFAULT_CUSTOM_WIDGET = customWidgetFactory;
1959
+ var customKey = (type, v) => `${type}@${String(v)}`;
1960
+ function createRendererRegistry(packs, options = {}) {
1961
+ const all = [...BUILTIN_PACKS, ...packs];
1962
+ const components = /* @__PURE__ */ new Map();
1963
+ const definitions = [];
1964
+ const sources = [];
1965
+ const resolvers = /* @__PURE__ */ new Map();
1966
+ for (const pack of all) {
1967
+ for (const { Component: Component2, ...definition } of pack.widgets) {
1968
+ const key = customKey(definition.type, definition.v);
1969
+ if (components.has(key)) continue;
1970
+ components.set(key, Component2);
1971
+ definitions.push(definition);
1972
+ }
1973
+ for (const { resolve, ...descriptor } of pack.dataSources) {
1974
+ if (resolvers.has(descriptor.id)) continue;
1975
+ resolvers.set(descriptor.id, resolve);
1976
+ sources.push(descriptor);
1977
+ }
1978
+ }
1979
+ const factory = options.customWidget ?? DEFAULT_CUSTOM_WIDGET;
1980
+ const build2 = (custom) => {
1981
+ const schema = createRegistry(definitions, sources, custom);
1982
+ const snapshots = new Map(custom.map((snapshot) => [customKey(snapshot.type, snapshot.v), snapshot]));
1983
+ const built = /* @__PURE__ */ new Map();
1984
+ const registry = {
1985
+ widget: schema.widget,
1986
+ latest: schema.latest,
1987
+ source: schema.source,
1988
+ sources: schema.sources,
1989
+ all: schema.all,
1990
+ resolver: (id) => resolvers.get(id),
1991
+ component: (node) => {
1992
+ const key = customKey(node.type, node.v);
1993
+ const own = components.get(key);
1994
+ if (own !== void 0) return own;
1995
+ if (!node.type.startsWith("custom.") || factory === void 0) return void 0;
1996
+ const snapshot = snapshots.get(key);
1997
+ if (snapshot === void 0) return void 0;
1998
+ if (!built.has(key)) built.set(key, factory(snapshot, registry));
1999
+ return built.get(key) ?? void 0;
2000
+ },
2001
+ withCustom: (more) => build2([...custom, ...more])
2002
+ };
2003
+ return registry;
2004
+ };
2005
+ return build2([]);
2006
+ }
2007
+
2008
+ // src/slot.tsx
2009
+ import { Suspense as Suspense3 } from "react";
2010
+ import { jsx as jsx24 } from "react/jsx-runtime";
2011
+ function BuilderSlot({ name, context }) {
2012
+ const builder = useBuilder();
2013
+ if (builder === null || builder.site.status !== "ok") return null;
2014
+ const part = Object.hasOwn(builder.site.slots, name) ? builder.site.slots[name] : void 0;
2015
+ if (part === void 0 || part.document.sections.length === 0) return null;
2016
+ return (
2017
+ // Suspense inside the boundary: see parts.tsx.
2018
+ /* @__PURE__ */ jsx24(PartBoundary, { label: `Builder slot ${name}`, children: /* @__PURE__ */ jsx24("div", { "data-throttle-part": "builder-slot", "data-b-slot": name, children: /* @__PURE__ */ jsx24(Suspense3, { fallback: null, children: /* @__PURE__ */ jsx24(PartView, { part, context }) }) }) })
2019
+ );
2020
+ }
2021
+
2022
+ // src/theme.ts
2023
+ import { SITE_FONTS, safeUrl as safeUrl12 } from "@usethrottle/builder-schema";
2024
+ import { PRESET_NAMES, PRESET_TOKENS } from "@usethrottle/ui/presets";
2025
+ var isRecord4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
2026
+ var str2 = (v) => typeof v === "string" && v !== "" ? v : void 0;
2027
+ var HEX = /^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
2028
+ var SCALE = { compact: 0.85, comfortable: 1, roomy: 1.25 };
2029
+ var PALETTE_KEYS = Object.keys(PRESET_TOKENS.clean.light);
2030
+ function palette(base, over) {
2031
+ if (!isRecord4(over)) return base;
2032
+ const out = { ...base };
2033
+ for (const key of PALETTE_KEYS) {
2034
+ const value = over[key];
2035
+ if (typeof value === "string" && HEX.test(value)) out[key] = value;
2036
+ }
2037
+ return out;
2038
+ }
2039
+ function themeTokens(settings) {
2040
+ const theme = isRecord4(settings.theme) ? settings.theme : {};
2041
+ const preset = PRESET_NAMES.includes(theme.preset) ? theme.preset : "clean";
2042
+ const customized = theme.customized === true;
2043
+ const base = PRESET_TOKENS[preset];
2044
+ const colorScheme = theme.colorScheme === "light" || theme.colorScheme === "dark" ? theme.colorScheme : "auto";
2045
+ if (!customized) return { preset, customized, tokens: base, colorScheme };
2046
+ const fonts = isRecord4(theme.fonts) ? theme.fonts : {};
2047
+ return {
2048
+ preset,
2049
+ customized,
2050
+ colorScheme,
2051
+ tokens: {
2052
+ light: palette(base.light, theme.light),
2053
+ dark: palette(base.dark, theme.dark),
2054
+ fonts: {
2055
+ heading: str2(fonts.heading) ?? base.fonts.heading,
2056
+ body: str2(fonts.body) ?? base.fonts.body,
2057
+ mono: str2(fonts.mono) ?? base.fonts.mono
2058
+ },
2059
+ radius: typeof theme.radius === "number" && theme.radius >= 0 && theme.radius <= 32 ? theme.radius : base.radius,
2060
+ spacingScale: theme.spacingScale === "compact" || theme.spacingScale === "roomy" ? theme.spacingScale : base.spacingScale
2061
+ }
2062
+ };
2063
+ }
2064
+ var GENERIC = { serif: "serif", sans: "sans-serif", mono: "monospace", display: "sans-serif" };
2065
+ var SYSTEM_STACK = {
2066
+ "system-sans": 'system-ui, -apple-system, "Segoe UI", sans-serif',
2067
+ "system-serif": 'Georgia, "Times New Roman", serif',
2068
+ "system-mono": "ui-monospace, SFMono-Regular, Menlo, monospace"
2069
+ };
2070
+ function fontStack(family) {
2071
+ if (Object.hasOwn(SYSTEM_STACK, family)) return SYSTEM_STACK[family];
2072
+ const known = SITE_FONTS.find((f) => f.family === family);
2073
+ if (known === void 0 || !/^[A-Za-z0-9 ]{1,60}$/.test(family)) return SYSTEM_STACK["system-sans"];
2074
+ return `"${family}", ${Object.hasOwn(GENERIC, known.category) ? GENERIC[known.category] : "sans-serif"}`;
2075
+ }
2076
+ function variables(p) {
2077
+ return {
2078
+ colorPrimary: p.colorPrimary,
2079
+ colorPrimaryForeground: p.colorPrimaryForeground,
2080
+ colorBackground: p.colorBackground,
2081
+ colorSurface: p.colorSurface,
2082
+ colorForeground: p.colorForeground,
2083
+ colorMuted: p.colorMuted,
2084
+ colorMutedForeground: p.colorMutedForeground,
2085
+ colorBorder: p.colorBorder,
2086
+ colorBorderControl: p.colorBorderControl,
2087
+ colorSuccess: p.colorSuccess,
2088
+ colorWarning: p.colorWarning,
2089
+ colorDanger: p.colorDanger
2090
+ };
2091
+ }
2092
+ function appearanceOf(settings) {
2093
+ const { tokens, colorScheme } = themeTokens(settings);
2094
+ return {
2095
+ theme: colorScheme,
2096
+ variables: {
2097
+ ...variables(tokens.light),
2098
+ fontFamily: fontStack(tokens.fonts.body),
2099
+ borderRadius: `${String(tokens.radius)}px`
2100
+ },
2101
+ darkVariables: variables(tokens.dark)
2102
+ };
2103
+ }
2104
+ var kebab = (key) => key.replace(/^color/, "").replace(/([a-z])([A-Z])/g, "$1-$2").replace(/^([A-Z])/, (c) => c.toLowerCase()).toLowerCase();
2105
+ function colourDecls(p) {
2106
+ return PALETTE_KEYS.map((key) => `--tb-color-${kebab(key)}:${p[key]}`).join(";");
2107
+ }
2108
+ function themeCss(settings) {
2109
+ const { tokens, colorScheme } = themeTokens(settings);
2110
+ const light = `:root{--tb-scale:${String(SCALE[tokens.spacingScale])};${colourDecls(tokens.light)}}`;
2111
+ const dark = colourDecls(tokens.dark);
2112
+ if (colorScheme === "light") return light;
2113
+ if (colorScheme === "dark") return `${light}:root{${dark}}`;
2114
+ return `${light}@media (prefers-color-scheme:dark){:root{${dark}}}`;
2115
+ }
2116
+ function makeResolveLink(settings, packs) {
2117
+ const routes = isRecord4(settings.routes) ? settings.routes : {};
2118
+ const pageRoute = str2(routes.page) ?? "/pages/{handle}";
2119
+ return (target) => {
2120
+ for (const pack of packs) {
2121
+ const href = pack.linkTargets?.resolve(target) ?? null;
2122
+ if (href !== null) return safeUrl12(href, "href", { mediaOrigin: "" });
2123
+ }
2124
+ if (target.kind === "url") return safeUrl12(target.href, "href", { mediaOrigin: "" });
2125
+ if (typeof target.href === "string") return safeUrl12(target.href, "href", { mediaOrigin: "" });
2126
+ if (target.kind === "page") {
2127
+ const slug = str2(target.slug) ?? str2(target.handle);
2128
+ if (slug !== void 0 && /^[A-Za-z0-9._~-]{1,200}$/.test(slug)) {
2129
+ return safeUrl12(pageRoute.replace("{handle}", slug), "href", { mediaOrigin: "" });
2130
+ }
2131
+ }
2132
+ return null;
2133
+ };
2134
+ }
2135
+ var MENU_KINDS = /* @__PURE__ */ new Set(["category", "collection", "product", "page", "search", "url"]);
2136
+ function menuItems(items, resolve, depth = 0) {
2137
+ if (!Array.isArray(items) || depth > 3) return [];
2138
+ const out = [];
2139
+ for (const item of items) {
2140
+ if (!isRecord4(item) || !isRecord4(item.target) || typeof item.target.kind !== "string") continue;
2141
+ const label = str2(item.label);
2142
+ const href = resolve(item.target);
2143
+ if (label === void 0 || href === null) continue;
2144
+ const kind = MENU_KINDS.has(item.target.kind) ? item.target.kind : void 0;
2145
+ const children = menuItems(item.children, resolve, depth + 1);
2146
+ out.push({
2147
+ label,
2148
+ href,
2149
+ ...kind === void 0 ? {} : { kind },
2150
+ ...children.length === 0 ? {} : { children }
2151
+ });
2152
+ }
2153
+ return out;
2154
+ }
2155
+ var assetUrl = (v, mediaOrigin) => {
2156
+ const raw = typeof v === "string" ? v : isRecord4(v) ? v.url : void 0;
2157
+ return typeof raw === "string" ? safeUrl12(raw, "src", { mediaOrigin }) ?? void 0 : void 0;
2158
+ };
2159
+ function siteDesignOf(settings, resolve, pageOutlet, mediaOrigin) {
2160
+ const { preset, customized, tokens, colorScheme } = themeTokens(settings);
2161
+ const brand = isRecord4(settings.brand) ? settings.brand : {};
2162
+ const logo = isRecord4(brand.logo) ? brand.logo : {};
2163
+ const light = assetUrl(logo.light, mediaOrigin);
2164
+ const dark = assetUrl(logo.dark, mediaOrigin);
2165
+ const favicon = assetUrl(brand.favicon, mediaOrigin);
2166
+ const menus = isRecord4(settings.menus) ? Object.fromEntries(Object.entries(settings.menus).map(([name, items]) => [name, menuItems(items, resolve)])) : {};
2167
+ const announcement = isRecord4(settings.announcement) ? settings.announcement : null;
2168
+ const message = announcement === null ? void 0 : str2(announcement.message);
2169
+ const announcementHref = announcement !== null && isRecord4(announcement.target) && typeof announcement.target.kind === "string" ? resolve(announcement.target) : null;
2170
+ const strings = isRecord4(settings.strings) ? Object.fromEntries(Object.entries(settings.strings).filter((entry) => typeof entry[1] === "string")) : {};
2171
+ const seo = isRecord4(settings.seo) ? settings.seo : {};
2172
+ const routes = isRecord4(settings.routes) ? settings.routes : {};
2173
+ const connections = isRecord4(settings.connections) ? settings.connections : {};
2174
+ const shareImage = assetUrl(seo.shareImage, mediaOrigin);
2175
+ const titleTemplate = str2(seo.titleTemplate);
2176
+ const defaultDescription = str2(seo.defaultDescription);
2177
+ const pageRoute = str2(routes.page);
2178
+ return {
2179
+ source: "builder",
2180
+ theme: { preset, customized, colorScheme, ...customized ? { values: tokens } : {} },
2181
+ brand: {
2182
+ ...str2(brand.storeName) === void 0 ? {} : { storeName: str2(brand.storeName) },
2183
+ logo: light === void 0 && dark === void 0 ? null : { ...light === void 0 ? {} : { light }, ...dark === void 0 ? {} : { dark } },
2184
+ favicon: favicon ?? null
2185
+ },
2186
+ menus,
2187
+ announcement: announcement !== null && announcement.enabled === true && message !== void 0 ? { message, ...announcementHref === null ? {} : { href: announcementHref } } : null,
2188
+ strings,
2189
+ seo: {
2190
+ ...titleTemplate === void 0 ? {} : { titleTemplate },
2191
+ ...defaultDescription === void 0 ? {} : { defaultDescription },
2192
+ ...shareImage === void 0 ? {} : { shareImage }
2193
+ },
2194
+ ...pageRoute === void 0 ? {} : { routes: { page: pageRoute } },
2195
+ connections: {
2196
+ throttlePublishableKey: typeof connections.throttlePublishableKey === "string" ? connections.throttlePublishableKey : null
2197
+ },
2198
+ ...pageOutlet === void 0 ? {} : { pageOutlet }
2199
+ };
2200
+ }
2201
+
2202
+ // src/provider.tsx
2203
+ import { jsx as jsx25, jsxs as jsxs15 } from "react/jsx-runtime";
2204
+ var EMPTY = {};
2205
+ function BuilderProvider({ builderKey, client, packs, site, children }) {
2206
+ const packsKey = packs.map((pack) => `${pack.id}@${pack.version}`).join("|");
2207
+ const registryRef = useRef2(null);
2208
+ if (registryRef.current?.key !== packsKey) {
2209
+ registryRef.current = { key: packsKey, registry: createRendererRegistry(packs) };
2210
+ }
2211
+ const registry = registryRef.current.registry;
2212
+ const builder = useMemo(
2213
+ () => client ?? (builderKey === void 0 ? null : createBuilderClient({ builderKey })),
2214
+ [client, builderKey]
2215
+ );
2216
+ const mediaOrigin = site.status === "ok" ? site.mediaOrigin : "";
2217
+ const settings = site.status === "ok" ? site.settings : EMPTY;
2218
+ const resolveLink = useMemo(() => makeResolveLink(settings, packs), [settings, packs]);
2219
+ const outlets = useRef2(/* @__PURE__ */ new Map());
2220
+ const renderers = useRef2(/* @__PURE__ */ new Map());
2221
+ const pageOutlet = useCallback((handle) => {
2222
+ let outlet = outlets.current.get(handle);
2223
+ if (outlet === void 0) {
2224
+ outlet = function PageOutlet() {
2225
+ return /* @__PURE__ */ jsx25(PartBoundary, { label: `Builder page ${handle}`, children: /* @__PURE__ */ jsx25(Suspense4, { fallback: null, children: /* @__PURE__ */ jsx25(BuilderPage, { slug: handle }) }) });
2226
+ };
2227
+ outlets.current.set(handle, outlet);
2228
+ }
2229
+ return outlet;
2230
+ }, []);
2231
+ const resolveSlot = useCallback(
2232
+ (name) => {
2233
+ const part = site.status === "ok" && Object.hasOwn(site.slots, name) ? site.slots[name] : void 0;
2234
+ if (part === void 0 || part.document.sections.length === 0) return null;
2235
+ let renderer = renderers.current.get(name);
2236
+ if (renderer === void 0) {
2237
+ renderer = function SlotRenderer({ context }) {
2238
+ return /* @__PURE__ */ jsx25(BuilderSlot, { name, context });
2239
+ };
2240
+ renderers.current.set(name, renderer);
2241
+ }
2242
+ return renderer;
2243
+ },
2244
+ [site]
2245
+ );
2246
+ const value = useMemo(
2247
+ () => ({ client: builder, packs, registry, site, locale: site.locale, mediaOrigin, resolveLink }),
2248
+ [builder, packs, registry, site, mediaOrigin, resolveLink]
2249
+ );
2250
+ const design = useMemo(
2251
+ () => site.status === "ok" ? siteDesignOf(site.settings, resolveLink, pageOutlet, mediaOrigin) : null,
2252
+ [site, resolveLink, pageOutlet, mediaOrigin]
2253
+ );
2254
+ const appearance = useMemo(() => site.status === "ok" ? appearanceOf(site.settings) : void 0, [site]);
2255
+ return /* @__PURE__ */ jsx25(BuilderContext.Provider, { value, children: /* @__PURE__ */ jsx25(ThrottleUIProvider, { ...appearance === void 0 ? {} : { appearance }, children: /* @__PURE__ */ jsx25(SiteDesignProvider, { value: design, children: /* @__PURE__ */ jsxs15(SlotOutletProvider, { resolve: resolveSlot, children: [
2256
+ site.status === "ok" ? /* @__PURE__ */ jsx25("style", { children: themeCss(site.settings) }) : null,
2257
+ children
2258
+ ] }) }) }) });
2259
+ }
2260
+
2261
+ // src/parts.tsx
2262
+ import { Suspense as Suspense5 } from "react";
2263
+ import { jsx as jsx26 } from "react/jsx-runtime";
2264
+ function Part({ name, tag }) {
2265
+ const builder = useBuilder();
2266
+ if (builder === null || builder.site.status !== "ok") return null;
2267
+ const part = builder.site[name];
2268
+ if (part.document.sections.length === 0) return null;
2269
+ const Tag = tag;
2270
+ return (
2271
+ // Error boundaries do not catch on the server: the Suspense inside turns a throw
2272
+ // during SSR into "render nothing here" and the client retries under the boundary.
2273
+ /* @__PURE__ */ jsx26(PartBoundary, { label: `Builder ${name}`, children: /* @__PURE__ */ jsx26(Tag, { "data-throttle-part": `builder-${name}`, children: /* @__PURE__ */ jsx26(Suspense5, { fallback: null, children: /* @__PURE__ */ jsx26(PartView, { part }) }) }) })
2274
+ );
2275
+ }
2276
+ var BuilderHeader = () => /* @__PURE__ */ jsx26(Part, { name: "header", tag: "header" });
2277
+ var BuilderFooter = () => /* @__PURE__ */ jsx26(Part, { name: "footer", tag: "footer" });
2278
+
2279
+ // src/index.ts
2280
+ import { BuilderNotFoundError, BuilderUnavailableError as BuilderUnavailableError2 } from "@usethrottle/builder";
2281
+ export {
2282
+ AssetImage,
2283
+ BASE_CSS,
2284
+ BASIC_COMPONENTS,
2285
+ BuilderContext,
2286
+ BuilderFooter,
2287
+ BuilderHeader,
2288
+ BuilderNotFoundError,
2289
+ BuilderPage,
2290
+ BuilderPageView,
2291
+ BuilderProvider,
2292
+ BuilderRenderer,
2293
+ BuilderSlot,
2294
+ BuilderUnavailableError2 as BuilderUnavailableError,
2295
+ CUSTOM_WIDGET_CONTAINMENT,
2296
+ CompositeWidget,
2297
+ MAX_RENDERED_NODES,
2298
+ NodeWrapper,
2299
+ RenderBudget,
2300
+ RichText,
2301
+ TemplateWidget,
2302
+ WidgetStyle,
2303
+ basicPack,
2304
+ bindingKey,
2305
+ bindingsOf,
2306
+ collectBindings,
2307
+ compileResponsiveCss,
2308
+ createRendererRegistry,
2309
+ cssValue,
2310
+ customWidgetFactory,
2311
+ embedSrc,
2312
+ fitsBudget,
2313
+ isFrozenAsset,
2314
+ parseRichText,
2315
+ parseVideoUrl,
2316
+ pickLocale,
2317
+ resolveBindings,
2318
+ useBuilder,
2319
+ validateRender
2320
+ };