@usethrottle/builder-react 0.3.1 → 0.4.1

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 CHANGED
@@ -4,38 +4,869 @@ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { en
4
4
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
5
 
6
6
  // src/renderer.tsx
7
- import { Fragment } from "react";
7
+ import { Fragment as Fragment3 } from "react";
8
8
  import {
9
+ ANCHOR_RE as ANCHOR_RE3,
9
10
  COMMON_WIDGET_SETTINGS as COMMON_WIDGET_SETTINGS2,
11
+ resolveEntrance,
12
+ resolveInteraction,
13
+ codeWidgetSnapshotSchema,
10
14
  resolveResponsive as resolveResponsive2,
11
- safeUrl as safeUrl2,
15
+ safeUrl as safeUrl3,
12
16
  upgradeNodes,
13
17
  validateSettingValue as validateSettingValue2,
14
- walkNodes as walkNodes2
18
+ walkNodes as walkNodes3
15
19
  } from "@usethrottle/builder-schema";
16
20
 
17
- // src/budget.ts
18
- import { MAX_TEMPLATE_WEIGHT, templateWeight } from "@usethrottle/builder-schema";
19
- var MAX_RENDERED_NODES = MAX_TEMPLATE_WEIGHT;
20
- var RenderBudget = class {
21
- constructor(limit = MAX_RENDERED_NODES) {
22
- this.limit = limit;
23
- __publicField(this, "spent", 0);
21
+ // src/budget.ts
22
+ import { MAX_TEMPLATE_WEIGHT, templateWeight } from "@usethrottle/builder-schema";
23
+ var MAX_RENDERED_NODES = MAX_TEMPLATE_WEIGHT;
24
+ var RenderBudget = class {
25
+ constructor(limit = MAX_RENDERED_NODES) {
26
+ this.limit = limit;
27
+ __publicField(this, "spent", 0);
28
+ }
29
+ /** Takes `count` nodes. False, and nothing taken, when that would pass the limit. */
30
+ take(count = 1) {
31
+ if (this.spent + count > this.limit) return false;
32
+ this.spent += count;
33
+ return true;
34
+ }
35
+ get used() {
36
+ return this.spent;
37
+ }
38
+ get exhausted() {
39
+ return this.spent >= this.limit;
40
+ }
41
+ };
42
+ var fitsBudget = (ast, limit = MAX_RENDERED_NODES) => templateWeight(ast) <= limit;
43
+
44
+ // src/code/code-widget.tsx
45
+ import { Suspense as Suspense2 } from "react";
46
+ import { LIMITS } from "@usethrottle/builder-schema";
47
+
48
+ // src/custom/custom-css.tsx
49
+ import { sanitizeWidgetCss } from "@usethrottle/builder-schema";
50
+
51
+ // src/widget-style.tsx
52
+ import { jsx } from "react/jsx-runtime";
53
+ function WidgetStyle({ css }) {
54
+ if (css === "" || css.includes("<")) return null;
55
+ return /* @__PURE__ */ jsx("style", { children: css });
56
+ }
57
+
58
+ // src/custom/custom-css.tsx
59
+ import { jsx as jsx2 } from "react/jsx-runtime";
60
+ function scopedCss(source, type) {
61
+ if (source === void 0 || source === "") return "";
62
+ if (typeof source !== "string") return null;
63
+ const result = sanitizeWidgetCss(source, type);
64
+ return result.ok ? result.css : null;
65
+ }
66
+ function CustomCss({ css }) {
67
+ return /* @__PURE__ */ jsx2(WidgetStyle, { css });
68
+ }
69
+
70
+ // src/custom/interpreter.tsx
71
+ import { Fragment, createElement } from "react";
72
+ import {
73
+ ALLOWED_ATTRS,
74
+ ALLOWED_ELEMENTS,
75
+ ALLOWED_ROLES,
76
+ CLASS_TOKEN_RE,
77
+ DATA_ATTR_RE,
78
+ EACH_ITERATION_CAP,
79
+ RESERVED_DATA_PREFIX,
80
+ VOID_ELEMENTS,
81
+ isReservedClass,
82
+ safeUrl
83
+ } from "@usethrottle/builder-schema";
84
+ import { jsx as jsx3 } from "react/jsx-runtime";
85
+ var MAX_OUTPUT_CHARS = 1e6;
86
+ var MAX_ATTR_CHARS = 2e3;
87
+ var MAX_DEPTH = 24;
88
+ function newEnv(env) {
89
+ return { ...env, charsLeft: MAX_OUTPUT_CHARS, stopped: false };
90
+ }
91
+ var BLOCKED = /* @__PURE__ */ new Set([
92
+ "__proto__",
93
+ "constructor",
94
+ "prototype",
95
+ ...Object.getOwnPropertyNames(Object.prototype)
96
+ ]);
97
+ var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
98
+ function step(value, key) {
99
+ if (BLOCKED.has(key) || !isPlainObject(value) || !Object.hasOwn(value, key)) return void 0;
100
+ return value[key];
101
+ }
102
+ function lookup(path, env, scope) {
103
+ const [root, ...rest] = path;
104
+ if (root === void 0) return void 0;
105
+ if (root === "locale") return rest.length === 0 ? env.locale : void 0;
106
+ let value;
107
+ if (root === "settings") value = rest.length === 0 ? void 0 : env.settings;
108
+ else if (root === "data") value = rest.length === 0 ? void 0 : env.data;
109
+ else if (scope.has(root)) value = scope.get(root);
110
+ else return void 0;
111
+ for (const key of rest) {
112
+ value = step(value, key);
113
+ if (value === void 0) return void 0;
114
+ }
115
+ return value;
116
+ }
117
+ function truthy(value) {
118
+ if (value === null || value === void 0 || value === false || value === "") return false;
119
+ if (typeof value === "number") return value !== 0 && !Number.isNaN(value);
120
+ if (Array.isArray(value)) return value.length > 0;
121
+ return true;
122
+ }
123
+ function asText(value) {
124
+ if (typeof value === "string") return value;
125
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
126
+ return "";
127
+ }
128
+ function filtered(value, filters) {
129
+ let text = asText(value);
130
+ for (const filter of filters) {
131
+ switch (filter.name) {
132
+ case "upper":
133
+ text = text.toUpperCase();
134
+ break;
135
+ case "lower":
136
+ text = text.toLowerCase();
137
+ break;
138
+ case "truncate": {
139
+ const chars = Array.from(text);
140
+ if (chars.length > filter.n) text = `${chars.slice(0, filter.n).join("")}\u2026`;
141
+ break;
142
+ }
143
+ case "default":
144
+ if (text === "") text = filter.text;
145
+ break;
146
+ }
147
+ }
148
+ return text;
149
+ }
150
+ function spend(env, count) {
151
+ if (count > env.charsLeft) {
152
+ env.stopped = true;
153
+ return false;
154
+ }
155
+ env.charsLeft -= count;
156
+ return true;
157
+ }
158
+ var ELEMENTS = new Set(ALLOWED_ELEMENTS);
159
+ var VOIDS = new Set(VOID_ELEMENTS);
160
+ var ROLES = new Set(ALLOWED_ROLES);
161
+ function attrAllowed(tag, name) {
162
+ if (DATA_ATTR_RE.test(name)) return !name.startsWith(RESERVED_DATA_PREFIX);
163
+ const own = Object.hasOwn(ALLOWED_ATTRS, tag) ? ALLOWED_ATTRS[tag] : void 0;
164
+ return (ALLOWED_ATTRS["*"]?.includes(name) ?? false) || (own?.includes(name) ?? false);
165
+ }
166
+ function attrText(attr, env, scope) {
167
+ return attr.value.map((part) => part.type === "text" ? part.value : filtered(lookup(part.path, env, scope), part.filters)).join("");
168
+ }
169
+ function urlSource(attr, env, scope) {
170
+ const [only] = attr.value;
171
+ if (attr.value.length !== 1 || only === void 0 || only.type !== "output") return attrText(attr, env, scope);
172
+ const value = lookup(only.path, env, scope);
173
+ if (isPlainObject(value)) {
174
+ if (typeof value.href === "string") return value.href;
175
+ if (typeof value.url === "string") return value.url;
176
+ return null;
177
+ }
178
+ return value;
179
+ }
180
+ function attrProp(tag, attr, env, scope) {
181
+ const { name } = attr;
182
+ if (!attrAllowed(tag, name)) return null;
183
+ if (name === "href" || name === "src") {
184
+ const safe = safeUrl(urlSource(attr, env, scope), name, { mediaOrigin: env.mediaOrigin });
185
+ return safe === null || !spend(env, safe.length) ? null : [name, safe];
186
+ }
187
+ const text = attrText(attr, env, scope);
188
+ if (text === "" || text.length > MAX_ATTR_CHARS) return null;
189
+ let value = text;
190
+ if (name === "class") {
191
+ const tokens = text.split(/\s+/).filter((token) => CLASS_TOKEN_RE.test(token) && !isReservedClass(token));
192
+ if (tokens.length === 0) return null;
193
+ value = tokens.join(" ");
194
+ } else if (name === "role") {
195
+ if (!ROLES.has(text)) return null;
196
+ } else if (name === "aria-hidden") {
197
+ if (text !== "true" && text !== "false") return null;
198
+ }
199
+ if (!spend(env, value.length)) return null;
200
+ return [name === "class" ? "className" : name, value];
201
+ }
202
+ function renderElement(node, env, scope, depth, key) {
203
+ const tag = node.tag;
204
+ if (!ELEMENTS.has(tag)) return null;
205
+ const props = { key };
206
+ for (const attr of node.attrs) {
207
+ const prop = attrProp(tag, attr, env, scope);
208
+ if (prop !== null) props[prop[0]] = prop[1];
209
+ }
210
+ if (VOIDS.has(tag)) return createElement(tag, props);
211
+ return createElement(tag, props, renderNodes(node.children, env, scope, depth + 1));
212
+ }
213
+ function renderNodes(nodes, env, scope, depth) {
214
+ const out = [];
215
+ if (depth > MAX_DEPTH) return out;
216
+ for (const node of nodes) {
217
+ if (env.stopped) break;
218
+ if (!env.budget.take(1) || node.type === "element" && !env.budget.take(node.attrs.reduce((n, a) => n + a.value.length, 0))) {
219
+ env.stopped = true;
220
+ break;
221
+ }
222
+ switch (node.type) {
223
+ case "text":
224
+ if (spend(env, node.value.length)) out.push(node.value);
225
+ break;
226
+ case "output": {
227
+ const text = filtered(lookup(node.path, env, scope), node.filters);
228
+ if (text !== "" && spend(env, text.length)) out.push(text);
229
+ break;
230
+ }
231
+ case "if": {
232
+ const branch = truthy(lookup(node.path, env, scope)) ? node.then : node.else;
233
+ out.push(/* @__PURE__ */ jsx3(Fragment, { children: renderNodes(branch, env, scope, depth + 1) }, out.length));
234
+ break;
235
+ }
236
+ case "unless":
237
+ if (!truthy(lookup(node.path, env, scope))) {
238
+ out.push(/* @__PURE__ */ jsx3(Fragment, { children: renderNodes(node.body, env, scope, depth + 1) }, out.length));
239
+ }
240
+ break;
241
+ case "each": {
242
+ const list = lookup(node.path, env, scope);
243
+ if (!Array.isArray(list)) break;
244
+ const count = Math.min(list.length, EACH_ITERATION_CAP);
245
+ for (let i = 0; i < count && !env.stopped; i += 1) {
246
+ const inner = new Map(scope).set(node.as, list[i]);
247
+ out.push(/* @__PURE__ */ jsx3(Fragment, { children: renderNodes(node.body, env, inner, depth + 1) }, out.length));
248
+ }
249
+ break;
250
+ }
251
+ case "element":
252
+ out.push(renderElement(node, env, scope, depth, out.length));
253
+ break;
254
+ }
255
+ }
256
+ return out;
257
+ }
258
+ function renderTemplate(ast, env) {
259
+ return renderNodes(ast, env, /* @__PURE__ */ new Map(), 0);
260
+ }
261
+
262
+ // src/custom/template-widget.tsx
263
+ import { Suspense } from "react";
264
+ import { MAX_TEMPLATE_WEIGHT as MAX_TEMPLATE_WEIGHT2, parseTemplate, templateWeight as templateWeight2, validateTemplate } from "@usethrottle/builder-schema";
265
+
266
+ // src/part-view.tsx
267
+ import { Component } from "react";
268
+
269
+ // src/context.ts
270
+ import { createContext, useContext } from "react";
271
+ function codeRenderOf(builder, runtime) {
272
+ return { runtime, pathname: builder.pathname, routes: builder.codeRoutes, preview: builder.mode === "preview" };
273
+ }
274
+ var BuilderContext = typeof createContext === "function" ? createContext(null) : null;
275
+ var useBuilder = () => useContext(BuilderContext);
276
+
277
+ // src/saved-section.tsx
278
+ import { ANCHOR_RE as ANCHOR_RE2, anyCustomWidgetSnapshotSchema, sectionNodeSchema, walkNodes } from "@usethrottle/builder-schema";
279
+
280
+ // src/node-wrapper.tsx
281
+ import { ANCHOR_RE } from "@usethrottle/builder-schema";
282
+ import { jsx as jsx4 } from "react/jsx-runtime";
283
+ var CUSTOM_WIDGET_CONTAINMENT = {
284
+ contain: "layout paint",
285
+ isolation: "isolate",
286
+ overflow: "clip"
287
+ };
288
+ var PART_NAME = {
289
+ section: "builder-section",
290
+ column: "builder-column",
291
+ widget: "builder-widget"
292
+ };
293
+ function NodeWrapper(props) {
294
+ const { id, part, type, className, anchor, copyAnchor, custom, missing, attributes, edit, entrance, children } = props;
295
+ const Tag = props.as ?? "div";
296
+ const handlers = edit === void 0 ? {} : {
297
+ onClickCapture: (event) => {
298
+ const target = event.target;
299
+ if (target?.closest?.("a[href]") != null) event.preventDefault();
300
+ },
301
+ onClick: (event) => {
302
+ event.stopPropagation();
303
+ edit.onSelect(id);
304
+ },
305
+ onMouseOver: (event) => {
306
+ event.stopPropagation();
307
+ edit.onHover(id);
308
+ },
309
+ onMouseLeave: () => edit.onHover(null)
310
+ };
311
+ const style = custom === true || entrance !== void 0 ? {
312
+ ...custom === true ? CUSTOM_WIDGET_CONTAINMENT : {},
313
+ ...entrance !== void 0 && entrance.delayMs > 0 ? { "--tb-ed": `${String(entrance.delayMs)}ms` } : {}
314
+ } : void 0;
315
+ return /* @__PURE__ */ jsx4(
316
+ Tag,
317
+ {
318
+ className,
319
+ "data-b-id": id,
320
+ "data-throttle-part": PART_NAME[part],
321
+ ...type === void 0 ? {} : { "data-b-type": type },
322
+ ...custom === true && type !== void 0 ? { "data-b-w": type } : {},
323
+ ...missing === true ? { "data-b-missing": "" } : {},
324
+ ...attributes,
325
+ ...typeof anchor === "string" && ANCHOR_RE.test(anchor) ? { id: anchor } : {},
326
+ ...typeof copyAnchor === "string" && ANCHOR_RE.test(copyAnchor) ? { "data-b-anchor": copyAnchor } : {},
327
+ ...entrance === void 0 ? {} : { "data-b-entrance": entrance.name },
328
+ ...style === void 0 || Object.keys(style).length === 0 ? {} : { style },
329
+ ...handlers,
330
+ children
331
+ }
332
+ );
333
+ }
334
+
335
+ // src/warn.ts
336
+ var seen = /* @__PURE__ */ new Set();
337
+ function warnOnce(key, message) {
338
+ if (seen.has(key)) return;
339
+ seen.add(key);
340
+ console.warn(`[throttle-builder] ${message}`);
341
+ }
342
+ var isDevelopment = () => typeof process === "undefined" || process.env?.NODE_ENV !== "production";
343
+
344
+ // src/saved-section.tsx
345
+ import { jsx as jsx5 } from "react/jsx-runtime";
346
+ var pid = (refId, id) => `${refId}-${id}`;
347
+ var MAX_EXPANDED_NODES = 2e4;
348
+ function prefixAnchor(refId, props) {
349
+ const anchor = props.anchor;
350
+ if (typeof anchor !== "string") return props;
351
+ const prefixed = pid(refId, anchor);
352
+ const { anchor: _drop, ...rest } = props;
353
+ void _drop;
354
+ return ANCHOR_RE2.test(prefixed) ? { ...rest, anchor: prefixed } : rest;
355
+ }
356
+ function prefixColumn(refId, column) {
357
+ return {
358
+ ...column,
359
+ id: pid(refId, column.id),
360
+ props: prefixAnchor(refId, column.props),
361
+ children: column.children.map(
362
+ (child) => child.type === "inner-section" ? prefixSection(refId, child) : { ...child, id: pid(refId, child.id), props: prefixAnchor(refId, child.props) }
363
+ )
364
+ };
365
+ }
366
+ function prefixSection(refId, section) {
367
+ return {
368
+ ...section,
369
+ id: pid(refId, section.id),
370
+ props: prefixAnchor(refId, section.props),
371
+ columns: section.columns.map((column) => prefixColumn(refId, column))
372
+ };
373
+ }
374
+ var parsed = /* @__PURE__ */ new WeakMap();
375
+ function sectionOf(entry) {
376
+ const cached = parsed.get(entry);
377
+ if (cached !== void 0) return cached;
378
+ const result = sectionNodeSchema.safeParse(entry.section);
379
+ const section = result.success ? result.data : null;
380
+ parsed.set(entry, section);
381
+ return section;
382
+ }
383
+ var sized = /* @__PURE__ */ new WeakMap();
384
+ function sizeOf(section) {
385
+ const known = sized.get(section);
386
+ if (known !== void 0) return known;
387
+ let size = 0;
388
+ walkNodes({ sections: [section] }, () => {
389
+ size += 1;
390
+ });
391
+ sized.set(section, size);
392
+ return size;
393
+ }
394
+ var cache = /* @__PURE__ */ new WeakMap();
395
+ var NONE = {};
396
+ function expandSavedSections(source, answer) {
397
+ if (!source.sections.some((root) => root.type === "saved-section")) return { doc: source, roots: null };
398
+ let perAnswer = cache.get(source);
399
+ if (perAnswer === void 0) {
400
+ perAnswer = /* @__PURE__ */ new WeakMap();
401
+ cache.set(source, perAnswer);
402
+ }
403
+ const key = answer ?? NONE;
404
+ const known = perAnswer.get(key);
405
+ if (known !== void 0) return known;
406
+ const made = expand(source, answer);
407
+ perAnswer.set(key, made);
408
+ return made;
409
+ }
410
+ function expand(source, answer) {
411
+ const sections = [];
412
+ const roots = [];
413
+ const snapshots = {};
414
+ let nodes = 0;
415
+ walkNodes({ sections: source.sections.filter((root) => root.type === "section") }, () => {
416
+ nodes += 1;
417
+ });
418
+ for (const root of source.sections) {
419
+ if (root.type === "section") {
420
+ sections.push(root);
421
+ roots.push({ kind: "section", id: root.id });
422
+ continue;
423
+ }
424
+ const entry = answer !== void 0 && Object.hasOwn(answer, root.ref) ? answer[root.ref] : void 0;
425
+ const section = entry === void 0 ? null : sectionOf(entry);
426
+ if (entry !== void 0 && section !== null && nodes + sizeOf(section) > MAX_EXPANDED_NODES) {
427
+ warnOnce("saved-section-cap", `A page holds more than ${String(MAX_EXPANDED_NODES)} nodes with its saved sections; the rest are left out`);
428
+ roots.push({ kind: "ref", ref: root, sectionId: null });
429
+ continue;
430
+ }
431
+ if (entry === void 0 || section === null) {
432
+ roots.push({ kind: "ref", ref: root, sectionId: null });
433
+ continue;
434
+ }
435
+ nodes += sizeOf(section);
436
+ const prefixed = prefixSection(root.id, section);
437
+ const anchor = root.props.anchor;
438
+ const placed = anchor !== void 0 ? { ...prefixed, props: { ...prefixed.props, anchor } } : prefixed;
439
+ sections.push(placed);
440
+ roots.push({ kind: "ref", ref: root, sectionId: placed.id });
441
+ for (const [snapshotKey, snapshot] of Object.entries(entry.customWidgets ?? {})) {
442
+ if (anyCustomWidgetSnapshotSchema.safeParse(snapshot).success) snapshots[snapshotKey] = snapshot;
443
+ }
444
+ }
445
+ const customWidgets = { ...snapshots, ...source.customWidgets };
446
+ return {
447
+ doc: { ...source, sections, ...Object.keys(customWidgets).length === 0 ? {} : { customWidgets } },
448
+ roots
449
+ };
450
+ }
451
+ function MissingSavedSection({ node }) {
452
+ warnOnce(`saved-section:${node.ref}`, `Saved section ${node.ref} has no published section; rendering nothing for it`);
453
+ return /* @__PURE__ */ jsx5(NodeWrapper, { id: node.id, part: "section", as: "section", className: "tb-section", missing: true });
454
+ }
455
+
456
+ // src/shopper-data.ts
457
+ import { useEffect, useState } from "react";
458
+
459
+ // src/data.ts
460
+ import { walkNodes as walkNodes2 } from "@usethrottle/builder-schema";
461
+ function stable(value) {
462
+ if (Array.isArray(value)) return `[${value.map(stable).join(",")}]`;
463
+ if (typeof value === "object" && value !== null) {
464
+ const entries2 = Object.entries(value).filter(([, item]) => item !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
465
+ return `{${entries2.map(([k, v]) => `${JSON.stringify(k)}:${stable(v)}`).join(",")}}`;
466
+ }
467
+ return JSON.stringify(value) ?? "null";
468
+ }
469
+ function bindingKey(binding) {
470
+ return "params" in binding ? `${binding.source}?${stable(binding.params)}` : binding.source;
471
+ }
472
+ var isContextBinding = (binding) => binding.source.startsWith("context.");
473
+ function bindingsOf(node, registry) {
474
+ const def = registry.widget(node.type, node.v);
475
+ const out = {};
476
+ for (const [name, input] of Object.entries(def?.data ?? {})) {
477
+ if (input.default !== void 0) out[name] = input.default;
478
+ }
479
+ return { ...out, ...node.data ?? {} };
480
+ }
481
+ function collectBindings(doc, registry) {
482
+ const found = /* @__PURE__ */ new Map();
483
+ walkNodes2(doc, (node) => {
484
+ if (node.type === "section" || node.type === "inner-section" || node.type === "column" || node.type === "saved-section") {
485
+ return;
486
+ }
487
+ for (const binding of Object.values(bindingsOf(node, registry))) {
488
+ const key = bindingKey(binding);
489
+ if (!found.has(key)) found.set(key, binding);
490
+ }
491
+ });
492
+ return found;
493
+ }
494
+ async function resolveBindings(bindings, registry, ctx, options) {
495
+ const jobs = [];
496
+ for (const [key, binding] of bindings) {
497
+ if (isContextBinding(binding) || !("params" in binding)) continue;
498
+ const descriptor = registry.source(binding.source);
499
+ const resolve = registry.resolver(binding.source);
500
+ if (descriptor === void 0 || resolve === void 0) continue;
501
+ if (options.include === "static" && descriptor.perShopper) continue;
502
+ if (options.include === "shopper" && !descriptor.perShopper) continue;
503
+ jobs.push(
504
+ resolve(binding.params, ctx).then(
505
+ (value) => [key, value],
506
+ (error) => {
507
+ warnOnce(`resolve:${binding.source}`, `Data source ${binding.source} failed (${String(error)}); its widgets render without data`);
508
+ return null;
509
+ }
510
+ )
511
+ );
512
+ }
513
+ const settled = await Promise.all(jobs);
514
+ return Object.fromEntries(settled.filter((entry) => entry !== null));
515
+ }
516
+
517
+ // src/shopper-data.ts
518
+ function useResolvedData(document2, registry, locale, include, context) {
519
+ const [data, setData] = useState({});
520
+ useEffect(() => {
521
+ const controller = new AbortController();
522
+ const bindings = collectBindings(document2, registry);
523
+ if (bindings.size === 0) return void 0;
524
+ void resolveBindings(
525
+ bindings,
526
+ registry,
527
+ { locale, preview: false, context, signal: controller.signal },
528
+ { include }
529
+ ).then((resolved) => {
530
+ if (!controller.signal.aborted && Object.keys(resolved).length > 0) setData(resolved);
531
+ });
532
+ return () => controller.abort();
533
+ }, [document2, registry, locale, include, context]);
534
+ return data;
535
+ }
536
+
537
+ // src/part-view.tsx
538
+ import { jsx as jsx6 } from "react/jsx-runtime";
539
+ var BoundaryBase = Component ?? class {
540
+ };
541
+ var Boundary = class extends BoundaryBase {
542
+ constructor() {
543
+ super(...arguments);
544
+ __publicField(this, "state", { failed: false });
24
545
  }
25
- /** Takes `count` nodes. False, and nothing taken, when that would pass the limit. */
26
- take(count = 1) {
27
- if (this.spent + count > this.limit) return false;
28
- this.spent += count;
29
- return true;
546
+ static getDerivedStateFromError() {
547
+ return { failed: true };
30
548
  }
31
- get used() {
32
- return this.spent;
549
+ componentDidCatch(error, _info) {
550
+ warnOnce(`part:${this.props.label}`, `${this.props.label} failed to render (${String(error)}); rendering nothing for it`);
551
+ try {
552
+ this.props.onError?.(error, { part: this.props.label });
553
+ } catch {
554
+ }
33
555
  }
34
- get exhausted() {
35
- return this.spent >= this.limit;
556
+ componentDidUpdate(previous) {
557
+ const moved = previous.resetKeys.length !== this.props.resetKeys.length || previous.resetKeys.some((key, i) => !Object.is(key, this.props.resetKeys[i]));
558
+ if (moved && this.state.failed) this.setState({ failed: false });
559
+ }
560
+ render() {
561
+ return this.state.failed ? null : this.props.children;
36
562
  }
37
563
  };
38
- var fitsBudget = (ast, limit = MAX_RENDERED_NODES) => templateWeight(ast) <= limit;
564
+ function PartBoundary({
565
+ label,
566
+ resetKey,
567
+ children
568
+ }) {
569
+ const builder = useBuilder();
570
+ return /* @__PURE__ */ jsx6(Boundary, { label, resetKeys: [builder?.site, resetKey], onError: builder?.onError, children });
571
+ }
572
+ function contextData(context) {
573
+ if (typeof context !== "object" || context === null) return {};
574
+ return Object.fromEntries(Object.entries(context).map(([key, value]) => [`context.${key}`, value]));
575
+ }
576
+ function PartView({ part, context }) {
577
+ const builder = useBuilder();
578
+ if (builder === null) return null;
579
+ return /* @__PURE__ */ jsx6(PartBody, { part, context, builder });
580
+ }
581
+ function PartBody({
582
+ part,
583
+ context,
584
+ builder
585
+ }) {
586
+ const expanded = expandSavedSections(part.document, part.savedSections).doc;
587
+ const shopper = useResolvedData(expanded, builder.registry, builder.locale, "shopper", context);
588
+ return /* @__PURE__ */ jsx6(
589
+ BuilderRenderer,
590
+ {
591
+ document: part.document,
592
+ registry: builder.registry,
593
+ data: { ...part.initialData, ...contextData(context), ...shopper },
594
+ locale: builder.locale,
595
+ assets: part.assets,
596
+ mediaOrigin: builder.mediaOrigin,
597
+ resolveLink: builder.resolveLink,
598
+ interactive: builder.interactive,
599
+ scopeCustomCss: builder.customCss !== "",
600
+ savedSections: part.savedSections,
601
+ code: codeRenderOf(builder, part.code)
602
+ }
603
+ );
604
+ }
605
+
606
+ // src/custom/template-widget.tsx
607
+ import { Fragment as Fragment2, jsx as jsx7, jsxs } from "react/jsx-runtime";
608
+ var componentWeights = /* @__PURE__ */ new WeakMap();
609
+ var compiled = /* @__PURE__ */ new WeakMap();
610
+ function compileTemplate(snapshot, registry) {
611
+ let perRegistry = compiled.get(snapshot);
612
+ if (perRegistry === void 0) {
613
+ perRegistry = /* @__PURE__ */ new WeakMap();
614
+ compiled.set(snapshot, perRegistry);
615
+ }
616
+ if (perRegistry.has(registry)) return perRegistry.get(registry) ?? null;
617
+ const result = compile(snapshot, registry);
618
+ perRegistry.set(registry, result);
619
+ return result;
620
+ }
621
+ function compile(snapshot, registry) {
622
+ const label = `${snapshot.type}@${String(snapshot.v)}`;
623
+ const refuse = (why) => {
624
+ warnOnce(`template:${label}`, `${label} was refused (${why}); rendering nothing for it`);
625
+ return null;
626
+ };
627
+ if (snapshot.kind !== "template") return refuse("not a template widget");
628
+ const source = snapshot.template;
629
+ if (typeof source !== "string") return refuse("no template source");
630
+ const parsed2 = parseTemplate(source);
631
+ if (!parsed2.ok) return refuse(`template does not parse: ${parsed2.issues[0]?.message ?? "invalid"}`);
632
+ const data = snapshot.data;
633
+ const issues = validateTemplate(parsed2.ast, {
634
+ settings: snapshot.settings,
635
+ data: typeof data === "object" && data !== null ? data : {},
636
+ sources: registry.sources()
637
+ });
638
+ if (issues.length > 0) return refuse(`template does not validate: ${issues[0]?.message ?? "invalid"}`);
639
+ if (!fitsBudget(parsed2.ast)) return refuse(`it can render more than ${String(MAX_TEMPLATE_WEIGHT2)} nodes`);
640
+ const css = scopedCss(snapshot.css, snapshot.type);
641
+ if (css === null) return refuse("its css does not pass the sanitiser");
642
+ return { ast: parsed2.ast, css, weight: templateWeight2(parsed2.ast) };
643
+ }
644
+ function TemplateBody({ snapshot, registry, props, data, locale, mediaOrigin, budget }) {
645
+ const template = compileTemplate(snapshot, registry);
646
+ if (template === null) return null;
647
+ const env = newEnv({ settings: props, data, locale, mediaOrigin, budget: budget ?? new RenderBudget() });
648
+ return /* @__PURE__ */ jsxs(Fragment2, { children: [
649
+ template.css === "" ? null : /* @__PURE__ */ jsx7(CustomCss, { css: template.css }),
650
+ renderTemplate(template.ast, env)
651
+ ] });
652
+ }
653
+ function TemplateWidget(props) {
654
+ return /* @__PURE__ */ jsx7(PartBoundary, { label: `${props.snapshot.type}@${String(props.snapshot.v)}`, children: /* @__PURE__ */ jsx7(Suspense, { fallback: null, children: /* @__PURE__ */ jsx7(TemplateBody, { ...props }) }) });
655
+ }
656
+
657
+ // src/code/leave.ts
658
+ import { useEffect as useEffect2, useRef } from "react";
659
+
660
+ // src/code/reload.ts
661
+ function reloadHere() {
662
+ window.location.assign(window.location.href);
663
+ }
664
+
665
+ // src/code/routes.ts
666
+ var CODE_ROUTE_DENY = /^(checkout|cart|basket|bag|account|my-?account|sign[-_]?in|sign[-_]?up|log[-_]?in|log[-_]?out|register|orders?|pay|payments?|password|wallet)([;.\s].*)?$|^(confirm|thank|receipt|invoice|quote).*$|^order[-_].*$/i;
667
+ var DEFAULT_CATALOG_ROUTES = [
668
+ "/p/{handle}",
669
+ "/c/{handle}",
670
+ "/collections/{handle}",
671
+ "/tags/{tag}",
672
+ "/search",
673
+ "/shop"
674
+ ];
675
+ function normalizePath(pathname) {
676
+ const bare = pathname.split(/[?#]/, 1)[0] ?? "";
677
+ let decoded2 = bare;
678
+ try {
679
+ for (let i = 0; i < 3; i++) {
680
+ let next;
681
+ try {
682
+ next = decodeURIComponent(decoded2);
683
+ } catch (error) {
684
+ if (i === 0) throw error;
685
+ break;
686
+ }
687
+ if (next === decoded2) break;
688
+ decoded2 = next;
689
+ }
690
+ } catch {
691
+ return null;
692
+ }
693
+ if (decoded2.includes("\0")) return null;
694
+ const flat = decoded2.replace(/\\/g, "/");
695
+ if (!flat.startsWith("/")) return null;
696
+ const out = [];
697
+ for (const segment of flat.split("/")) {
698
+ if (segment === "" || segment === ".") continue;
699
+ if (segment === "..") out.pop();
700
+ else out.push(segment);
701
+ }
702
+ return `/${out.join("/")}`;
703
+ }
704
+ var escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
705
+ var compiled2 = /* @__PURE__ */ new Map();
706
+ var MAX_COMPILED = 64;
707
+ function matcherOf(template) {
708
+ const known = compiled2.get(template);
709
+ if (known !== void 0) return known;
710
+ let regex = null;
711
+ if (template.startsWith("/")) {
712
+ const pattern = template.split(/(\{[A-Za-z][A-Za-z0-9]*\})/).map((part) => /^\{[A-Za-z][A-Za-z0-9]*\}$/.test(part) ? "[^/]+" : escapeRegExp(part)).join("").replace(/\/+$/, "");
713
+ regex = new RegExp(`^${pattern === "" ? "/" : pattern}$`);
714
+ }
715
+ if (compiled2.size >= MAX_COMPILED) compiled2.clear();
716
+ compiled2.set(template, regex);
717
+ return regex;
718
+ }
719
+ var matchesTemplate = (path, template) => matcherOf(template)?.test(path) ?? false;
720
+ function isCodeRoute(pathname, routes) {
721
+ if (pathname === void 0) return false;
722
+ const path = normalizePath(pathname);
723
+ if (path === null) return false;
724
+ if (path.split("/").some((segment) => CODE_ROUTE_DENY.test(segment))) return false;
725
+ if (path === "/") return true;
726
+ return [routes.page, ...routes.catalog ?? DEFAULT_CATALOG_ROUTES].some(
727
+ (template) => matchesTemplate(path, template)
728
+ );
729
+ }
730
+
731
+ // src/code/leave.ts
732
+ var emitted = false;
733
+ function markCodeEmitted() {
734
+ emitted = true;
735
+ }
736
+ function mustLeave(pathname, routes) {
737
+ return emitted && typeof window !== "undefined" && pathname !== void 0 && !isCodeRoute(pathname, routes);
738
+ }
739
+ function useLeaveCodeRoutes(pathname, routes) {
740
+ useEffect2(() => {
741
+ if (mustLeave(pathname, routes)) reloadHere();
742
+ }, [pathname, routes]);
743
+ const latest = useRef(routes);
744
+ latest.current = routes;
745
+ useEffect2(
746
+ () => () => {
747
+ if (mustLeave(window.location.pathname, latest.current)) reloadHere();
748
+ },
749
+ []
750
+ );
751
+ }
752
+
753
+ // src/code/code-widget.tsx
754
+ import { jsx as jsx8, jsxs as jsxs2 } from "react/jsx-runtime";
755
+ var SHA256_HEX = /^[0-9a-f]{64}$/;
756
+ var CUSTOM_TYPE = /^custom\.[a-z][a-z0-9-]{0,63}$/;
757
+ var SCRIPT_ORIGIN = /^https:\/\/[a-z0-9]([a-z0-9.-]*[a-z0-9])?(:[0-9]{1,5})?$/i;
758
+ var SITE_ID = /^[A-Za-z0-9_-]{1,64}$/;
759
+ var MAX_INPUT_CHARS = 2e5;
760
+ var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
761
+ var checked = /* @__PURE__ */ new WeakMap();
762
+ function check(raw, registry) {
763
+ let perRegistry = checked.get(raw);
764
+ if (perRegistry === void 0) {
765
+ perRegistry = /* @__PURE__ */ new WeakMap();
766
+ checked.set(raw, perRegistry);
767
+ }
768
+ const known = perRegistry.get(registry);
769
+ if (known !== void 0) return known;
770
+ const result = verify(raw, registry);
771
+ perRegistry.set(registry, result);
772
+ return result;
773
+ }
774
+ function verify(raw, registry) {
775
+ const snapshot = raw;
776
+ const label = `${String(snapshot.type)}@${String(snapshot.v)}`;
777
+ if (snapshot.disabled === true) return { status: "disabled" };
778
+ const refuse = (why) => {
779
+ warnOnce(`code:${label}`, `Code widget ${label} was refused (${why}); rendering nothing for it`);
780
+ return { status: "invalid" };
781
+ };
782
+ if (snapshot.kind !== "code") return refuse("not a code widget");
783
+ if (typeof snapshot.type !== "string" || !CUSTOM_TYPE.test(snapshot.type)) return refuse("bad type");
784
+ if (snapshot.disabled !== void 0) return refuse("bad disabled flag");
785
+ if ("js" in snapshot) return refuse("it carries a script");
786
+ if (typeof snapshot.jsHash !== "string" || !SHA256_HEX.test(snapshot.jsHash)) return refuse("bad script hash");
787
+ if (typeof snapshot.html !== "string" || snapshot.html.length > LIMITS.codeHtmlBytes) return refuse("bad html");
788
+ if (typeof snapshot.css !== "string" || snapshot.css.length > LIMITS.codeCssBytes) return refuse("bad css");
789
+ const template = { ...snapshot, kind: "template", template: snapshot.html };
790
+ if (compileTemplate(template, registry) === null) return refuse("its markup or css does not validate");
791
+ return { status: "ok", snapshot: raw, template };
792
+ }
793
+ function codeScriptUrl(runtime, jsHash) {
794
+ if (!isRecord(runtime) || runtime.enabled !== true) return null;
795
+ const { scriptOrigin, codeSiteId } = runtime;
796
+ if (typeof scriptOrigin !== "string" || !SCRIPT_ORIGIN.test(scriptOrigin)) return null;
797
+ if (typeof codeSiteId !== "string" || !SITE_ID.test(codeSiteId)) return null;
798
+ if (!SHA256_HEX.test(jsHash)) return null;
799
+ return `${scriptOrigin}/v1/code/${codeSiteId}/${jsHash}.js`;
800
+ }
801
+ function jsonForScript(value) {
802
+ return JSON.stringify(value).replace(/[<>&\u2028\u2029]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
803
+ }
804
+ var BADGE = {
805
+ display: "inline-block",
806
+ margin: 4,
807
+ padding: "2px 8px",
808
+ borderRadius: 4,
809
+ font: "600 11px/1.5 system-ui, sans-serif",
810
+ letterSpacing: "0.02em",
811
+ background: "#1f2937",
812
+ color: "#fff"
813
+ };
814
+ function runs(props, jsHash) {
815
+ const { code, edit, interactive } = props;
816
+ if (edit !== void 0 || interactive === false || code === void 0 || code.preview === true) return null;
817
+ if (!isCodeRoute(code.pathname, code.routes)) return null;
818
+ return codeScriptUrl(code.runtime, jsHash);
819
+ }
820
+ function CodeWidget(props) {
821
+ const { node, snapshot, registry, edit, anchor, copyAnchor, entrance } = props;
822
+ const result = check(snapshot, registry);
823
+ if (result.status !== "ok") {
824
+ return result.status === "disabled" && edit !== void 0 ? /* @__PURE__ */ jsx8(NodeWrapper, { id: node.id, part: "widget", type: node.type, className: "tb-w", edit, children: /* @__PURE__ */ jsx8("div", { className: "tb-missing", children: "This code widget is disabled" }) }) : null;
825
+ }
826
+ const template = compileTemplate(result.template, registry);
827
+ const src = runs(props, result.snapshot.jsHash);
828
+ if (src !== null) markCodeEmitted();
829
+ const env = newEnv({ settings: props.props, data: props.data, locale: props.locale, mediaOrigin: props.mediaOrigin, budget: new RenderBudget() });
830
+ const label = `${node.type}@${String(node.v)}`;
831
+ return /* @__PURE__ */ jsxs2(
832
+ NodeWrapper,
833
+ {
834
+ id: node.id,
835
+ part: "widget",
836
+ type: node.type,
837
+ custom: true,
838
+ edit,
839
+ className: "tb-w",
840
+ anchor,
841
+ copyAnchor,
842
+ entrance,
843
+ attributes: src === null ? { "data-b-code-inert": "" } : { "data-b-code": result.snapshot.jsHash },
844
+ children: [
845
+ /* @__PURE__ */ jsx8(PartBoundary, { label, children: /* @__PURE__ */ jsxs2(Suspense2, { fallback: null, children: [
846
+ template.css === "" ? null : /* @__PURE__ */ jsx8(CustomCss, { css: template.css }),
847
+ renderTemplate(template.ast, env)
848
+ ] }) }),
849
+ src === null && (edit !== void 0 || props.code?.preview === true) ? /* @__PURE__ */ jsx8("div", { "data-b-code-badge": "", style: BADGE, children: "Runs on your store" }) : null,
850
+ src === null ? null : /* @__PURE__ */ jsx8(CodeInput, { props: props.props, data: props.data, label }),
851
+ src === null ? null : /* @__PURE__ */ jsx8("script", { async: true, src })
852
+ ]
853
+ }
854
+ );
855
+ }
856
+ function CodeInput({ props, data, label }) {
857
+ let json = "";
858
+ try {
859
+ json = jsonForScript({ props, data });
860
+ if (json.length > MAX_INPUT_CHARS) {
861
+ warnOnce(`code-input:${label}`, `The data of ${label} is too large for its code input; it gets its props only`);
862
+ json = jsonForScript({ props, data: {} });
863
+ }
864
+ } catch {
865
+ warnOnce(`code-input:${label}`, `The input of ${label} cannot be written as JSON; it gets none`);
866
+ json = jsonForScript({ props: {}, data: {} });
867
+ }
868
+ return /* @__PURE__ */ jsx8("script", { type: "application/json", "data-b-code-input": "", children: json });
869
+ }
39
870
 
40
871
  // src/css-compiler.ts
41
872
  import {
@@ -43,26 +874,15 @@ import {
43
874
  resolveColumnProps,
44
875
  resolveColumnWidths,
45
876
  resolveResponsive,
46
- safeUrl,
877
+ safeUrl as safeUrl2,
47
878
  validateSettingValue,
48
879
  wrapColumnRows
49
880
  } from "@usethrottle/builder-schema";
50
-
51
- // src/warn.ts
52
- var seen = /* @__PURE__ */ new Set();
53
- function warnOnce(key, message) {
54
- if (seen.has(key)) return;
55
- seen.add(key);
56
- console.warn(`[throttle-builder] ${message}`);
57
- }
58
- var isDevelopment = () => typeof process === "undefined" || process.env?.NODE_ENV !== "production";
59
-
60
- // src/css-compiler.ts
61
881
  var TABLET_QUERY = "(max-width:1024px)";
62
882
  var PHONE_QUERY = "(max-width:767px)";
63
883
  var SAFE_VALUE = /^[A-Za-z0-9#%.,()\-+*/_: ]{1,200}$/;
64
884
  var URL_QUOTE_SAFE = /^[^\s"'\\()<>{};]+$/;
65
- var ID_RE = /^[a-z0-9]{8,24}$/;
885
+ var ID_RE = /^[a-z0-9]{8,24}(-[a-z0-9]{8,24})?$/;
66
886
  var PROPERTY_RE = /^--(?:b|w|tb)-[A-Za-z][A-Za-z0-9-]{0,39}$/;
67
887
  var COLOR_TOKEN = /* @__PURE__ */ new Set([
68
888
  "primary",
@@ -163,7 +983,7 @@ function backgroundDecls(out, bg, assets, mediaOrigin) {
163
983
  if (bg.position !== void 0 && BG_POSITION.has(bg.position)) put(out, "--tb-bgpos", bg.position);
164
984
  if (bg.size !== void 0 && BG_SIZE.has(bg.size)) put(out, "--tb-bgsize", bg.size);
165
985
  const asset = bg.image === void 0 || assets === void 0 || !Object.hasOwn(assets, bg.image) ? void 0 : assets[bg.image];
166
- if (asset !== void 0 && safeUrl(asset.url, "src", { mediaOrigin }) !== null && URL_QUOTE_SAFE.test(asset.url)) {
986
+ if (asset !== void 0 && safeUrl2(asset.url, "src", { mediaOrigin }) !== null && URL_QUOTE_SAFE.test(asset.url)) {
167
987
  out.set("--tb-bgimg", `url("${asset.url}")`);
168
988
  }
169
989
  }
@@ -270,110 +1090,354 @@ function compileResponsiveCss(doc, registry, assets = doc.assets, mediaOrigin =
270
1090
  return base + (tablet === "" ? "" : `@media ${TABLET_QUERY}{${tablet}}`) + (phone === "" ? "" : `@media ${PHONE_QUERY}{${phone}}`);
271
1091
  }
272
1092
 
273
- // src/data.ts
274
- import { walkNodes } from "@usethrottle/builder-schema";
275
- function stable(value) {
276
- if (Array.isArray(value)) return `[${value.map(stable).join(",")}]`;
277
- if (typeof value === "object" && value !== null) {
278
- const entries2 = Object.entries(value).filter(([, item]) => item !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
279
- return `{${entries2.map(([k, v]) => `${JSON.stringify(k)}:${stable(v)}`).join(",")}}`;
280
- }
281
- return JSON.stringify(value) ?? "null";
282
- }
283
- function bindingKey(binding) {
284
- return "params" in binding ? `${binding.source}?${stable(binding.params)}` : binding.source;
285
- }
286
- var isContextBinding = (binding) => binding.source.startsWith("context.");
287
- function bindingsOf(node, registry) {
288
- const def = registry.widget(node.type, node.v);
289
- const out = {};
290
- for (const [name, input] of Object.entries(def?.data ?? {})) {
291
- if (input.default !== void 0) out[name] = input.default;
292
- }
293
- return { ...out, ...node.data ?? {} };
1093
+ // src/interactions/accordion.tsx
1094
+ import { jsx as jsx9, jsxs as jsxs3 } from "react/jsx-runtime";
1095
+ function Accordion({
1096
+ id,
1097
+ panels,
1098
+ multiple,
1099
+ openFirst
1100
+ }) {
1101
+ return /* @__PURE__ */ jsx9("div", { className: "tb-accordion", children: panels.map((panel, i) => /* @__PURE__ */ jsxs3(
1102
+ "details",
1103
+ {
1104
+ className: "tb-acc-item",
1105
+ ...multiple ? {} : { name: `${id}-acc` },
1106
+ ...openFirst && i === 0 ? { open: true } : {},
1107
+ children: [
1108
+ /* @__PURE__ */ jsx9("summary", { className: "tb-acc-sum", children: panel.title }),
1109
+ /* @__PURE__ */ jsx9("div", { className: "tb-acc-body", children: panel.node })
1110
+ ]
1111
+ },
1112
+ panel.key
1113
+ )) });
294
1114
  }
295
- function collectBindings(doc, registry) {
296
- const found = /* @__PURE__ */ new Map();
297
- walkNodes(doc, (node) => {
298
- if (node.type === "section" || node.type === "inner-section" || node.type === "column" || node.type === "saved-section") {
299
- return;
300
- }
301
- for (const binding of Object.values(bindingsOf(node, registry))) {
302
- const key = bindingKey(binding);
303
- if (!found.has(key)) found.set(key, binding);
1115
+
1116
+ // src/interactions/carousel.tsx
1117
+ import { jsx as jsx10, jsxs as jsxs4 } from "react/jsx-runtime";
1118
+ function Carousel({
1119
+ panels,
1120
+ autoplayMs,
1121
+ loop
1122
+ }) {
1123
+ return /* @__PURE__ */ jsxs4(
1124
+ "div",
1125
+ {
1126
+ className: "tb-car",
1127
+ role: "region",
1128
+ "aria-roledescription": "carousel",
1129
+ "aria-label": "Carousel",
1130
+ "data-b-car": "",
1131
+ ...loop ? { "data-b-loop": "" } : {},
1132
+ ...autoplayMs === null ? {} : { "data-b-autoplay": String(autoplayMs) },
1133
+ children: [
1134
+ /* @__PURE__ */ jsx10("div", { className: "tb-car-track", tabIndex: 0, children: panels.map((panel, i) => /* @__PURE__ */ jsx10(
1135
+ "div",
1136
+ {
1137
+ className: "tb-slide",
1138
+ role: "group",
1139
+ "aria-roledescription": "slide",
1140
+ "aria-label": panel.title === "" ? `${String(i + 1)} of ${String(panels.length)}` : panel.title,
1141
+ children: panel.node
1142
+ },
1143
+ panel.key
1144
+ )) }),
1145
+ /* @__PURE__ */ jsxs4("div", { className: "tb-car-ctrl", children: [
1146
+ /* @__PURE__ */ jsx10("button", { type: "button", className: "tb-car-btn", "data-b-act": "prev", "aria-label": "Previous slide", children: "\u2039" }),
1147
+ autoplayMs === null ? null : /* @__PURE__ */ jsx10("button", { type: "button", className: "tb-car-btn tb-car-pause", "data-b-act": "pause", hidden: true, children: "Pause" }),
1148
+ /* @__PURE__ */ jsx10("button", { type: "button", className: "tb-car-btn", "data-b-act": "next", "aria-label": "Next slide", children: "\u203A" })
1149
+ ] })
1150
+ ]
304
1151
  }
1152
+ );
1153
+ }
1154
+
1155
+ // src/interactions/entrance.tsx
1156
+ import { useEffect as useEffect3 } from "react";
1157
+ import { ENTRANCES } from "@usethrottle/builder-schema";
1158
+
1159
+ // src/interactions/styles.ts
1160
+ var INTERACTIONS_CSS = `@layer throttle{
1161
+ .tb-panel>.tb-col,.tb-acc-body>.tb-col,.tb-slide>.tb-col{inline-size:100%}
1162
+ .tb-tablist{display:none;flex-wrap:wrap;gap:var(--tb-space-xs);border-block-end:1px solid var(--tb-color-border,currentColor);margin-block-end:var(--tb-space-m)}
1163
+ html[data-b-js] .tb-tablist{display:flex}
1164
+ html[data-b-js] .tb-panel-title{display:none}
1165
+ .tb-panel-title{margin:0 0 var(--tb-space-s);font-weight:600}
1166
+ .tb-panel[hidden]{display:none}
1167
+ .tb-tab{appearance:none;cursor:pointer;font:inherit;color:inherit;background:none;border:0;border-block-end:2px solid transparent;padding:var(--tb-space-s) var(--tb-space-m)}
1168
+ .tb-tab[aria-selected=true]{border-block-end-color:var(--tb-color-primary,currentColor);font-weight:600}
1169
+ .tb-tab:focus-visible,.tb-car-btn:focus-visible,.tb-acc-sum:focus-visible,.tb-toggle-sum:focus-visible,.tb-car-track:focus-visible{outline:2px solid var(--tb-color-primary,currentColor);outline-offset:2px}
1170
+ .tb-acc-item{border-block-end:1px solid var(--tb-color-border,currentColor)}
1171
+ .tb-acc-sum,.tb-toggle-sum{cursor:pointer;padding:var(--tb-space-s) 0;font-weight:600}
1172
+ .tb-acc-body{padding-block-end:var(--tb-space-m)}
1173
+ .tb-toggle-open,.tb-toggle[open] .tb-toggle-closed{display:none}
1174
+ .tb-toggle[open] .tb-toggle-open{display:inline}
1175
+ .tb-toggle .tb-row{margin-block-start:var(--tb-space-m)}
1176
+ .tb-car{position:relative}
1177
+ .tb-car-track{display:flex;overflow-x:auto;scroll-snap-type:x mandatory;scrollbar-width:thin}
1178
+ .tb-slide{flex:0 0 100%;min-inline-size:0;scroll-snap-align:start}
1179
+ .tb-car-ctrl{display:none;justify-content:center;gap:var(--tb-space-s);margin-block-start:var(--tb-space-s)}
1180
+ html[data-b-js] .tb-car-ctrl{display:flex}
1181
+ .tb-car-btn{appearance:none;cursor:pointer;font:inherit;color:inherit;background:var(--tb-color-surface,transparent);border:1px solid var(--tb-color-border-control,currentColor);border-radius:999px;min-inline-size:2.5rem;min-block-size:2.5rem;padding:0 var(--tb-space-m)}
1182
+ .tb-car-btn[hidden]{display:none}
1183
+ @media (prefers-reduced-motion:no-preference){
1184
+ html[data-b-js] [data-b-entrance]{transition:opacity .6s ease var(--tb-ed,0ms),transform .6s ease var(--tb-ed,0ms)}
1185
+ html[data-b-js] [data-b-entrance]:not([data-b-in]){opacity:0}
1186
+ html[data-b-js] [data-b-entrance=slide-up]:not([data-b-in]){transform:translateY(1.5rem)}
1187
+ html[data-b-js] [data-b-entrance=slide-left]:not([data-b-in]){transform:translateX(-1.5rem)}
1188
+ html[data-b-js] [data-b-entrance=zoom]:not([data-b-in]){transform:scale(.94)}
1189
+ }
1190
+ @media (prefers-reduced-motion:reduce){.tb-car-track{scroll-behavior:auto}}
1191
+ }`;
1192
+
1193
+ // src/interactions/runtime.ts
1194
+ var UNITS = [86400, 3600, 60, 1];
1195
+ var KEYS = ["d", "h", "m", "s"];
1196
+ var NAMES = ["days", "hours", "minutes", "seconds"];
1197
+ var holds = 0;
1198
+ var stop;
1199
+ var seen2 = /* @__PURE__ */ new WeakSet();
1200
+ var autoplay = /* @__PURE__ */ new Map();
1201
+ var all = (selector) => Array.from(document.querySelectorAll(selector));
1202
+ var reduced = () => window.matchMedia?.("(prefers-reduced-motion: reduce)").matches === true;
1203
+ function selectTab(list, index, focus = false) {
1204
+ const tabs = Array.from(list.querySelectorAll("[role=tab]"));
1205
+ tabs.forEach((tab, i) => {
1206
+ const on = i === index;
1207
+ tab.setAttribute("aria-selected", String(on));
1208
+ tab.tabIndex = on ? 0 : -1;
1209
+ const panel = document.getElementById(tab.getAttribute("aria-controls") ?? "");
1210
+ if (panel !== null) panel.hidden = !on;
1211
+ if (on && focus) tab.focus();
305
1212
  });
306
- return found;
307
1213
  }
308
- async function resolveBindings(bindings, registry, ctx, options) {
309
- const jobs = [];
310
- for (const [key, binding] of bindings) {
311
- if (isContextBinding(binding) || !("params" in binding)) continue;
312
- const descriptor = registry.source(binding.source);
313
- const resolve = registry.resolver(binding.source);
314
- if (descriptor === void 0 || resolve === void 0) continue;
315
- if (options.include === "static" && descriptor.perShopper) continue;
316
- if (options.include === "shopper" && !descriptor.perShopper) continue;
317
- jobs.push(
318
- resolve(binding.params, ctx).then(
319
- (value) => [key, value],
320
- (error) => {
321
- warnOnce(`resolve:${binding.source}`, `Data source ${binding.source} failed (${String(error)}); its widgets render without data`);
322
- return null;
323
- }
324
- )
1214
+ function slideTo(root, step2) {
1215
+ const track = root.querySelector(".tb-car-track");
1216
+ if (track === null || track.clientWidth === 0) return;
1217
+ const count = track.children.length;
1218
+ const at = Math.round(track.scrollLeft / track.clientWidth) + step2;
1219
+ const loop = root.hasAttribute("data-b-loop");
1220
+ const to = at >= count ? loop ? 0 : count - 1 : at < 0 ? loop ? count - 1 : 0 : at;
1221
+ track.scrollTo?.({ left: to * track.clientWidth, behavior: reduced() ? "auto" : "smooth" });
1222
+ }
1223
+ var carousels = /* @__PURE__ */ new WeakMap();
1224
+ function setupCarousel(root) {
1225
+ const every = Number(root.getAttribute("data-b-autoplay"));
1226
+ const pause = root.querySelector("[data-b-act=pause]");
1227
+ if (!(every > 0) || reduced() || pause === null) return;
1228
+ pause.hidden = false;
1229
+ let state = carousels.get(root);
1230
+ if (state === void 0) {
1231
+ const own = state = { hold: 0 };
1232
+ carousels.set(root, own);
1233
+ const set = (bit, on) => void (own.hold = on ? own.hold | bit : own.hold & ~bit);
1234
+ root.addEventListener("mouseenter", () => set(1, true));
1235
+ root.addEventListener("mouseleave", () => set(1, false));
1236
+ root.addEventListener("focusin", () => set(2, true));
1237
+ root.addEventListener("focusout", () => set(2, false));
1238
+ pause.addEventListener("click", () => {
1239
+ set(4, (own.hold & 4) === 0);
1240
+ pause.textContent = own.hold & 4 ? "Play" : "Pause";
1241
+ });
1242
+ }
1243
+ const shared = state;
1244
+ autoplay.set(root, window.setInterval(() => shared.hold === 0 && slideTo(root, 1), every));
1245
+ }
1246
+ function remaining(el) {
1247
+ return Math.max(0, Math.floor((Number(el.getAttribute("data-b-cd")) - Date.now()) / 1e3));
1248
+ }
1249
+ function tick(el, minute) {
1250
+ let left = remaining(el);
1251
+ const parts = [];
1252
+ KEYS.forEach((key, i) => {
1253
+ const out = el.querySelector(`[data-u=${key}]`);
1254
+ if (out === null) return;
1255
+ const value = Math.floor(left / UNITS[i]);
1256
+ left -= value * UNITS[i];
1257
+ out.textContent = String(value).padStart(2, "0");
1258
+ parts.push(`${String(value)} ${out.nextElementSibling?.textContent || NAMES[i]}`);
1259
+ });
1260
+ const live = el.querySelector("[data-b-live]");
1261
+ if (live !== null && minute) live.textContent = parts.join(", ");
1262
+ if (remaining(el) === 0) {
1263
+ el.setAttribute("data-b-ended", "");
1264
+ const text = el.querySelector(".tb-b-cd-ended");
1265
+ if (text !== null) text.hidden = false;
1266
+ if (el.getAttribute("data-b-expired") === "hide") el.hidden = true;
1267
+ }
1268
+ }
1269
+ function scan() {
1270
+ autoplay.forEach((id, root) => {
1271
+ if (!root.isConnected) {
1272
+ window.clearInterval(id);
1273
+ autoplay.delete(root);
1274
+ }
1275
+ });
1276
+ document.documentElement.setAttribute("data-b-js", "");
1277
+ const fresh = (selector) => all(selector).filter((el) => !seen2.has(el) && seen2.add(el));
1278
+ fresh("[data-b-tabs]").forEach((list) => selectTab(list, 0));
1279
+ fresh("[data-b-car]").forEach((root) => setupCarousel(root));
1280
+ const counts = fresh("[data-b-cd]");
1281
+ counts.forEach((el) => tick(el, true));
1282
+ const targets = fresh("[data-b-entrance]");
1283
+ if (targets.length === 0) return;
1284
+ if (typeof IntersectionObserver === "undefined") targets.forEach((el) => el.setAttribute("data-b-in", ""));
1285
+ else {
1286
+ const watch = new IntersectionObserver(
1287
+ (entries2) => entries2.forEach((entry) => {
1288
+ if (!entry.isIntersecting) return;
1289
+ entry.target.setAttribute("data-b-in", "");
1290
+ watch.unobserve(entry.target);
1291
+ })
325
1292
  );
1293
+ targets.forEach((el) => watch.observe(el));
326
1294
  }
327
- const settled = await Promise.all(jobs);
328
- return Object.fromEntries(settled.filter((entry) => entry !== null));
329
1295
  }
330
-
331
- // src/node-wrapper.tsx
332
- import { ANCHOR_RE } from "@usethrottle/builder-schema";
333
- import { jsx } from "react/jsx-runtime";
334
- var CUSTOM_WIDGET_CONTAINMENT = {
335
- contain: "layout paint",
336
- isolation: "isolate",
337
- overflow: "clip"
338
- };
339
- var PART_NAME = {
340
- section: "builder-section",
341
- column: "builder-column",
342
- widget: "builder-widget"
1296
+ var shown = (el) => el !== null && el.getClientRects().length > 0;
1297
+ function goAnchor(name) {
1298
+ if (name === "" || shown(document.getElementById(name))) return false;
1299
+ const copy = all("[data-b-anchor]").find((el) => el.getAttribute("data-b-anchor") === name && shown(el));
1300
+ copy?.scrollIntoView();
1301
+ return copy !== void 0;
1302
+ }
1303
+ var decoded = (hash) => {
1304
+ try {
1305
+ return decodeURIComponent(hash.slice(1));
1306
+ } catch {
1307
+ return "";
1308
+ }
343
1309
  };
344
- function NodeWrapper(props) {
345
- const { id, part, type, className, anchor, custom, missing, edit, children } = props;
346
- const Tag = props.as ?? "div";
347
- const handlers = edit === void 0 ? {} : {
348
- onClickCapture: (event) => {
349
- const target = event.target;
350
- if (target?.closest?.("a[href]") != null) event.preventDefault();
351
- },
352
- onClick: (event) => {
353
- event.stopPropagation();
354
- edit.onSelect(id);
355
- },
356
- onMouseOver: (event) => {
357
- event.stopPropagation();
358
- edit.onHover(id);
359
- },
360
- onMouseLeave: () => edit.onHover(null)
1310
+ var onHash = () => void goAnchor(decoded(location.hash));
1311
+ function onClick(event) {
1312
+ const target = event.target;
1313
+ const href = target?.closest('a[href^="#"]')?.getAttribute("href");
1314
+ if (href && !event.defaultPrevented && !event.button && !(event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) && goAnchor(decoded(href))) {
1315
+ event.preventDefault();
1316
+ history.pushState(null, "", href);
1317
+ }
1318
+ const tab = target?.closest("[role=tab]");
1319
+ const list = tab?.closest("[data-b-tabs]");
1320
+ if (tab && list) return selectTab(list, Array.from(list.querySelectorAll("[role=tab]")).indexOf(tab));
1321
+ const button = target?.closest("[data-b-act]");
1322
+ const act = button?.getAttribute("data-b-act");
1323
+ const root = button?.closest("[data-b-car]");
1324
+ if (root && (act === "prev" || act === "next")) slideTo(root, act === "next" ? 1 : -1);
1325
+ }
1326
+ function onKey(event) {
1327
+ const tab = event.target?.closest("[role=tab]");
1328
+ const list = tab?.closest("[data-b-tabs]");
1329
+ if (!tab || !list) return;
1330
+ const count = list.querySelectorAll("[role=tab]").length;
1331
+ const at = Array.from(list.querySelectorAll("[role=tab]")).indexOf(tab);
1332
+ const to = event.key === "ArrowRight" ? (at + 1) % count : event.key === "ArrowLeft" ? (at + count - 1) % count : event.key === "Home" ? 0 : event.key === "End" ? count - 1 : -1;
1333
+ if (to < 0) return;
1334
+ event.preventDefault();
1335
+ selectTab(list, to, true);
1336
+ }
1337
+ function startRuntime() {
1338
+ if (typeof document === "undefined") return () => void 0;
1339
+ const first = holds++ === 0;
1340
+ if (first) {
1341
+ document.addEventListener("click", onClick);
1342
+ document.addEventListener("keydown", onKey);
1343
+ window.addEventListener("hashchange", onHash);
1344
+ let beat = 0;
1345
+ const clock = window.setInterval(() => {
1346
+ const minute = ++beat % 60 === 0;
1347
+ all("[data-b-cd]:not([data-b-ended])").forEach((el) => tick(el, minute));
1348
+ }, 1e3);
1349
+ let queued = false;
1350
+ const watcher = new MutationObserver(() => {
1351
+ if (queued) return;
1352
+ queued = true;
1353
+ void Promise.resolve().then(() => {
1354
+ queued = false;
1355
+ if (holds > 0) scan();
1356
+ });
1357
+ });
1358
+ watcher.observe(document.documentElement, { childList: true, subtree: true });
1359
+ stop = () => {
1360
+ document.removeEventListener("click", onClick);
1361
+ document.removeEventListener("keydown", onKey);
1362
+ window.removeEventListener("hashchange", onHash);
1363
+ window.clearInterval(clock);
1364
+ watcher.disconnect();
1365
+ autoplay.forEach((id) => window.clearInterval(id));
1366
+ autoplay.clear();
1367
+ seen2 = /* @__PURE__ */ new WeakSet();
1368
+ };
1369
+ }
1370
+ scan();
1371
+ if (first) onHash();
1372
+ return () => {
1373
+ if (--holds === 0) stop?.();
361
1374
  };
362
- return /* @__PURE__ */ jsx(
363
- Tag,
364
- {
365
- className,
366
- "data-b-id": id,
367
- "data-throttle-part": PART_NAME[part],
368
- ...type === void 0 ? {} : { "data-b-type": type },
369
- ...custom === true && type !== void 0 ? { "data-b-w": type } : {},
370
- ...missing === true ? { "data-b-missing": "" } : {},
371
- ...typeof anchor === "string" && ANCHOR_RE.test(anchor) ? { id: anchor } : {},
372
- ...custom === true ? { style: CUSTOM_WIDGET_CONTAINMENT } : {},
373
- ...handlers,
374
- children
375
- }
376
- );
1375
+ }
1376
+
1377
+ // src/interactions/entrance.tsx
1378
+ import { jsx as jsx11 } from "react/jsx-runtime";
1379
+ function entranceOf(entrance, delayMs, interactive) {
1380
+ if (!interactive || typeof entrance !== "string" || entrance === "none") return void 0;
1381
+ if (!ENTRANCES.includes(entrance)) return void 0;
1382
+ const delay = typeof delayMs === "number" && Number.isFinite(delayMs) ? Math.min(2e3, Math.max(0, Math.round(delayMs))) : 0;
1383
+ return { name: entrance, delayMs: delay };
1384
+ }
1385
+ function InteractionRuntime() {
1386
+ useEffect3(() => startRuntime(), []);
1387
+ return /* @__PURE__ */ jsx11("style", { href: "tb-interactions", precedence: "throttle", children: INTERACTIONS_CSS });
1388
+ }
1389
+
1390
+ // src/interactions/tabs.tsx
1391
+ import { jsx as jsx12, jsxs as jsxs5 } from "react/jsx-runtime";
1392
+ function Tabs({ id, panels }) {
1393
+ return /* @__PURE__ */ jsxs5("div", { className: "tb-tabs", children: [
1394
+ /* @__PURE__ */ jsx12("div", { role: "tablist", className: "tb-tablist", "data-b-tabs": "", children: panels.map((panel, i) => /* @__PURE__ */ jsx12(
1395
+ "button",
1396
+ {
1397
+ type: "button",
1398
+ role: "tab",
1399
+ className: "tb-tab",
1400
+ id: `${id}-t${String(i)}`,
1401
+ "aria-controls": `${id}-p${String(i)}`,
1402
+ "aria-selected": i === 0,
1403
+ tabIndex: i === 0 ? 0 : -1,
1404
+ children: panel.title
1405
+ },
1406
+ panel.key
1407
+ )) }),
1408
+ panels.map((panel, i) => /* @__PURE__ */ jsxs5(
1409
+ "div",
1410
+ {
1411
+ role: "tabpanel",
1412
+ className: "tb-panel",
1413
+ id: `${id}-p${String(i)}`,
1414
+ "aria-labelledby": `${id}-t${String(i)}`,
1415
+ tabIndex: 0,
1416
+ children: [
1417
+ /* @__PURE__ */ jsx12("p", { className: "tb-panel-title", children: panel.title }),
1418
+ panel.node
1419
+ ]
1420
+ },
1421
+ panel.key
1422
+ ))
1423
+ ] });
1424
+ }
1425
+
1426
+ // src/interactions/toggle.tsx
1427
+ import { jsx as jsx13, jsxs as jsxs6 } from "react/jsx-runtime";
1428
+ function Toggle({
1429
+ labelOpen,
1430
+ labelClosed,
1431
+ startOpen,
1432
+ children
1433
+ }) {
1434
+ return /* @__PURE__ */ jsxs6("details", { className: "tb-toggle", ...startOpen ? { open: true } : {}, children: [
1435
+ /* @__PURE__ */ jsxs6("summary", { className: "tb-toggle-sum", children: [
1436
+ /* @__PURE__ */ jsx13("span", { className: "tb-toggle-closed", children: labelClosed }),
1437
+ /* @__PURE__ */ jsx13("span", { className: "tb-toggle-open", children: labelOpen })
1438
+ ] }),
1439
+ /* @__PURE__ */ jsx13("div", { className: "tb-row", children })
1440
+ ] });
377
1441
  }
378
1442
 
379
1443
  // src/styles.ts
@@ -398,7 +1462,7 @@ var BASE_CSS = `@layer throttle{
398
1462
  }`;
399
1463
 
400
1464
  // src/renderer.tsx
401
- import { jsx as jsx2, jsxs } from "react/jsx-runtime";
1465
+ import { jsx as jsx14, jsxs as jsxs7 } from "react/jsx-runtime";
402
1466
  var DEVICES = ["desktop", "tablet", "phone"];
403
1467
  var COMMON_BY_KEY2 = new Map(COMMON_WIDGET_SETTINGS2.map((f) => [f.key, f]));
404
1468
  var withCustomCache = /* @__PURE__ */ new WeakMap();
@@ -415,7 +1479,7 @@ function registryFor(doc, base) {
415
1479
  try {
416
1480
  registry = base.withCustom(
417
1481
  Object.values(snapshots).filter(
418
- (snapshot) => snapshot.kind !== "code"
1482
+ (snapshot) => snapshot.kind !== "code" || codeWidgetSnapshotSchema.safeParse(snapshot).success
419
1483
  )
420
1484
  );
421
1485
  } catch (error) {
@@ -426,7 +1490,7 @@ function registryFor(doc, base) {
426
1490
  }
427
1491
  return registry;
428
1492
  }
429
- var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1493
+ var isRecord2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
430
1494
  function pickLocale(value, locale) {
431
1495
  const lang = locale.split("-")[0] ?? locale;
432
1496
  for (const key of [locale, lang, "en"]) {
@@ -437,25 +1501,25 @@ function pickLocale(value, locale) {
437
1501
  return "";
438
1502
  }
439
1503
  function onOrigin(asset, mediaOrigin) {
440
- if (safeUrl2(asset.url, "src", { mediaOrigin }) === null) return null;
441
- return { ...asset, variants: asset.variants.filter((v) => safeUrl2(v.url, "src", { mediaOrigin }) !== null) };
1504
+ if (safeUrl3(asset.url, "src", { mediaOrigin }) === null) return null;
1505
+ return { ...asset, variants: asset.variants.filter((v) => safeUrl3(v.url, "src", { mediaOrigin }) !== null) };
442
1506
  }
443
1507
  function prepare(field, value, ctx) {
444
1508
  if (field === void 0 || value === null) return value;
445
- if (field.translatable === true && isRecord(value)) return pickLocale(value, ctx.locale);
1509
+ if (field.translatable === true && isRecord2(value)) return pickLocale(value, ctx.locale);
446
1510
  if (field.control === "image" && typeof value === "string") {
447
1511
  const asset = Object.hasOwn(ctx.assets, value) ? ctx.assets[value] : void 0;
448
1512
  return asset === void 0 ? null : onOrigin(asset, ctx.mediaOrigin);
449
1513
  }
450
- if (field.control === "link" && isRecord(value) && typeof value.kind === "string") {
1514
+ if (field.control === "link" && isRecord2(value) && typeof value.kind === "string") {
451
1515
  const target = value;
452
1516
  const raw = ctx.resolveLink?.(target) ?? (target.kind === "url" ? target.href : null);
453
- return { ...value, href: safeUrl2(raw, "href", { mediaOrigin: ctx.mediaOrigin }) };
1517
+ return { ...value, href: safeUrl3(raw, "href", { mediaOrigin: ctx.mediaOrigin }) };
454
1518
  }
455
1519
  return value;
456
1520
  }
457
1521
  function storedLinkPart(value) {
458
- if (!isRecord(value) || value.kind !== "page") return value;
1522
+ if (!isRecord2(value) || value.kind !== "page") return value;
459
1523
  const { slug: _slug, href: _href, ...stored } = value;
460
1524
  void _slug;
461
1525
  void _href;
@@ -469,8 +1533,8 @@ function settingsAt(node, fields, device, ctx) {
469
1533
  for (const [key, value] of Object.entries(resolved)) {
470
1534
  const field = fields.get(key);
471
1535
  const freeText = field?.control === "text" || field?.control === "richtext";
472
- const checked = field?.control === "link" ? storedLinkPart(value) : value;
473
- const usable = field === void 0 || (freeText ? value !== null : validateSettingValue2(field, checked) === null) ? value : field.default;
1536
+ const checked2 = field?.control === "link" ? storedLinkPart(value) : value;
1537
+ const usable = field === void 0 || (freeText ? value !== null : validateSettingValue2(field, checked2) === null) ? value : field.default;
474
1538
  out[key] = prepare(field, usable, ctx);
475
1539
  }
476
1540
  return out;
@@ -494,29 +1558,63 @@ function hiddenEverywhere(props, responsive) {
494
1558
  );
495
1559
  }
496
1560
  var variantClass = (variant) => `tb-v ${variant.devices.map((d) => `tb-only-${d}`).join(" ")}`;
1561
+ function renderCodeWidget(node, snapshot, ctx, registry) {
1562
+ if (ctx.edit === void 0 && hiddenEverywhere(node.props, node.responsive)) return null;
1563
+ const def = registry.widget(node.type, node.v);
1564
+ const fields = new Map([...COMMON_BY_KEY2, ...(def?.settings ?? []).map((f) => [f.key, f])]);
1565
+ const data = {};
1566
+ for (const [name, binding] of Object.entries(bindingsOf(node, registry))) {
1567
+ const key = bindingKey(binding);
1568
+ const value = Object.hasOwn(ctx.data, key) ? ctx.data[key] : void 0;
1569
+ if (value !== void 0) data[name] = value;
1570
+ }
1571
+ const props = settingsAt(node, fields, "desktop", ctx);
1572
+ const anchor = props.anchor;
1573
+ return /* @__PURE__ */ jsx14(
1574
+ CodeWidget,
1575
+ {
1576
+ node,
1577
+ snapshot,
1578
+ registry,
1579
+ props,
1580
+ data,
1581
+ locale: ctx.locale,
1582
+ mediaOrigin: ctx.mediaOrigin,
1583
+ edit: ctx.edit,
1584
+ code: ctx.code,
1585
+ interactive: ctx.interactive,
1586
+ anchor: !ctx.dupe && typeof anchor === "string" && anchor !== "" ? anchor : void 0,
1587
+ copyAnchor: ctx.vpath !== "" && typeof anchor === "string" && anchor !== "" ? anchor : void 0,
1588
+ entrance: entranceOf(props.entrance, props.entranceDelayMs, ctx.interactive)
1589
+ }
1590
+ );
1591
+ }
497
1592
  function renderWidget(node, ctx, registry) {
1593
+ const key = `${node.type}@${String(node.v)}`;
1594
+ const frozen = ctx.snapshots !== void 0 && Object.hasOwn(ctx.snapshots, key) ? ctx.snapshots[key] : void 0;
1595
+ if (frozen?.kind === "code") return renderCodeWidget(node, frozen, ctx, registry);
498
1596
  const def = registry.widget(node.type, node.v);
499
1597
  const Component2 = def === void 0 ? void 0 : registry.component(node);
500
1598
  if (def === void 0 || Component2 === void 0) {
501
1599
  if (isDevelopment()) {
502
1600
  warnOnce(`missing:${node.type}@${String(node.v)}`, `Unknown widget ${node.type} v${String(node.v)}; rendering nothing for it`);
503
1601
  }
504
- 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" }) });
1602
+ return /* @__PURE__ */ jsx14(NodeWrapper, { id: node.id, part: "widget", type: node.type, className: "tb-w", missing: true, children: ctx.edit !== void 0 && /* @__PURE__ */ jsx14("div", { className: "tb-missing", children: "Widget unavailable: update @usethrottle/storefront-react" }) });
505
1603
  }
506
1604
  if (ctx.edit === void 0 && hiddenEverywhere(node.props, node.responsive)) return null;
507
1605
  const fields = new Map([...COMMON_BY_KEY2, ...def.settings.map((f) => [f.key, f])]);
508
1606
  const variants = variantsOf(node, def, fields, ctx);
509
1607
  const data = {};
510
1608
  for (const [name, binding] of Object.entries(bindingsOf(node, registry))) {
511
- const key = bindingKey(binding);
512
- const value = Object.hasOwn(ctx.data, key) ? ctx.data[key] : void 0;
1609
+ const key2 = bindingKey(binding);
1610
+ const value = Object.hasOwn(ctx.data, key2) ? ctx.data[key2] : void 0;
513
1611
  if (value !== void 0) data[name] = value;
514
1612
  }
515
1613
  const custom = node.type.startsWith("custom.");
516
1614
  const edit = ctx.edit;
517
1615
  return variants.map((variant, index) => {
518
1616
  const anchor = variant.props.anchor;
519
- return /* @__PURE__ */ jsx2(
1617
+ return /* @__PURE__ */ jsx14(
520
1618
  NodeWrapper,
521
1619
  {
522
1620
  id: node.id,
@@ -525,18 +1623,22 @@ function renderWidget(node, ctx, registry) {
525
1623
  custom,
526
1624
  edit,
527
1625
  className: variants.length > 1 ? `tb-w ${variantClass(variant)}` : "tb-w",
528
- anchor: index === 0 && typeof anchor === "string" && anchor !== "" ? anchor : void 0,
529
- children: /* @__PURE__ */ jsx2(
1626
+ anchor: index === 0 && !ctx.dupe && typeof anchor === "string" && anchor !== "" ? anchor : void 0,
1627
+ copyAnchor: ctx.vpath !== "" && typeof anchor === "string" && anchor !== "" ? anchor : void 0,
1628
+ entrance: entranceOf(variant.props.entrance, variant.props.entranceDelayMs, ctx.interactive),
1629
+ children: /* @__PURE__ */ jsx14(
530
1630
  Component2,
531
1631
  {
532
1632
  node,
533
1633
  props: variant.props,
534
1634
  data,
535
1635
  editMode: edit !== void 0,
1636
+ interactive: ctx.interactive,
1637
+ idScope: ctx.vpath === "" && !ctx.dupe ? void 0 : { vpath: ctx.vpath, dupe: ctx.dupe },
536
1638
  locale: ctx.locale,
537
1639
  mediaOrigin: ctx.mediaOrigin,
538
1640
  resolveLink: ctx.resolveLink,
539
- inlineEdit: edit === void 0 ? void 0 : (key) => edit.inlineEdit(node.id, key),
1641
+ inlineEdit: edit === void 0 ? void 0 : (key2) => edit.inlineEdit(node.id, key2),
540
1642
  budget: custom ? new RenderBudget() : void 0
541
1643
  }
542
1644
  )
@@ -547,62 +1649,167 @@ function renderWidget(node, ctx, registry) {
547
1649
  }
548
1650
  function renderColumn(column, ctx, registry) {
549
1651
  if (ctx.edit === void 0 && hiddenEverywhere(column.props, column.responsive)) return null;
550
- return /* @__PURE__ */ jsx2(
1652
+ return /* @__PURE__ */ jsx14(
551
1653
  NodeWrapper,
552
1654
  {
553
1655
  id: column.id,
554
1656
  part: "column",
555
1657
  className: "tb-col",
556
- anchor: column.props.anchor,
1658
+ anchor: ctx.dupe ? void 0 : column.props.anchor,
1659
+ copyAnchor: ctx.vpath === "" ? void 0 : column.props.anchor,
557
1660
  edit: ctx.edit,
1661
+ entrance: entranceOf(
1662
+ resolveEntrance(column, "desktop").entrance,
1663
+ resolveEntrance(column, "desktop").entranceDelayMs,
1664
+ ctx.interactive
1665
+ ),
558
1666
  children: column.children.map(
559
- (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)
1667
+ (child) => child.type === "inner-section" ? /* @__PURE__ */ jsx14(Fragment3, { children: renderSection(child, ctx, registry, true) }, child.id) : /* @__PURE__ */ jsx14(Fragment3, { children: renderWidget(child, ctx, registry) }, child.id)
560
1668
  )
561
1669
  },
562
1670
  column.id
563
1671
  );
564
1672
  }
1673
+ var PLAIN = resolveInteraction({ props: {}, responsive: void 0 }, "desktop");
1674
+ function sectionVariants(section, ctx) {
1675
+ const groups = /* @__PURE__ */ new Map();
1676
+ for (const device of DEVICES) {
1677
+ const interaction = ctx.interactive ? resolveInteraction(section, device) : PLAIN;
1678
+ const entrance = ctx.interactive ? resolveEntrance(section, device) : { entrance: "none", entranceDelayMs: 0 };
1679
+ const signature = stable([interaction, entrance]);
1680
+ const group = groups.get(signature);
1681
+ if (group === void 0) groups.set(signature, { devices: [device], interaction, entrance });
1682
+ else group.devices.push(device);
1683
+ }
1684
+ return [...groups.values()];
1685
+ }
1686
+ function panelsOf(section, ctx, registry, fallback) {
1687
+ const rendered = section.columns.map((column) => ({ column, node: renderColumn(column, ctx, registry) })).filter((entry) => entry.node !== null);
1688
+ return rendered.map(({ column, node }, i) => {
1689
+ const title = pickLocale(column.props.panelTitle ?? {}, ctx.locale).trim();
1690
+ return { key: column.id, title: title === "" ? fallback(i + 1, rendered.length) : title, node };
1691
+ });
1692
+ }
565
1693
  function renderSection(section, ctx, registry, nested = false) {
566
1694
  if (ctx.edit === void 0 && hiddenEverywhere(section.props, section.responsive)) return null;
567
- return /* @__PURE__ */ jsx2(
568
- NodeWrapper,
569
- {
570
- id: section.id,
571
- part: "section",
572
- as: nested ? "div" : "section",
573
- className: nested ? "tb-section tb-nested" : "tb-section",
574
- anchor: section.props.anchor,
575
- edit: ctx.edit,
576
- children: /* @__PURE__ */ jsx2("div", { className: "tb-inner", children: /* @__PURE__ */ jsx2("div", { className: "tb-row", children: section.columns.map((column) => renderColumn(column, ctx, registry)) }) })
1695
+ const variants = sectionVariants(section, ctx);
1696
+ const marker = variants.length > 1 && !ctx.dupe && section.props.anchor !== void 0 && ANCHOR_RE3.test(section.props.anchor) ? /* @__PURE__ */ jsx14("div", { id: section.props.anchor, className: "tb-anchor" }, "anchor") : null;
1697
+ const copies = variants.map((variant, index) => {
1698
+ const { interaction } = variant;
1699
+ const id = `ix-${section.id}-${ctx.vpath}${String(index)}`;
1700
+ const own = variants.length > 1 ? { ...ctx, vpath: `${ctx.vpath}${String(index)}-`, dupe: ctx.dupe || index > 0 } : ctx;
1701
+ const columns = () => section.columns.map((column) => renderColumn(column, own, registry));
1702
+ let body;
1703
+ if (interaction.interaction === "tabs") {
1704
+ body = /* @__PURE__ */ jsx14(Tabs, { id, panels: panelsOf(section, own, registry, (n) => `Tab ${String(n)}`) });
1705
+ } else if (interaction.interaction === "accordion") {
1706
+ body = /* @__PURE__ */ jsx14(
1707
+ Accordion,
1708
+ {
1709
+ id,
1710
+ panels: panelsOf(section, own, registry, (n) => `Section ${String(n)}`),
1711
+ multiple: interaction.accordionMultiple,
1712
+ openFirst: interaction.accordionOpenFirst
1713
+ }
1714
+ );
1715
+ } else if (interaction.interaction === "carousel") {
1716
+ body = /* @__PURE__ */ jsx14(
1717
+ Carousel,
1718
+ {
1719
+ panels: panelsOf(section, own, registry, () => ""),
1720
+ autoplayMs: interaction.carouselAutoplay ? interaction.carouselIntervalMs : null,
1721
+ loop: interaction.carouselLoop
1722
+ }
1723
+ );
1724
+ } else if (interaction.interaction === "toggle") {
1725
+ body = /* @__PURE__ */ jsx14(
1726
+ Toggle,
1727
+ {
1728
+ labelOpen: pickLocale(interaction.toggleLabelOpen, ctx.locale),
1729
+ labelClosed: pickLocale(interaction.toggleLabelClosed, ctx.locale),
1730
+ startOpen: interaction.toggleStartOpen,
1731
+ children: columns()
1732
+ }
1733
+ );
1734
+ } else {
1735
+ body = /* @__PURE__ */ jsx14("div", { className: "tb-row", children: columns() });
577
1736
  }
578
- );
1737
+ return /* @__PURE__ */ jsx14(
1738
+ NodeWrapper,
1739
+ {
1740
+ id: section.id,
1741
+ part: "section",
1742
+ as: nested ? "div" : "section",
1743
+ className: `${nested ? "tb-section tb-nested" : "tb-section"}${variants.length > 1 ? ` ${variantClass({ devices: variant.devices, props: {} })}` : ""}`,
1744
+ anchor: variants.length === 1 && !ctx.dupe ? section.props.anchor : void 0,
1745
+ copyAnchor: variants.length > 1 || ctx.vpath !== "" ? section.props.anchor : void 0,
1746
+ edit: ctx.edit,
1747
+ entrance: entranceOf(variant.entrance.entrance, variant.entrance.entranceDelayMs, ctx.interactive),
1748
+ children: /* @__PURE__ */ jsx14("div", { className: "tb-inner", children: body })
1749
+ },
1750
+ variant.devices.join("-")
1751
+ );
1752
+ });
1753
+ return marker === null ? copies : [marker, ...copies];
1754
+ }
1755
+ function needsRuntime(doc) {
1756
+ let found = false;
1757
+ walkNodes3(doc, (node) => {
1758
+ if (found || node.type === "saved-section") return;
1759
+ if (node.type === "section" || node.type === "inner-section") {
1760
+ found = DEVICES.some(
1761
+ (device) => resolveInteraction(node, device).interaction !== "none" || resolveEntrance(node, device).entrance !== "none"
1762
+ );
1763
+ } else if (node.type === "column") {
1764
+ found = DEVICES.some((device) => resolveEntrance(node, device).entrance !== "none");
1765
+ } else {
1766
+ found = DEVICES.some((device) => {
1767
+ const entrance = resolveResponsive2(node.props, node.responsive, device).entrance;
1768
+ return entrance !== void 0 && entrance !== "none";
1769
+ });
1770
+ }
1771
+ });
1772
+ return found;
579
1773
  }
580
1774
  function BuilderRenderer(props) {
581
- const { document: source, registry: base, data, editMode, locale, assets, resolveLink } = props;
1775
+ const { document: raw, registry: base, data, editMode, locale, assets, resolveLink, code } = props;
1776
+ const expansion = expandSavedSections(raw, props.savedSections);
1777
+ const source = expansion.doc;
582
1778
  const registry = registryFor(source, base);
583
1779
  const { doc } = upgradeNodes(source, registry);
584
1780
  const mediaOrigin = props.mediaOrigin ?? "";
585
- const ctx = { registry, data, locale, assets, mediaOrigin, resolveLink, edit: editMode };
1781
+ const interactive = props.interactive !== false;
1782
+ const ctx = { registry, data, locale, assets, mediaOrigin, resolveLink, code, edit: editMode, interactive, vpath: props.idScope?.vpath ?? "", dupe: props.idScope?.dupe ?? false, snapshots: source.customWidgets };
586
1783
  const css = compileResponsiveCss(doc, registry, assets, mediaOrigin);
587
- return /* @__PURE__ */ jsxs("div", { className: "tb-root", "data-throttle-part": "builder-root", children: [
588
- /* @__PURE__ */ jsx2("style", { href: "tb-base", precedence: "throttle", children: BASE_CSS }),
589
- css === "" ? null : /* @__PURE__ */ jsx2("style", { children: css }),
590
- doc.sections.map(
591
- (section) => section.type === "section" ? /* @__PURE__ */ jsx2(Fragment, { children: renderSection(section, ctx, registry) }, section.id) : null
592
- )
1784
+ const upgraded = new Map(doc.sections.map((section) => [section.id, section]));
1785
+ return /* @__PURE__ */ jsxs7("div", { className: "tb-root", "data-throttle-part": "builder-root", ...props.scopeCustomCss === true ? { "data-b-root": "" } : {}, children: [
1786
+ interactive && needsRuntime(doc) ? /* @__PURE__ */ jsx14(InteractionRuntime, {}) : null,
1787
+ /* @__PURE__ */ jsx14("style", { href: "tb-base", precedence: "throttle", children: BASE_CSS }),
1788
+ css === "" ? null : /* @__PURE__ */ jsx14("style", { children: css }),
1789
+ (expansion.roots ?? doc.sections.map((section) => ({ kind: "section", id: section.id }))).map((root) => {
1790
+ if (root.kind === "section") {
1791
+ const section2 = upgraded.get(root.id);
1792
+ return section2?.type === "section" ? /* @__PURE__ */ jsx14(Fragment3, { children: renderSection(section2, ctx, registry) }, root.id) : null;
1793
+ }
1794
+ const section = root.sectionId === null ? void 0 : upgraded.get(root.sectionId);
1795
+ if (section?.type === "section") {
1796
+ return root.ref.props.hidden === true && ctx.edit === void 0 ? null : /* @__PURE__ */ jsx14(Fragment3, { children: renderSection(section, ctx, registry) }, root.ref.id);
1797
+ }
1798
+ return /* @__PURE__ */ jsx14(MissingSavedSection, { node: root.ref }, root.ref.id);
1799
+ })
593
1800
  ] });
594
1801
  }
595
1802
  function validateRender(doc) {
596
1803
  const h1 = [];
597
- walkNodes2(doc, (node) => {
1804
+ walkNodes3(doc, (node) => {
598
1805
  if (node.type === "basic.heading" && node.props.level === "h1") h1.push(node.id);
599
1806
  });
600
1807
  return h1.length > 1 ? [{ code: "MULTIPLE_H1", message: `The page has ${String(h1.length)} level 1 headings; use one`, nodeIds: h1 }] : [];
601
1808
  }
602
1809
 
603
1810
  // src/asset-image.tsx
604
- import { safeUrl as safeUrl3 } from "@usethrottle/builder-schema";
605
- import { jsx as jsx3 } from "react/jsx-runtime";
1811
+ import { safeUrl as safeUrl4 } from "@usethrottle/builder-schema";
1812
+ import { jsx as jsx15 } from "react/jsx-runtime";
606
1813
  function isFrozenAsset(value) {
607
1814
  if (typeof value !== "object" || value === null) return false;
608
1815
  const v = value;
@@ -610,7 +1817,7 @@ function isFrozenAsset(value) {
610
1817
  }
611
1818
  function AssetImage(props) {
612
1819
  const { asset, alt, sizes, className, loading = "lazy", style, mediaOrigin } = props;
613
- const href = (url) => safeUrl3(url, "src", { mediaOrigin });
1820
+ const href = (url) => safeUrl4(url, "src", { mediaOrigin });
614
1821
  if (!isFrozenAsset(asset)) return null;
615
1822
  const src = href(asset.url);
616
1823
  if (src === null) return null;
@@ -618,7 +1825,7 @@ function AssetImage(props) {
618
1825
  const url = href(variant.url);
619
1826
  return url === null || url.includes(",") ? [] : [`${url} ${String(variant.width)}w`];
620
1827
  }).join(", ");
621
- return /* @__PURE__ */ jsx3(
1828
+ return /* @__PURE__ */ jsx15(
622
1829
  "img",
623
1830
  {
624
1831
  src,
@@ -634,46 +1841,36 @@ function AssetImage(props) {
634
1841
  );
635
1842
  }
636
1843
 
637
- // src/widget-style.tsx
638
- import { jsx as jsx4 } from "react/jsx-runtime";
639
- function WidgetStyle({ css }) {
640
- if (css === "" || css.includes("<")) return null;
641
- return /* @__PURE__ */ jsx4("style", { children: css });
642
- }
643
-
644
1844
  // src/provider.tsx
645
- import { Suspense as Suspense4, useCallback, useContext as useContext2, useMemo, useRef as useRef2 } from "react";
1845
+ import { Suspense as Suspense5, useCallback, useContext as useContext2, useMemo, useRef as useRef3 } from "react";
646
1846
  import { createBuilderClient } from "@usethrottle/builder";
647
1847
  import { AppearanceContext, SiteDesignProvider, SlotOutletProvider, ThrottleUIProvider, useAppearanceProviderValue } from "@usethrottle/ui";
648
1848
 
649
- // src/context.ts
650
- import { createContext, useContext } from "react";
651
- var BuilderContext = typeof createContext === "function" ? createContext(null) : null;
652
- var useBuilder = () => useContext(BuilderContext);
653
-
654
1849
  // src/page.tsx
655
- import { useEffect as useEffect2 } from "react";
1850
+ import { useEffect as useEffect4 } from "react";
656
1851
  import { BuilderUnavailableError } from "@usethrottle/builder";
657
1852
 
658
1853
  // src/load.ts
659
1854
  function pageOf(raw, initialData) {
660
- const { document, id: _id, slug, title, path, generation, pageType: _type, updatedAt: _updated, ...meta } = raw;
1855
+ const { document: document2, id: _id, slug, title, path, generation, pageType: _type, updatedAt: _updated, savedSections, code, ...meta } = raw;
661
1856
  return {
662
1857
  kind: "page",
663
1858
  slug,
664
1859
  title,
665
1860
  path,
666
1861
  generation,
667
- document,
668
- assets: document.assets ?? {},
1862
+ document: document2,
1863
+ assets: document2.assets ?? {},
669
1864
  initialData,
670
- meta
1865
+ meta,
1866
+ ...savedSections === void 0 ? {} : { savedSections },
1867
+ ...code === void 0 ? {} : { code }
671
1868
  };
672
1869
  }
673
1870
  var isRedirect = (raw) => typeof raw.redirectTo === "string";
674
1871
 
675
1872
  // src/safe-path.ts
676
- import { safeUrl as safeUrl4 } from "@usethrottle/builder-schema";
1873
+ import { safeUrl as safeUrl5 } from "@usethrottle/builder-schema";
677
1874
  var UNSAFE = /[\x00-\x20\x7f-\xa0\\\u1680\u2000-\u200f\u2028\u2029\u202f\u205f\u3000\ufeff]/;
678
1875
  var LEADING = /^\/(?![/\\])/;
679
1876
  function plainPath(path) {
@@ -681,51 +1878,31 @@ function plainPath(path) {
681
1878
  }
682
1879
  function sitePath(to) {
683
1880
  if (typeof to !== "string" || !plainPath(to)) return null;
684
- let decoded;
1881
+ let decoded2;
685
1882
  try {
686
- decoded = decodeURIComponent(to);
1883
+ decoded2 = decodeURIComponent(to);
687
1884
  } catch {
688
1885
  return null;
689
1886
  }
690
- if (!plainPath(decoded)) return null;
691
- return safeUrl4(to, "href", { mediaOrigin: "" });
692
- }
693
-
694
- // src/shopper-data.ts
695
- import { useEffect, useState } from "react";
696
- function useResolvedData(document, registry, locale, include, context) {
697
- const [data, setData] = useState({});
698
- useEffect(() => {
699
- const controller = new AbortController();
700
- const bindings = collectBindings(document, registry);
701
- if (bindings.size === 0) return void 0;
702
- void resolveBindings(
703
- bindings,
704
- registry,
705
- { locale, preview: false, context, signal: controller.signal },
706
- { include }
707
- ).then((resolved) => {
708
- if (!controller.signal.aborted && Object.keys(resolved).length > 0) setData(resolved);
709
- });
710
- return () => controller.abort();
711
- }, [document, registry, locale, include, context]);
712
- return data;
1887
+ if (!plainPath(decoded2)) return null;
1888
+ return safeUrl5(to, "href", { mediaOrigin: "" });
713
1889
  }
714
1890
 
715
1891
  // src/page.tsx
716
- import { jsx as jsx5 } from "react/jsx-runtime";
1892
+ import { jsx as jsx16 } from "react/jsx-runtime";
717
1893
  function BuilderPageView({ page, resolve = "shopper" }) {
718
1894
  const builder = useBuilder();
719
1895
  if (builder === null) throw new Error("A Builder page needs a BuilderProvider above it");
720
- return /* @__PURE__ */ jsx5(PageBody, { page, resolve, builder });
1896
+ return /* @__PURE__ */ jsx16(PageBody, { page, resolve, builder });
721
1897
  }
722
1898
  function PageBody({
723
1899
  page,
724
1900
  resolve,
725
1901
  builder
726
1902
  }) {
727
- const resolved = useResolvedData(page.document, builder.registry, builder.locale, resolve);
728
- return /* @__PURE__ */ jsx5(
1903
+ const expanded = expandSavedSections(page.document, page.savedSections).doc;
1904
+ const resolved = useResolvedData(expanded, builder.registry, builder.locale, resolve);
1905
+ return /* @__PURE__ */ jsx16(
729
1906
  BuilderRenderer,
730
1907
  {
731
1908
  document: page.document,
@@ -734,7 +1911,11 @@ function PageBody({
734
1911
  locale: builder.locale,
735
1912
  assets: page.assets,
736
1913
  mediaOrigin: builder.mediaOrigin,
737
- resolveLink: builder.resolveLink
1914
+ resolveLink: builder.resolveLink,
1915
+ interactive: builder.interactive,
1916
+ scopeCustomCss: builder.customCss !== "",
1917
+ savedSections: page.savedSections,
1918
+ code: codeRenderOf(builder, page.code)
738
1919
  }
739
1920
  );
740
1921
  }
@@ -773,7 +1954,7 @@ function read(client, slug, locale) {
773
1954
  function BuilderPage({ slug, initial }) {
774
1955
  const builder = useBuilder();
775
1956
  if (builder === null) throw new Error("BuilderPage needs a BuilderProvider above it");
776
- if (initial !== void 0) return /* @__PURE__ */ jsx5(BuilderPageView, { page: initial });
1957
+ if (initial !== void 0) return /* @__PURE__ */ jsx16(BuilderPageView, { page: initial });
777
1958
  if (builder.site.status === "unavailable") {
778
1959
  throw new BuilderUnavailableError("network", "The Builder is unavailable and has no last good answer");
779
1960
  }
@@ -781,82 +1962,17 @@ function BuilderPage({ slug, initial }) {
781
1962
  throw new Error("BuilderPage reads the page itself: give BuilderProvider a builderKey or a client, or pass `initial`");
782
1963
  }
783
1964
  const found = read(builder.client, slug, builder.locale);
784
- if ("redirectTo" in found) return /* @__PURE__ */ jsx5(Redirect, { to: found.redirectTo });
785
- return /* @__PURE__ */ jsx5(BuilderPageView, { page: found, resolve: "all" });
1965
+ if ("redirectTo" in found) return /* @__PURE__ */ jsx16(Redirect, { to: found.redirectTo });
1966
+ return /* @__PURE__ */ jsx16(BuilderPageView, { page: found, resolve: "all" });
786
1967
  }
787
1968
  function Redirect({ to }) {
788
- useEffect2(() => {
1969
+ useEffect4(() => {
789
1970
  const path = sitePath(to);
790
1971
  if (path !== null) window.location.replace(path);
791
1972
  }, [to]);
792
1973
  return null;
793
1974
  }
794
1975
 
795
- // src/part-view.tsx
796
- import { Component } from "react";
797
- import { jsx as jsx6 } from "react/jsx-runtime";
798
- var BoundaryBase = Component ?? class {
799
- };
800
- var Boundary = class extends BoundaryBase {
801
- constructor() {
802
- super(...arguments);
803
- __publicField(this, "state", { failed: false });
804
- }
805
- static getDerivedStateFromError() {
806
- return { failed: true };
807
- }
808
- componentDidCatch(error, _info) {
809
- warnOnce(`part:${this.props.label}`, `${this.props.label} failed to render (${String(error)}); rendering nothing for it`);
810
- try {
811
- this.props.onError?.(error, { part: this.props.label });
812
- } catch {
813
- }
814
- }
815
- componentDidUpdate(previous) {
816
- const moved = previous.resetKeys.length !== this.props.resetKeys.length || previous.resetKeys.some((key, i) => !Object.is(key, this.props.resetKeys[i]));
817
- if (moved && this.state.failed) this.setState({ failed: false });
818
- }
819
- render() {
820
- return this.state.failed ? null : this.props.children;
821
- }
822
- };
823
- function PartBoundary({
824
- label,
825
- resetKey,
826
- children
827
- }) {
828
- const builder = useBuilder();
829
- return /* @__PURE__ */ jsx6(Boundary, { label, resetKeys: [builder?.site, resetKey], onError: builder?.onError, children });
830
- }
831
- function contextData(context) {
832
- if (typeof context !== "object" || context === null) return {};
833
- return Object.fromEntries(Object.entries(context).map(([key, value]) => [`context.${key}`, value]));
834
- }
835
- function PartView({ part, context }) {
836
- const builder = useBuilder();
837
- if (builder === null) return null;
838
- return /* @__PURE__ */ jsx6(PartBody, { part, context, builder });
839
- }
840
- function PartBody({
841
- part,
842
- context,
843
- builder
844
- }) {
845
- const shopper = useResolvedData(part.document, builder.registry, builder.locale, "shopper", context);
846
- return /* @__PURE__ */ jsx6(
847
- BuilderRenderer,
848
- {
849
- document: part.document,
850
- registry: builder.registry,
851
- data: { ...part.initialData, ...contextData(context), ...shopper },
852
- locale: builder.locale,
853
- assets: part.assets,
854
- mediaOrigin: builder.mediaOrigin,
855
- resolveLink: builder.resolveLink
856
- }
857
- );
858
- }
859
-
860
1976
  // src/registry.ts
861
1977
  import { createRegistry } from "@usethrottle/builder-schema";
862
1978
 
@@ -864,12 +1980,12 @@ import { createRegistry } from "@usethrottle/builder-schema";
864
1980
  import { BASIC_WIDGET_DEFINITIONS as BASIC_WIDGET_DEFINITIONS2 } from "@usethrottle/builder-schema";
865
1981
 
866
1982
  // src/basics/announcement.tsx
867
- import { useEffect as useEffect3, useState as useState2 } from "react";
1983
+ import { useEffect as useEffect5, useState as useState2 } from "react";
868
1984
  import { Icon, useSiteDesign } from "@usethrottle/ui";
869
- import { SITE_STRING_DEFAULTS, safeUrl as safeUrl6 } from "@usethrottle/builder-schema";
1985
+ import { SITE_STRING_DEFAULTS, safeUrl as safeUrl7 } from "@usethrottle/builder-schema";
870
1986
 
871
1987
  // src/basics/util.tsx
872
- import { BASIC_WIDGET_DEFINITIONS, resolveResponsive as resolveResponsive3, safeUrl as safeUrl5 } from "@usethrottle/builder-schema";
1988
+ import { BASIC_WIDGET_DEFINITIONS, resolveResponsive as resolveResponsive3, safeUrl as safeUrl6 } from "@usethrottle/builder-schema";
873
1989
 
874
1990
  // src/basics/styles.ts
875
1991
  var BASICS_CSS = `@layer throttle{
@@ -934,23 +2050,23 @@ var BASICS_CSS = `@layer throttle{
934
2050
  }`;
935
2051
 
936
2052
  // src/basics/util.tsx
937
- import { jsx as jsx7 } from "react/jsx-runtime";
2053
+ import { jsx as jsx17 } from "react/jsx-runtime";
938
2054
  function BasicStyles() {
939
- return /* @__PURE__ */ jsx7("style", { href: "tb-basics", precedence: "throttle", children: BASICS_CSS });
2055
+ return /* @__PURE__ */ jsx17("style", { href: "tb-basics", precedence: "throttle", children: BASICS_CSS });
940
2056
  }
941
- var isRecord2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
2057
+ var isRecord3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
942
2058
  var str = (v) => typeof v === "string" && v !== "" ? v : void 0;
943
2059
  function oneOf(value, allowed, fallback) {
944
2060
  return allowed.find((candidate) => candidate === value) ?? fallback;
945
2061
  }
946
2062
  function hrefOf(link, mediaOrigin) {
947
- if (!isRecord2(link)) return null;
948
- return safeUrl5(link.href, "href", { mediaOrigin });
2063
+ if (!isRecord3(link)) return null;
2064
+ return safeUrl6(link.href, "href", { mediaOrigin });
949
2065
  }
950
2066
  function Placeholder({ editMode, children }) {
951
- return editMode ? /* @__PURE__ */ jsx7("div", { className: "tb-b-empty", children }) : null;
2067
+ return editMode ? /* @__PURE__ */ jsx17("div", { className: "tb-b-empty", children }) : null;
952
2068
  }
953
- var ID_RE2 = /^[a-z0-9]{8,24}$/;
2069
+ var ID_RE2 = /^[a-z0-9]{8,24}(-[a-z0-9]{8,24})?$/;
954
2070
  var DEVICES2 = ["desktop", "tablet", "phone"];
955
2071
  function defaultOf(type, key) {
956
2072
  const def = BASIC_WIDGET_DEFINITIONS.find((d) => d.type === type);
@@ -978,7 +2094,7 @@ function enumCss(node, rules) {
978
2094
  }
979
2095
 
980
2096
  // src/basics/announcement.tsx
981
- import { Fragment as Fragment2, jsx as jsx8, jsxs as jsxs2 } from "react/jsx-runtime";
2097
+ import { Fragment as Fragment4, jsx as jsx18, jsxs as jsxs8 } from "react/jsx-runtime";
982
2098
  var KEY = "tb-announcement-dismissed";
983
2099
  function read2(message) {
984
2100
  try {
@@ -997,24 +2113,24 @@ function Announcement({ props, mediaOrigin, editMode }) {
997
2113
  const design = useSiteDesign();
998
2114
  const message = design?.announcement?.message;
999
2115
  const [dismissed, setDismissed] = useState2(false);
1000
- useEffect3(() => {
2116
+ useEffect5(() => {
1001
2117
  if (message !== void 0 && read2(message)) setDismissed(true);
1002
2118
  }, [message]);
1003
2119
  if (message === void 0) {
1004
- return /* @__PURE__ */ jsxs2(Fragment2, { children: [
1005
- /* @__PURE__ */ jsx8(BasicStyles, {}),
1006
- /* @__PURE__ */ jsx8(Placeholder, { editMode, children: "No announcement: turn one on in Site settings" })
2120
+ return /* @__PURE__ */ jsxs8(Fragment4, { children: [
2121
+ /* @__PURE__ */ jsx18(BasicStyles, {}),
2122
+ /* @__PURE__ */ jsx18(Placeholder, { editMode, children: "No announcement: turn one on in Site settings" })
1007
2123
  ] });
1008
2124
  }
1009
2125
  if (dismissed && !editMode) return null;
1010
- const href = safeUrl6(design?.announcement?.href, "href", { mediaOrigin });
2126
+ const href = safeUrl7(design?.announcement?.href, "href", { mediaOrigin });
1011
2127
  const strings = design?.strings;
1012
2128
  const dismissLabel = (strings !== void 0 && Object.hasOwn(strings, "announcement.dismiss") ? str(strings["announcement.dismiss"]) : void 0) ?? SITE_STRING_DEFAULTS["announcement.dismiss"];
1013
- return /* @__PURE__ */ jsxs2(Fragment2, { children: [
1014
- /* @__PURE__ */ jsx8(BasicStyles, {}),
1015
- /* @__PURE__ */ jsxs2("div", { className: "tb-b-announcement", role: "region", "aria-label": message, children: [
1016
- /* @__PURE__ */ jsx8("span", { className: "tb-b-announcement-text", children: href === null ? message : /* @__PURE__ */ jsx8("a", { href, children: message }) }),
1017
- props.dismissible === true && /* @__PURE__ */ jsx8(
2129
+ return /* @__PURE__ */ jsxs8(Fragment4, { children: [
2130
+ /* @__PURE__ */ jsx18(BasicStyles, {}),
2131
+ /* @__PURE__ */ jsxs8("div", { className: "tb-b-announcement", role: "region", "aria-label": message, children: [
2132
+ /* @__PURE__ */ jsx18("span", { className: "tb-b-announcement-text", children: href === null ? message : /* @__PURE__ */ jsx18("a", { href, children: message }) }),
2133
+ props.dismissible === true && /* @__PURE__ */ jsx18(
1018
2134
  "button",
1019
2135
  {
1020
2136
  type: "button",
@@ -1023,7 +2139,7 @@ function Announcement({ props, mediaOrigin, editMode }) {
1023
2139
  write(message);
1024
2140
  setDismissed(true);
1025
2141
  },
1026
- children: /* @__PURE__ */ jsx8(Icon, { name: "close", size: 16, label: dismissLabel })
2142
+ children: /* @__PURE__ */ jsx18(Icon, { name: "close", size: 16, label: dismissLabel })
1027
2143
  }
1028
2144
  )
1029
2145
  ] })
@@ -1031,59 +2147,125 @@ function Announcement({ props, mediaOrigin, editMode }) {
1031
2147
  }
1032
2148
 
1033
2149
  // src/basics/button.tsx
1034
- import { Fragment as Fragment3, jsx as jsx9, jsxs as jsxs3 } from "react/jsx-runtime";
2150
+ import { Fragment as Fragment5, jsx as jsx19, jsxs as jsxs9 } from "react/jsx-runtime";
1035
2151
  var STYLES = ["primary", "secondary", "outline", "link"];
1036
2152
  var SIZES = ["s", "m", "l"];
1037
2153
  function Button({ props, mediaOrigin, inlineEdit }) {
1038
2154
  const href = hrefOf(props.link, mediaOrigin);
1039
2155
  const className = `tb-b-button tb-b-button--${oneOf(props.style, STYLES, "primary")} tb-b-button--${oneOf(props.size, SIZES, "m")}`;
1040
2156
  const label = inlineEdit?.("label") ?? str(props.label) ?? "";
1041
- return /* @__PURE__ */ jsxs3(Fragment3, { children: [
1042
- /* @__PURE__ */ jsx9(BasicStyles, {}),
1043
- /* @__PURE__ */ jsx9("div", { className: "tb-b-button-wrap", children: /* @__PURE__ */ jsx9("a", { className, ...href === null ? {} : { href }, children: label }) })
2157
+ return /* @__PURE__ */ jsxs9(Fragment5, { children: [
2158
+ /* @__PURE__ */ jsx19(BasicStyles, {}),
2159
+ /* @__PURE__ */ jsx19("div", { className: "tb-b-button-wrap", children: /* @__PURE__ */ jsx19("a", { className, ...href === null ? {} : { href }, children: label }) })
1044
2160
  ] });
1045
2161
  }
1046
2162
 
1047
2163
  // src/basics/copyright.tsx
1048
2164
  import { useSiteDesign as useSiteDesign2 } from "@usethrottle/ui";
1049
2165
  import { SITE_STRING_DEFAULTS as SITE_STRING_DEFAULTS2 } from "@usethrottle/builder-schema";
1050
- import { Fragment as Fragment4, jsx as jsx10, jsxs as jsxs4 } from "react/jsx-runtime";
2166
+ import { Fragment as Fragment6, jsx as jsx20, jsxs as jsxs10 } from "react/jsx-runtime";
1051
2167
  function Copyright(_) {
1052
2168
  const design = useSiteDesign2();
1053
2169
  const strings = design?.strings;
1054
2170
  const template = strings !== void 0 && Object.hasOwn(strings, "footer.copyright") ? str(strings["footer.copyright"]) : void 0;
1055
2171
  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");
1056
- return /* @__PURE__ */ jsxs4(Fragment4, { children: [
1057
- /* @__PURE__ */ jsx10(BasicStyles, {}),
1058
- /* @__PURE__ */ jsx10("p", { className: "tb-b-copyright", children: line })
2172
+ return /* @__PURE__ */ jsxs10(Fragment6, { children: [
2173
+ /* @__PURE__ */ jsx20(BasicStyles, {}),
2174
+ /* @__PURE__ */ jsx20("p", { className: "tb-b-copyright", children: line })
2175
+ ] });
2176
+ }
2177
+
2178
+ // src/basics/countdown.tsx
2179
+ import { Fragment as Fragment7, jsx as jsx21, jsxs as jsxs11 } from "react/jsx-runtime";
2180
+ var UNITS2 = [
2181
+ { key: "d", show: "showDays", label: "labelDays", seconds: 86400 },
2182
+ { key: "h", show: "showHours", label: "labelHours", seconds: 3600 },
2183
+ { key: "m", show: "showMinutes", label: "labelMinutes", seconds: 60 },
2184
+ { key: "s", show: "showSeconds", label: "labelSeconds", seconds: 1 }
2185
+ ];
2186
+ var COUNTDOWN_CSS = `@layer throttle{
2187
+ .tb-b-cd{text-align:var(--b-align,center);color:var(--b-color,inherit);font-size:var(--b-size,var(--tb-text-l))}
2188
+ .tb-b-cd-date{margin:0}
2189
+ .tb-b-cd-units{display:none;justify-content:var(--b-align,center);gap:var(--tb-space-m);flex-wrap:wrap}
2190
+ html[data-b-js] .tb-b-cd-units{display:flex}
2191
+ html[data-b-js] .tb-b-cd-date{font-size:.5em;opacity:.7}
2192
+ .tb-b-cd-unit{display:flex;flex-direction:column;align-items:center;min-inline-size:3ch}
2193
+ .tb-b-cd-num{font-variant-numeric:tabular-nums;font-weight:700;line-height:1.1}
2194
+ .tb-b-cd-label{font-size:.45em;opacity:.8}
2195
+ .tb-b-cd-ended{margin:0}
2196
+ .tb-b-cd[data-b-ended] .tb-b-cd-units,.tb-b-cd[data-b-ended] .tb-b-cd-date{display:none}
2197
+ .tb-b-sr{position:absolute;inline-size:1px;block-size:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap}
2198
+ }`;
2199
+ var two = (n) => String(n).padStart(2, "0");
2200
+ function targetText(date) {
2201
+ return `${date.toISOString().slice(0, 10)} ${date.toISOString().slice(11, 16)} UTC`;
2202
+ }
2203
+ function Countdown({ props, editMode, interactive, locale }) {
2204
+ void locale;
2205
+ const target = str(props.target);
2206
+ const when = target === void 0 ? null : new Date(target);
2207
+ if (when === null || Number.isNaN(when.getTime())) {
2208
+ return /* @__PURE__ */ jsx21(Placeholder, { editMode, children: "Set the date and time the countdown ends" });
2209
+ }
2210
+ const live = interactive !== false;
2211
+ const behavior = oneOf(props.expiredBehavior, ["text", "hide"], "text");
2212
+ const shown2 = UNITS2.filter((unit) => props[unit.show] !== false);
2213
+ let left = live ? 0 : Math.max(0, Math.floor((when.getTime() - Date.now()) / 1e3));
2214
+ const units = shown2.map((unit) => {
2215
+ const value = live ? null : Math.floor(left / unit.seconds);
2216
+ if (value !== null) left -= value * unit.seconds;
2217
+ return { ...unit, text: value === null ? "--" : two(value), name: str(props[unit.label]) ?? "" };
2218
+ });
2219
+ return /* @__PURE__ */ jsxs11(Fragment7, { children: [
2220
+ /* @__PURE__ */ jsx21(BasicStyles, {}),
2221
+ /* @__PURE__ */ jsx21("style", { href: "tb-countdown", precedence: "throttle", children: COUNTDOWN_CSS }),
2222
+ live ? /* @__PURE__ */ jsx21(InteractionRuntime, {}) : null,
2223
+ /* @__PURE__ */ jsxs11(
2224
+ "div",
2225
+ {
2226
+ className: "tb-b-cd",
2227
+ role: "timer",
2228
+ "aria-live": "off",
2229
+ ...live ? { "data-b-cd": String(when.getTime()), "data-b-expired": behavior } : {},
2230
+ children: [
2231
+ /* @__PURE__ */ jsx21("p", { className: "tb-b-cd-date", children: /* @__PURE__ */ jsx21("time", { dateTime: when.toISOString(), children: targetText(when) }) }),
2232
+ units.length === 0 ? null : /* @__PURE__ */ jsx21("div", { className: "tb-b-cd-units", children: units.map((unit) => /* @__PURE__ */ jsxs11("div", { className: "tb-b-cd-unit", children: [
2233
+ /* @__PURE__ */ jsx21("span", { className: "tb-b-cd-num", "data-u": unit.key, "aria-hidden": "true", children: unit.text }),
2234
+ /* @__PURE__ */ jsx21("span", { className: "tb-b-cd-label", children: unit.name })
2235
+ ] }, unit.key)) }),
2236
+ /* @__PURE__ */ jsx21("p", { className: "tb-b-cd-ended", hidden: live || when.getTime() > Date.now(), children: str(props.expiredText) ?? "" }),
2237
+ /* @__PURE__ */ jsx21("span", { className: "tb-b-sr", "data-b-live": "", "aria-live": "polite" })
2238
+ ]
2239
+ }
2240
+ )
1059
2241
  ] });
1060
2242
  }
1061
2243
 
1062
2244
  // src/basics/divider.tsx
1063
- import { Fragment as Fragment5, jsx as jsx11, jsxs as jsxs5 } from "react/jsx-runtime";
2245
+ import { Fragment as Fragment8, jsx as jsx22, jsxs as jsxs12 } from "react/jsx-runtime";
1064
2246
  var RULES = [{ key: "style", property: "--bx-style", values: { solid: "solid", dashed: "dashed", dotted: "dotted" } }];
1065
2247
  function Divider({ node }) {
1066
- return /* @__PURE__ */ jsxs5(Fragment5, { children: [
1067
- /* @__PURE__ */ jsx11(BasicStyles, {}),
1068
- /* @__PURE__ */ jsx11(WidgetStyle, { css: enumCss(node, RULES) }),
1069
- /* @__PURE__ */ jsx11("hr", { className: "tb-b-divider" })
2248
+ return /* @__PURE__ */ jsxs12(Fragment8, { children: [
2249
+ /* @__PURE__ */ jsx22(BasicStyles, {}),
2250
+ /* @__PURE__ */ jsx22(WidgetStyle, { css: enumCss(node, RULES) }),
2251
+ /* @__PURE__ */ jsx22("hr", { className: "tb-b-divider" })
1070
2252
  ] });
1071
2253
  }
1072
2254
 
1073
2255
  // src/basics/heading.tsx
1074
- import { Fragment as Fragment6, jsx as jsx12, jsxs as jsxs6 } from "react/jsx-runtime";
2256
+ import { Fragment as Fragment9, jsx as jsx23, jsxs as jsxs13 } from "react/jsx-runtime";
1075
2257
  var LEVELS = ["h1", "h2", "h3", "h4", "h5", "h6"];
1076
2258
  function Heading({ props, inlineEdit }) {
1077
2259
  const Tag = oneOf(props.level, LEVELS, "h2");
1078
- return /* @__PURE__ */ jsxs6(Fragment6, { children: [
1079
- /* @__PURE__ */ jsx12(BasicStyles, {}),
1080
- /* @__PURE__ */ jsx12(Tag, { className: "tb-b-heading", children: inlineEdit?.("text") ?? str(props.text) ?? "" })
2260
+ return /* @__PURE__ */ jsxs13(Fragment9, { children: [
2261
+ /* @__PURE__ */ jsx23(BasicStyles, {}),
2262
+ /* @__PURE__ */ jsx23(Tag, { className: "tb-b-heading", children: inlineEdit?.("text") ?? str(props.text) ?? "" })
1081
2263
  ] });
1082
2264
  }
1083
2265
 
1084
2266
  // src/basics/image.tsx
1085
- import { safeUrl as safeUrl7 } from "@usethrottle/builder-schema";
1086
- import { Fragment as Fragment7, jsx as jsx13, jsxs as jsxs7 } from "react/jsx-runtime";
2267
+ import { safeUrl as safeUrl8 } from "@usethrottle/builder-schema";
2268
+ import { Fragment as Fragment10, jsx as jsx24, jsxs as jsxs14 } from "react/jsx-runtime";
1087
2269
  var RULES2 = [
1088
2270
  { key: "radius", property: "--bx-radius", values: { none: "0", s: "4px", m: "8px", l: "16px", full: "9999px" } },
1089
2271
  { key: "fit", property: "--bx-fit", values: { cover: "cover", contain: "contain" } }
@@ -1093,23 +2275,23 @@ function Image({ node, props, mediaOrigin, editMode }) {
1093
2275
  const decorative = props.decorative === true;
1094
2276
  const alt = decorative ? "" : typeof props.alt === "string" ? props.alt : "";
1095
2277
  const asset = isFrozenAsset(props.image) ? props.image : void 0;
1096
- const image = /* @__PURE__ */ jsx13(AssetImage, { asset, mediaOrigin, alt, className: "tb-b-img", sizes: "(max-width: 767px) 100vw, 50vw" });
1097
- const shown = asset !== void 0 && safeUrl7(asset.url, "src", { mediaOrigin }) !== null;
1098
- return /* @__PURE__ */ jsxs7(Fragment7, { children: [
1099
- /* @__PURE__ */ jsx13(BasicStyles, {}),
1100
- /* @__PURE__ */ jsx13(WidgetStyle, { css: enumCss(node, RULES2) }),
1101
- 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" })
2278
+ const image = /* @__PURE__ */ jsx24(AssetImage, { asset, mediaOrigin, alt, className: "tb-b-img", sizes: "(max-width: 767px) 100vw, 50vw" });
2279
+ const shown2 = asset !== void 0 && safeUrl8(asset.url, "src", { mediaOrigin }) !== null;
2280
+ return /* @__PURE__ */ jsxs14(Fragment10, { children: [
2281
+ /* @__PURE__ */ jsx24(BasicStyles, {}),
2282
+ /* @__PURE__ */ jsx24(WidgetStyle, { css: enumCss(node, RULES2) }),
2283
+ shown2 ? /* @__PURE__ */ jsx24("div", { className: "tb-b-image", children: /* @__PURE__ */ jsx24("div", { className: "tb-b-image-box", children: href === null ? image : /* @__PURE__ */ jsx24("a", { href, children: image }) }) }) : /* @__PURE__ */ jsx24(Placeholder, { editMode, children: asset === void 0 ? "Choose an image" : "Image unavailable" })
1102
2284
  ] });
1103
2285
  }
1104
2286
 
1105
2287
  // src/basics/logo.tsx
1106
2288
  import { useSiteDesign as useSiteDesign3 } from "@usethrottle/ui";
1107
- import { safeUrl as safeUrl8 } from "@usethrottle/builder-schema";
1108
- import { Fragment as Fragment8, jsx as jsx14, jsxs as jsxs8 } from "react/jsx-runtime";
2289
+ import { safeUrl as safeUrl9 } from "@usethrottle/builder-schema";
2290
+ import { Fragment as Fragment11, jsx as jsx25, jsxs as jsxs15 } from "react/jsx-runtime";
1109
2291
  function Logo({ props, mediaOrigin, editMode }) {
1110
2292
  const design = useSiteDesign3();
1111
2293
  const scheme = design?.theme?.colorScheme ?? "auto";
1112
- const src = (url) => url === void 0 ? void 0 : safeUrl8(url, "src", { mediaOrigin }) ?? void 0;
2294
+ const src = (url) => url === void 0 ? void 0 : safeUrl9(url, "src", { mediaOrigin }) ?? void 0;
1113
2295
  const light = src(design?.brand?.logo?.light);
1114
2296
  const dark = src(design?.brand?.logo?.dark);
1115
2297
  const main = scheme === "dark" ? dark ?? light : light ?? dark;
@@ -1118,42 +2300,42 @@ function Logo({ props, mediaOrigin, editMode }) {
1118
2300
  const alt = name ?? "";
1119
2301
  let content = null;
1120
2302
  if (main !== void 0) {
1121
- const img = /* @__PURE__ */ jsx14("img", { src: main, alt, decoding: "async" });
1122
- content = scheme === "auto" && light !== void 0 && dark !== void 0 ? /* @__PURE__ */ jsxs8("picture", { children: [
1123
- /* @__PURE__ */ jsx14("source", { media: "(prefers-color-scheme: dark)", srcSet: dark }),
2303
+ const img = /* @__PURE__ */ jsx25("img", { src: main, alt, decoding: "async" });
2304
+ content = scheme === "auto" && light !== void 0 && dark !== void 0 ? /* @__PURE__ */ jsxs15("picture", { children: [
2305
+ /* @__PURE__ */ jsx25("source", { media: "(prefers-color-scheme: dark)", srcSet: dark }),
1124
2306
  img
1125
2307
  ] }) : img;
1126
2308
  } else if (name !== void 0) {
1127
- content = /* @__PURE__ */ jsx14("span", { className: "tb-b-logo-name", children: name });
2309
+ content = /* @__PURE__ */ jsx25("span", { className: "tb-b-logo-name", children: name });
1128
2310
  }
1129
- return /* @__PURE__ */ jsxs8(Fragment8, { children: [
1130
- /* @__PURE__ */ jsx14(BasicStyles, {}),
1131
- 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 }) })
2311
+ return /* @__PURE__ */ jsxs15(Fragment11, { children: [
2312
+ /* @__PURE__ */ jsx25(BasicStyles, {}),
2313
+ content === null ? /* @__PURE__ */ jsx25(Placeholder, { editMode, children: "Logo: add one in Site settings" }) : /* @__PURE__ */ jsx25("div", { className: "tb-b-logo", children: /* @__PURE__ */ jsx25("a", { href, children: content }) })
1132
2314
  ] });
1133
2315
  }
1134
2316
 
1135
2317
  // src/basics/menu.tsx
1136
- import { useId, useRef, useState as useState3 } from "react";
2318
+ import { useId, useRef as useRef2, useState as useState3 } from "react";
1137
2319
  import { Icon as Icon2, useSiteDesign as useSiteDesign4 } from "@usethrottle/ui";
1138
- import { SITE_STRING_DEFAULTS as SITE_STRING_DEFAULTS3, safeUrl as safeUrl9 } from "@usethrottle/builder-schema";
1139
- import { Fragment as Fragment9, jsx as jsx15, jsxs as jsxs9 } from "react/jsx-runtime";
2320
+ import { SITE_STRING_DEFAULTS as SITE_STRING_DEFAULTS3, safeUrl as safeUrl10 } from "@usethrottle/builder-schema";
2321
+ import { Fragment as Fragment12, jsx as jsx26, jsxs as jsxs16 } from "react/jsx-runtime";
1140
2322
  var LAYOUTS = ["horizontal", "vertical", "drawer-on-phone"];
1141
- var MAX_DEPTH = 3;
2323
+ var MAX_DEPTH2 = 3;
1142
2324
  function List({ items, mediaOrigin, depth = 0, id, onNavigate }) {
1143
- const shown = items.flatMap((item) => {
1144
- const href = safeUrl9(item.href, "href", { mediaOrigin });
2325
+ const shown2 = items.flatMap((item) => {
2326
+ const href = safeUrl10(item.href, "href", { mediaOrigin });
1145
2327
  return href === null ? [] : [{ item, href }];
1146
2328
  });
1147
- if (shown.length === 0) return null;
1148
- return /* @__PURE__ */ jsx15("ul", { ...id === void 0 ? {} : { id }, ...onNavigate === void 0 ? {} : { onClick: onNavigate }, children: shown.map(({ item, href }, index) => /* @__PURE__ */ jsxs9("li", { children: [
1149
- /* @__PURE__ */ jsx15("a", { href, children: item.label }),
1150
- depth + 1 < MAX_DEPTH && item.children !== void 0 && /* @__PURE__ */ jsx15(List, { items: item.children, mediaOrigin, depth: depth + 1 })
2329
+ if (shown2.length === 0) return null;
2330
+ return /* @__PURE__ */ jsx26("ul", { ...id === void 0 ? {} : { id }, ...onNavigate === void 0 ? {} : { onClick: onNavigate }, children: shown2.map(({ item, href }, index) => /* @__PURE__ */ jsxs16("li", { children: [
2331
+ /* @__PURE__ */ jsx26("a", { href, children: item.label }),
2332
+ depth + 1 < MAX_DEPTH2 && item.children !== void 0 && /* @__PURE__ */ jsx26(List, { items: item.children, mediaOrigin, depth: depth + 1 })
1151
2333
  ] }, `${String(index)}:${href}`)) });
1152
2334
  }
1153
2335
  function Menu({ props, mediaOrigin, editMode }) {
1154
2336
  const design = useSiteDesign4();
1155
2337
  const listId = useId();
1156
- const toggle = useRef(null);
2338
+ const toggle = useRef2(null);
1157
2339
  const [open, setOpen] = useState3(false);
1158
2340
  const name = str(props.menu) ?? "header";
1159
2341
  const layout = oneOf(props.layout, LAYOUTS, "horizontal");
@@ -1162,9 +2344,9 @@ function Menu({ props, mediaOrigin, editMode }) {
1162
2344
  const strings = design?.strings;
1163
2345
  const label = (strings !== void 0 && Object.hasOwn(strings, "nav.menu") ? str(strings["nav.menu"]) : void 0) ?? SITE_STRING_DEFAULTS3["nav.menu"];
1164
2346
  if (items === void 0 || items.length === 0) {
1165
- return /* @__PURE__ */ jsxs9(Fragment9, { children: [
1166
- /* @__PURE__ */ jsx15(BasicStyles, {}),
1167
- /* @__PURE__ */ jsx15(Placeholder, { editMode, children: `Menu "${name}" is empty: add links in Site settings` })
2347
+ return /* @__PURE__ */ jsxs16(Fragment12, { children: [
2348
+ /* @__PURE__ */ jsx26(BasicStyles, {}),
2349
+ /* @__PURE__ */ jsx26(Placeholder, { editMode, children: `Menu "${name}" is empty: add links in Site settings` })
1168
2350
  ] });
1169
2351
  }
1170
2352
  const drawer = layout === "drawer-on-phone";
@@ -1174,9 +2356,9 @@ function Menu({ props, mediaOrigin, editMode }) {
1174
2356
  toggle.current?.focus();
1175
2357
  }
1176
2358
  };
1177
- return /* @__PURE__ */ jsxs9(Fragment9, { children: [
1178
- /* @__PURE__ */ jsx15(BasicStyles, {}),
1179
- /* @__PURE__ */ jsxs9(
2359
+ return /* @__PURE__ */ jsxs16(Fragment12, { children: [
2360
+ /* @__PURE__ */ jsx26(BasicStyles, {}),
2361
+ /* @__PURE__ */ jsxs16(
1180
2362
  "nav",
1181
2363
  {
1182
2364
  className: `tb-b-menu tb-b-menu--${layout}${layout === "vertical" ? "" : " tb-b-menu--h"}`,
@@ -1184,7 +2366,7 @@ function Menu({ props, mediaOrigin, editMode }) {
1184
2366
  "data-open": drawer ? String(open) : void 0,
1185
2367
  onKeyDown: drawer ? onKeyDown : void 0,
1186
2368
  children: [
1187
- drawer && /* @__PURE__ */ jsx15(
2369
+ drawer && /* @__PURE__ */ jsx26(
1188
2370
  "button",
1189
2371
  {
1190
2372
  ref: toggle,
@@ -1193,10 +2375,10 @@ function Menu({ props, mediaOrigin, editMode }) {
1193
2375
  "aria-expanded": open,
1194
2376
  "aria-controls": listId,
1195
2377
  onClick: () => setOpen((value) => !value),
1196
- children: /* @__PURE__ */ jsx15(Icon2, { name: open ? "close" : "menu", size: 24, label })
2378
+ children: /* @__PURE__ */ jsx26(Icon2, { name: open ? "close" : "menu", size: 24, label })
1197
2379
  }
1198
2380
  ),
1199
- /* @__PURE__ */ jsx15(List, { items, mediaOrigin, id: listId, ...drawer ? { onNavigate: () => setOpen(false) } : {} })
2381
+ /* @__PURE__ */ jsx26(List, { items, mediaOrigin, id: listId, ...drawer ? { onNavigate: () => setOpen(false) } : {} })
1200
2382
  ]
1201
2383
  }
1202
2384
  )
@@ -1204,18 +2386,18 @@ function Menu({ props, mediaOrigin, editMode }) {
1204
2386
  }
1205
2387
 
1206
2388
  // src/basics/spacer.tsx
1207
- import { Fragment as Fragment10, jsx as jsx16, jsxs as jsxs10 } from "react/jsx-runtime";
2389
+ import { Fragment as Fragment13, jsx as jsx27, jsxs as jsxs17 } from "react/jsx-runtime";
1208
2390
  function Spacer() {
1209
- return /* @__PURE__ */ jsxs10(Fragment10, { children: [
1210
- /* @__PURE__ */ jsx16(BasicStyles, {}),
1211
- /* @__PURE__ */ jsx16("div", { className: "tb-b-spacer", "aria-hidden": "true" })
2391
+ return /* @__PURE__ */ jsxs17(Fragment13, { children: [
2392
+ /* @__PURE__ */ jsx27(BasicStyles, {}),
2393
+ /* @__PURE__ */ jsx27("div", { className: "tb-b-spacer", "aria-hidden": "true" })
1212
2394
  ] });
1213
2395
  }
1214
2396
 
1215
2397
  // src/basics/rich-text.tsx
1216
- import { Fragment as Fragment11, createElement } from "react";
1217
- import { safeUrl as safeUrl10 } from "@usethrottle/builder-schema";
1218
- import { jsx as jsx17, jsxs as jsxs11 } from "react/jsx-runtime";
2398
+ import { Fragment as Fragment14, createElement as createElement2 } from "react";
2399
+ import { safeUrl as safeUrl11 } from "@usethrottle/builder-schema";
2400
+ import { jsx as jsx28, jsxs as jsxs18 } from "react/jsx-runtime";
1219
2401
  var ALLOWED = /* @__PURE__ */ new Set(["p", "br", "strong", "em", "u", "s", "a", "ul", "ol", "li", "h2", "h3", "h4", "blockquote", "code"]);
1220
2402
  var ALIAS = { b: "strong", i: "em", strike: "s", del: "s" };
1221
2403
  var DROP_WITH_CONTENT = /* @__PURE__ */ new Set([
@@ -1240,7 +2422,7 @@ var VOID = /* @__PURE__ */ new Set(["br"]);
1240
2422
  var BLOCK = /* @__PURE__ */ new Set(["p", "h2", "h3", "h4", "ul", "ol", "blockquote"]);
1241
2423
  var TEXT_BLOCK = /* @__PURE__ */ new Set(["p", "h2", "h3", "h4"]);
1242
2424
  var MAX_LENGTH = 2e4;
1243
- var MAX_DEPTH2 = 24;
2425
+ var MAX_DEPTH3 = 24;
1244
2426
  var MAX_NODES = 4e3;
1245
2427
  var NAMED = {
1246
2428
  amp: "&",
@@ -1384,23 +2566,23 @@ function parseRichText(source, mediaOrigin) {
1384
2566
  const el = { tag: name, children: [] };
1385
2567
  if (name === "a") {
1386
2568
  const href = tag.attrs.get("href");
1387
- el.href = href === void 0 ? null : safeUrl10(decode(href).trim(), "href", { mediaOrigin });
2569
+ el.href = href === void 0 ? null : safeUrl11(decode(href).trim(), "href", { mediaOrigin });
1388
2570
  }
1389
2571
  nodes += 1;
1390
2572
  top().children.push(el);
1391
- if (!VOID.has(name) && stack.length < MAX_DEPTH2) stack.push(el);
2573
+ if (!VOID.has(name) && stack.length < MAX_DEPTH3) stack.push(el);
1392
2574
  }
1393
2575
  if (nodes > MAX_NODES) root.truncated = true;
1394
2576
  return root;
1395
2577
  }
1396
2578
  function toReact(el, key) {
1397
2579
  const children = el.children.map((child, index) => typeof child === "string" ? child : toReact(child, index));
1398
- if (el.tag === "br") return /* @__PURE__ */ jsx17("br", {}, key);
2580
+ if (el.tag === "br") return /* @__PURE__ */ jsx28("br", {}, key);
1399
2581
  if (el.tag === "a") {
1400
- if (el.href === null || el.href === void 0) return /* @__PURE__ */ jsx17(Fragment11, { children }, key);
1401
- return /* @__PURE__ */ jsx17("a", { href: el.href, rel: "noopener noreferrer", className: "tb-b-link", children }, key);
2582
+ if (el.href === null || el.href === void 0) return /* @__PURE__ */ jsx28(Fragment14, { children }, key);
2583
+ return /* @__PURE__ */ jsx28("a", { href: el.href, rel: "noopener noreferrer", className: "tb-b-link", children }, key);
1402
2584
  }
1403
- return createElement(el.tag, { key }, ...children);
2585
+ return createElement2(el.tag, { key }, ...children);
1404
2586
  }
1405
2587
  function RichText({
1406
2588
  html,
@@ -1409,26 +2591,26 @@ function RichText({
1409
2591
  editMode = false
1410
2592
  }) {
1411
2593
  const tree = parseRichText(html, mediaOrigin);
1412
- return /* @__PURE__ */ jsxs11("div", { className, children: [
2594
+ return /* @__PURE__ */ jsxs18("div", { className, children: [
1413
2595
  tree.children.map((child, index) => typeof child === "string" ? child : toReact(child, index)),
1414
- 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." })
2596
+ editMode && tree.truncated === true && /* @__PURE__ */ jsx28("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." })
1415
2597
  ] });
1416
2598
  }
1417
2599
 
1418
2600
  // src/basics/text.tsx
1419
- import { Fragment as Fragment12, jsx as jsx18, jsxs as jsxs12 } from "react/jsx-runtime";
2601
+ import { Fragment as Fragment15, jsx as jsx29, jsxs as jsxs19 } from "react/jsx-runtime";
1420
2602
  function Text({ props, mediaOrigin, editMode, inlineEdit }) {
1421
2603
  const editor = inlineEdit?.("html") ?? null;
1422
- return /* @__PURE__ */ jsxs12(Fragment12, { children: [
1423
- /* @__PURE__ */ jsx18(BasicStyles, {}),
1424
- editor === null ? /* @__PURE__ */ jsx18(RichText, { html: str(props.html) ?? "", mediaOrigin, className: "tb-b-text", editMode }) : /* @__PURE__ */ jsx18("div", { className: "tb-b-text", children: editor })
2604
+ return /* @__PURE__ */ jsxs19(Fragment15, { children: [
2605
+ /* @__PURE__ */ jsx29(BasicStyles, {}),
2606
+ editor === null ? /* @__PURE__ */ jsx29(RichText, { html: str(props.html) ?? "", mediaOrigin, className: "tb-b-text", editMode }) : /* @__PURE__ */ jsx29("div", { className: "tb-b-text", children: editor })
1425
2607
  ] });
1426
2608
  }
1427
2609
 
1428
2610
  // src/basics/video.tsx
1429
2611
  import { useState as useState4 } from "react";
1430
2612
  import { Icon as Icon3 } from "@usethrottle/ui";
1431
- import { Fragment as Fragment13, jsx as jsx19, jsxs as jsxs13 } from "react/jsx-runtime";
2613
+ import { Fragment as Fragment16, jsx as jsx30, jsxs as jsxs20 } from "react/jsx-runtime";
1432
2614
  var RULES3 = [
1433
2615
  { key: "ratio", property: "--bx-ratio", values: { "16:9": "16 / 9", "4:3": "4 / 3", "1:1": "1 / 1", "9:16": "9 / 16" } }
1434
2616
  ];
@@ -1470,10 +2652,10 @@ function embedSrc(video, muted) {
1470
2652
  function Video({ node, props, editMode }) {
1471
2653
  const [loaded, setLoaded] = useState4(false);
1472
2654
  const video = parseVideoUrl(str(props.url) ?? "");
1473
- return /* @__PURE__ */ jsxs13(Fragment13, { children: [
1474
- /* @__PURE__ */ jsx19(BasicStyles, {}),
1475
- /* @__PURE__ */ jsx19(WidgetStyle, { css: enumCss(node, RULES3) }),
1476
- 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(
2655
+ return /* @__PURE__ */ jsxs20(Fragment16, { children: [
2656
+ /* @__PURE__ */ jsx30(BasicStyles, {}),
2657
+ /* @__PURE__ */ jsx30(WidgetStyle, { css: enumCss(node, RULES3) }),
2658
+ video === null ? /* @__PURE__ */ jsx30(Placeholder, { editMode, children: "Paste a YouTube or Vimeo link" }) : /* @__PURE__ */ jsx30("div", { className: "tb-b-video", "data-provider": video.provider, children: loaded && !editMode ? /* @__PURE__ */ jsx30(
1477
2659
  "iframe",
1478
2660
  {
1479
2661
  src: embedSrc(video, props.autoplayMuted === true),
@@ -1482,7 +2664,7 @@ function Video({ node, props, editMode }) {
1482
2664
  referrerPolicy: "strict-origin-when-cross-origin",
1483
2665
  sandbox: "allow-scripts allow-same-origin allow-presentation allow-popups"
1484
2666
  }
1485
- ) : /* @__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 }) }) }) })
2667
+ ) : /* @__PURE__ */ jsx30("button", { type: "button", className: "tb-b-play", "aria-label": "Play video", onClick: () => setLoaded(true), children: /* @__PURE__ */ jsx30("span", { children: /* @__PURE__ */ jsx30(Icon3, { name: "play", size: 28 }) }) }) })
1486
2668
  ] });
1487
2669
  }
1488
2670
 
@@ -1498,7 +2680,8 @@ var BASIC_COMPONENTS = {
1498
2680
  "basic.logo": Logo,
1499
2681
  "basic.menu": Menu,
1500
2682
  "basic.announcement": Announcement,
1501
- "basic.copyright": Copyright
2683
+ "basic.copyright": Copyright,
2684
+ "basic.countdown": Countdown
1502
2685
  };
1503
2686
  var widgets = BASIC_WIDGET_DEFINITIONS2.flatMap(
1504
2687
  (definition) => Object.hasOwn(BASIC_COMPONENTS, definition.type) ? [{ ...definition, Component: BASIC_COMPONENTS[definition.type] }] : []
@@ -1509,289 +2692,27 @@ var basicPack = { id: "basic", version: "0.0.0", widgets, dataSources: [] };
1509
2692
  import { createElement as createElement3 } from "react";
1510
2693
 
1511
2694
  // src/custom/composite-widget.tsx
1512
- import { Suspense as Suspense2 } from "react";
2695
+ import { Suspense as Suspense3 } from "react";
1513
2696
  import { pageDocumentSchema, validateSettingValue as validateSettingValue3 } from "@usethrottle/builder-schema";
1514
-
1515
- // src/custom/template-widget.tsx
1516
- import { Suspense } from "react";
1517
- import { MAX_TEMPLATE_WEIGHT as MAX_TEMPLATE_WEIGHT2, parseTemplate, templateWeight as templateWeight2, validateTemplate } from "@usethrottle/builder-schema";
1518
-
1519
- // src/custom/custom-css.tsx
1520
- import { sanitizeWidgetCss } from "@usethrottle/builder-schema";
1521
- import { jsx as jsx20 } from "react/jsx-runtime";
1522
- function scopedCss(source, type) {
1523
- if (source === void 0 || source === "") return "";
1524
- if (typeof source !== "string") return null;
1525
- const result = sanitizeWidgetCss(source, type);
1526
- return result.ok ? result.css : null;
1527
- }
1528
- function CustomCss({ css }) {
1529
- return /* @__PURE__ */ jsx20(WidgetStyle, { css });
1530
- }
1531
-
1532
- // src/custom/interpreter.tsx
1533
- import { Fragment as Fragment14, createElement as createElement2 } from "react";
1534
- import {
1535
- ALLOWED_ATTRS,
1536
- ALLOWED_ELEMENTS,
1537
- ALLOWED_ROLES,
1538
- CLASS_TOKEN_RE,
1539
- DATA_ATTR_RE,
1540
- EACH_ITERATION_CAP,
1541
- RESERVED_DATA_PREFIX,
1542
- VOID_ELEMENTS,
1543
- isReservedClass,
1544
- safeUrl as safeUrl11
1545
- } from "@usethrottle/builder-schema";
1546
- import { jsx as jsx21 } from "react/jsx-runtime";
1547
- var MAX_OUTPUT_CHARS = 1e6;
1548
- var MAX_ATTR_CHARS = 2e3;
1549
- var MAX_DEPTH3 = 24;
1550
- function newEnv(env) {
1551
- return { ...env, charsLeft: MAX_OUTPUT_CHARS, stopped: false };
1552
- }
1553
- var BLOCKED = /* @__PURE__ */ new Set([
1554
- "__proto__",
1555
- "constructor",
1556
- "prototype",
1557
- ...Object.getOwnPropertyNames(Object.prototype)
1558
- ]);
1559
- var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1560
- function step(value, key) {
1561
- if (BLOCKED.has(key) || !isPlainObject(value) || !Object.hasOwn(value, key)) return void 0;
1562
- return value[key];
1563
- }
1564
- function lookup(path, env, scope) {
1565
- const [root, ...rest] = path;
1566
- if (root === void 0) return void 0;
1567
- if (root === "locale") return rest.length === 0 ? env.locale : void 0;
1568
- let value;
1569
- if (root === "settings") value = rest.length === 0 ? void 0 : env.settings;
1570
- else if (root === "data") value = rest.length === 0 ? void 0 : env.data;
1571
- else if (scope.has(root)) value = scope.get(root);
1572
- else return void 0;
1573
- for (const key of rest) {
1574
- value = step(value, key);
1575
- if (value === void 0) return void 0;
1576
- }
1577
- return value;
1578
- }
1579
- function truthy(value) {
1580
- if (value === null || value === void 0 || value === false || value === "") return false;
1581
- if (typeof value === "number") return value !== 0 && !Number.isNaN(value);
1582
- if (Array.isArray(value)) return value.length > 0;
1583
- return true;
1584
- }
1585
- function asText(value) {
1586
- if (typeof value === "string") return value;
1587
- if (typeof value === "number" && Number.isFinite(value)) return String(value);
1588
- return "";
1589
- }
1590
- function filtered(value, filters) {
1591
- let text = asText(value);
1592
- for (const filter of filters) {
1593
- switch (filter.name) {
1594
- case "upper":
1595
- text = text.toUpperCase();
1596
- break;
1597
- case "lower":
1598
- text = text.toLowerCase();
1599
- break;
1600
- case "truncate": {
1601
- const chars = Array.from(text);
1602
- if (chars.length > filter.n) text = `${chars.slice(0, filter.n).join("")}\u2026`;
1603
- break;
1604
- }
1605
- case "default":
1606
- if (text === "") text = filter.text;
1607
- break;
1608
- }
1609
- }
1610
- return text;
1611
- }
1612
- function spend(env, count) {
1613
- if (count > env.charsLeft) {
1614
- env.stopped = true;
1615
- return false;
1616
- }
1617
- env.charsLeft -= count;
1618
- return true;
1619
- }
1620
- var ELEMENTS = new Set(ALLOWED_ELEMENTS);
1621
- var VOIDS = new Set(VOID_ELEMENTS);
1622
- var ROLES = new Set(ALLOWED_ROLES);
1623
- function attrAllowed(tag, name) {
1624
- if (DATA_ATTR_RE.test(name)) return !name.startsWith(RESERVED_DATA_PREFIX);
1625
- const own = Object.hasOwn(ALLOWED_ATTRS, tag) ? ALLOWED_ATTRS[tag] : void 0;
1626
- return (ALLOWED_ATTRS["*"]?.includes(name) ?? false) || (own?.includes(name) ?? false);
1627
- }
1628
- function attrText(attr, env, scope) {
1629
- return attr.value.map((part) => part.type === "text" ? part.value : filtered(lookup(part.path, env, scope), part.filters)).join("");
1630
- }
1631
- function urlSource(attr, env, scope) {
1632
- const [only] = attr.value;
1633
- if (attr.value.length !== 1 || only === void 0 || only.type !== "output") return attrText(attr, env, scope);
1634
- const value = lookup(only.path, env, scope);
1635
- if (isPlainObject(value)) {
1636
- if (typeof value.href === "string") return value.href;
1637
- if (typeof value.url === "string") return value.url;
1638
- return null;
1639
- }
1640
- return value;
1641
- }
1642
- function attrProp(tag, attr, env, scope) {
1643
- const { name } = attr;
1644
- if (!attrAllowed(tag, name)) return null;
1645
- if (name === "href" || name === "src") {
1646
- const safe = safeUrl11(urlSource(attr, env, scope), name, { mediaOrigin: env.mediaOrigin });
1647
- return safe === null || !spend(env, safe.length) ? null : [name, safe];
1648
- }
1649
- const text = attrText(attr, env, scope);
1650
- if (text === "" || text.length > MAX_ATTR_CHARS) return null;
1651
- let value = text;
1652
- if (name === "class") {
1653
- const tokens = text.split(/\s+/).filter((token) => CLASS_TOKEN_RE.test(token) && !isReservedClass(token));
1654
- if (tokens.length === 0) return null;
1655
- value = tokens.join(" ");
1656
- } else if (name === "role") {
1657
- if (!ROLES.has(text)) return null;
1658
- } else if (name === "aria-hidden") {
1659
- if (text !== "true" && text !== "false") return null;
1660
- }
1661
- if (!spend(env, value.length)) return null;
1662
- return [name === "class" ? "className" : name, value];
1663
- }
1664
- function renderElement(node, env, scope, depth, key) {
1665
- const tag = node.tag;
1666
- if (!ELEMENTS.has(tag)) return null;
1667
- const props = { key };
1668
- for (const attr of node.attrs) {
1669
- const prop = attrProp(tag, attr, env, scope);
1670
- if (prop !== null) props[prop[0]] = prop[1];
1671
- }
1672
- if (VOIDS.has(tag)) return createElement2(tag, props);
1673
- return createElement2(tag, props, renderNodes(node.children, env, scope, depth + 1));
1674
- }
1675
- function renderNodes(nodes, env, scope, depth) {
1676
- const out = [];
1677
- if (depth > MAX_DEPTH3) return out;
1678
- for (const node of nodes) {
1679
- if (env.stopped) break;
1680
- if (!env.budget.take(1) || node.type === "element" && !env.budget.take(node.attrs.reduce((n, a) => n + a.value.length, 0))) {
1681
- env.stopped = true;
1682
- break;
1683
- }
1684
- switch (node.type) {
1685
- case "text":
1686
- if (spend(env, node.value.length)) out.push(node.value);
1687
- break;
1688
- case "output": {
1689
- const text = filtered(lookup(node.path, env, scope), node.filters);
1690
- if (text !== "" && spend(env, text.length)) out.push(text);
1691
- break;
1692
- }
1693
- case "if": {
1694
- const branch = truthy(lookup(node.path, env, scope)) ? node.then : node.else;
1695
- out.push(/* @__PURE__ */ jsx21(Fragment14, { children: renderNodes(branch, env, scope, depth + 1) }, out.length));
1696
- break;
1697
- }
1698
- case "unless":
1699
- if (!truthy(lookup(node.path, env, scope))) {
1700
- out.push(/* @__PURE__ */ jsx21(Fragment14, { children: renderNodes(node.body, env, scope, depth + 1) }, out.length));
1701
- }
1702
- break;
1703
- case "each": {
1704
- const list = lookup(node.path, env, scope);
1705
- if (!Array.isArray(list)) break;
1706
- const count = Math.min(list.length, EACH_ITERATION_CAP);
1707
- for (let i = 0; i < count && !env.stopped; i += 1) {
1708
- const inner = new Map(scope).set(node.as, list[i]);
1709
- out.push(/* @__PURE__ */ jsx21(Fragment14, { children: renderNodes(node.body, env, inner, depth + 1) }, out.length));
1710
- }
1711
- break;
1712
- }
1713
- case "element":
1714
- out.push(renderElement(node, env, scope, depth, out.length));
1715
- break;
1716
- }
1717
- }
1718
- return out;
1719
- }
1720
- function renderTemplate(ast, env) {
1721
- return renderNodes(ast, env, /* @__PURE__ */ new Map(), 0);
1722
- }
1723
-
1724
- // src/custom/template-widget.tsx
1725
- import { Fragment as Fragment15, jsx as jsx22, jsxs as jsxs14 } from "react/jsx-runtime";
1726
- var componentWeights = /* @__PURE__ */ new WeakMap();
1727
- var compiled = /* @__PURE__ */ new WeakMap();
1728
- function compileTemplate(snapshot, registry) {
1729
- let perRegistry = compiled.get(snapshot);
1730
- if (perRegistry === void 0) {
1731
- perRegistry = /* @__PURE__ */ new WeakMap();
1732
- compiled.set(snapshot, perRegistry);
1733
- }
1734
- if (perRegistry.has(registry)) return perRegistry.get(registry) ?? null;
1735
- const result = compile(snapshot, registry);
1736
- perRegistry.set(registry, result);
1737
- return result;
1738
- }
1739
- function compile(snapshot, registry) {
1740
- const label = `${snapshot.type}@${String(snapshot.v)}`;
1741
- const refuse = (why) => {
1742
- warnOnce(`template:${label}`, `${label} was refused (${why}); rendering nothing for it`);
1743
- return null;
1744
- };
1745
- if (snapshot.kind !== "template") return refuse("not a template widget");
1746
- const source = snapshot.template;
1747
- if (typeof source !== "string") return refuse("no template source");
1748
- const parsed = parseTemplate(source);
1749
- if (!parsed.ok) return refuse(`template does not parse: ${parsed.issues[0]?.message ?? "invalid"}`);
1750
- const data = snapshot.data;
1751
- const issues = validateTemplate(parsed.ast, {
1752
- settings: snapshot.settings,
1753
- data: typeof data === "object" && data !== null ? data : {},
1754
- sources: registry.sources()
1755
- });
1756
- if (issues.length > 0) return refuse(`template does not validate: ${issues[0]?.message ?? "invalid"}`);
1757
- if (!fitsBudget(parsed.ast)) return refuse(`it can render more than ${String(MAX_TEMPLATE_WEIGHT2)} nodes`);
1758
- const css = scopedCss(snapshot.css, snapshot.type);
1759
- if (css === null) return refuse("its css does not pass the sanitiser");
1760
- return { ast: parsed.ast, css, weight: templateWeight2(parsed.ast) };
1761
- }
1762
- function TemplateBody({ snapshot, registry, props, data, locale, mediaOrigin, budget }) {
1763
- const template = compileTemplate(snapshot, registry);
1764
- if (template === null) return null;
1765
- const env = newEnv({ settings: props, data, locale, mediaOrigin, budget: budget ?? new RenderBudget() });
1766
- return /* @__PURE__ */ jsxs14(Fragment15, { children: [
1767
- template.css === "" ? null : /* @__PURE__ */ jsx22(CustomCss, { css: template.css }),
1768
- renderTemplate(template.ast, env)
1769
- ] });
1770
- }
1771
- function TemplateWidget(props) {
1772
- return /* @__PURE__ */ jsx22(PartBoundary, { label: `${props.snapshot.type}@${String(props.snapshot.v)}`, children: /* @__PURE__ */ jsx22(Suspense, { fallback: null, children: /* @__PURE__ */ jsx22(TemplateBody, { ...props }) }) });
1773
- }
1774
-
1775
- // src/custom/composite-widget.tsx
1776
- import { jsx as jsx23 } from "react/jsx-runtime";
2697
+ import { jsx as jsx31 } from "react/jsx-runtime";
1777
2698
  var SETTING_KEY_RE = /^[a-z][A-Za-z0-9]{0,39}$/;
1778
2699
  var NODE_ID_RE = /^[a-z0-9]{8,24}$/;
1779
2700
  var WRAP = { section: "zzcompsec001", column: "zzcompcol001", inner: "zzcompinr001" };
1780
- var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1781
- var compiled2 = /* @__PURE__ */ new WeakMap();
2701
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2702
+ var compiled3 = /* @__PURE__ */ new WeakMap();
1782
2703
  function parseBody(raw) {
1783
- if (!isRecord3(raw)) return null;
2704
+ if (!isRecord4(raw)) return null;
1784
2705
  const columns = Array.isArray(raw.columns) ? raw.columns : void 0;
1785
2706
  const stack = Array.isArray(raw.stack) ? raw.stack : void 0;
1786
2707
  if (columns === void 0 === (stack === void 0)) return null;
1787
2708
  const children = columns !== void 0 ? [{ id: WRAP.inner, type: "inner-section", props: {}, columns }] : stack ?? [];
1788
- if (stack?.some((node) => isRecord3(node) && node.type === "inner-section")) return null;
1789
- const parsed = pageDocumentSchema.safeParse({
2709
+ if (stack?.some((node) => isRecord4(node) && node.type === "inner-section")) return null;
2710
+ const parsed2 = pageDocumentSchema.safeParse({
1790
2711
  schemaVersion: 1,
1791
2712
  sections: [{ id: WRAP.section, type: "section", props: {}, columns: [{ id: WRAP.column, type: "column", props: { width: 100 }, children }] }]
1792
2713
  });
1793
- if (!parsed.success) return null;
1794
- const wrapper = parsed.data.sections[0];
2714
+ if (!parsed2.success) return null;
2715
+ const wrapper = parsed2.data.sections[0];
1795
2716
  const first = (wrapper?.type === "section" ? wrapper.columns[0]?.children : void 0) ?? [];
1796
2717
  if (columns !== void 0) {
1797
2718
  const inner = first[0];
@@ -1800,9 +2721,9 @@ function parseBody(raw) {
1800
2721
  return { stack: first.filter((node) => node.type !== "inner-section") };
1801
2722
  }
1802
2723
  function compileComposite(snapshot) {
1803
- if (compiled2.has(snapshot)) return compiled2.get(snapshot) ?? null;
2724
+ if (compiled3.has(snapshot)) return compiled3.get(snapshot) ?? null;
1804
2725
  const result = compile2(snapshot);
1805
- compiled2.set(snapshot, result);
2726
+ compiled3.set(snapshot, result);
1806
2727
  return result;
1807
2728
  }
1808
2729
  function compile2(snapshot) {
@@ -1818,12 +2739,12 @@ function compile2(snapshot) {
1818
2739
  const bindings = [];
1819
2740
  if (extra.bindings !== void 0 && !Array.isArray(extra.bindings)) return refuse("bindings is not a list");
1820
2741
  for (const raw of extra.bindings ?? []) {
1821
- if (!isRecord3(raw) || typeof raw.setting !== "string" || !SETTING_KEY_RE.test(raw.setting) || !Array.isArray(raw.targets)) {
2742
+ if (!isRecord4(raw) || typeof raw.setting !== "string" || !SETTING_KEY_RE.test(raw.setting) || !Array.isArray(raw.targets)) {
1822
2743
  return refuse("a binding is malformed");
1823
2744
  }
1824
2745
  const targets = [];
1825
2746
  for (const target of raw.targets) {
1826
- if (!isRecord3(target) || typeof target.node !== "string" || !NODE_ID_RE.test(target.node) || typeof target.prop !== "string" || !SETTING_KEY_RE.test(target.prop)) {
2747
+ if (!isRecord4(target) || typeof target.node !== "string" || !NODE_ID_RE.test(target.node) || typeof target.prop !== "string" || !SETTING_KEY_RE.test(target.prop)) {
1827
2748
  return refuse("a binding target is malformed");
1828
2749
  }
1829
2750
  targets.push({ node: target.node, prop: target.prop });
@@ -1831,12 +2752,12 @@ function compile2(snapshot) {
1831
2752
  bindings.push({ setting: raw.setting, targets });
1832
2753
  }
1833
2754
  const data = [];
1834
- if (extra.data !== void 0 && !isRecord3(extra.data)) return refuse("data is not a record");
2755
+ if (extra.data !== void 0 && !isRecord4(extra.data)) return refuse("data is not a record");
1835
2756
  for (const [name, raw] of Object.entries(extra.data ?? {})) {
1836
- if (!SETTING_KEY_RE.test(name) || !isRecord3(raw) || !Array.isArray(raw.targets)) return refuse("a data input is malformed");
2757
+ if (!SETTING_KEY_RE.test(name) || !isRecord4(raw) || !Array.isArray(raw.targets)) return refuse("a data input is malformed");
1837
2758
  const targets = [];
1838
2759
  for (const target of raw.targets) {
1839
- if (!isRecord3(target) || typeof target.node !== "string" || !NODE_ID_RE.test(target.node) || typeof target.input !== "string" || !SETTING_KEY_RE.test(target.input)) {
2760
+ if (!isRecord4(target) || typeof target.node !== "string" || !NODE_ID_RE.test(target.node) || typeof target.input !== "string" || !SETTING_KEY_RE.test(target.input)) {
1840
2761
  return refuse("a data target is malformed");
1841
2762
  }
1842
2763
  targets.push({ node: target.node, input: target.input });
@@ -1892,7 +2813,7 @@ function build(input) {
1892
2813
  return id;
1893
2814
  }
1894
2815
  if (field.control === "link") {
1895
- if (!isRecord3(value) || typeof value.kind !== "string") return null;
2816
+ if (!isRecord4(value) || typeof value.kind !== "string") return null;
1896
2817
  const { href, ...target } = value;
1897
2818
  if (target.kind === "url") return typeof href === "string" ? { kind: "url", href } : null;
1898
2819
  hrefs.set(JSON.stringify(target), typeof href === "string" ? href : null);
@@ -1943,7 +2864,7 @@ function build(input) {
1943
2864
  props: { width: 100 },
1944
2865
  children: columns !== void 0 ? [{ id: ids.inner, type: "inner-section", props: { width: "full" }, columns }] : stack ?? []
1945
2866
  };
1946
- const document = {
2867
+ const document2 = {
1947
2868
  schemaVersion: 1,
1948
2869
  sections: [{ id: ids.section, type: "section", props: { width: "full" }, columns: [column] }]
1949
2870
  };
@@ -1952,10 +2873,10 @@ function build(input) {
1952
2873
  const component = registry.component(widget);
1953
2874
  weight += 1 + (component === void 0 ? 0 : componentWeights.get(component) ?? 0);
1954
2875
  }
1955
- return { document, assets, data: innerData, hrefs, weight };
2876
+ return { document: document2, assets, data: innerData, hrefs, weight };
1956
2877
  }
1957
2878
  function CompositeBody(props) {
1958
- const { snapshot, registry, node, data, locale, mediaOrigin, budget, resolveLink } = props;
2879
+ const { snapshot, registry, node, data, locale, mediaOrigin, budget, resolveLink, interactive, idScope } = props;
1959
2880
  const composite = compileComposite(snapshot);
1960
2881
  if (composite === null) return null;
1961
2882
  const built = build({ snapshot, compiled: composite, registry, node, props: props.props, data });
@@ -1963,7 +2884,7 @@ function CompositeBody(props) {
1963
2884
  warnOnce(`composite-weight:${snapshot.type}@${String(snapshot.v)}`, `${snapshot.type} would render too many nodes; rendering nothing for it`);
1964
2885
  return null;
1965
2886
  }
1966
- return /* @__PURE__ */ jsx23(
2887
+ return /* @__PURE__ */ jsx31(
1967
2888
  BuilderRenderer,
1968
2889
  {
1969
2890
  document: built.document,
@@ -1972,12 +2893,14 @@ function CompositeBody(props) {
1972
2893
  locale,
1973
2894
  assets: built.assets,
1974
2895
  mediaOrigin,
2896
+ interactive,
2897
+ idScope,
1975
2898
  resolveLink: (target) => built.hrefs.get(JSON.stringify(target)) ?? resolveLink?.(target) ?? null
1976
2899
  }
1977
2900
  );
1978
2901
  }
1979
2902
  function CompositeWidget(props) {
1980
- return /* @__PURE__ */ jsx23(PartBoundary, { label: `${props.snapshot.type}@${String(props.snapshot.v)}`, children: /* @__PURE__ */ jsx23(Suspense2, { fallback: null, children: /* @__PURE__ */ jsx23(CompositeBody, { ...props }) }) });
2903
+ return /* @__PURE__ */ jsx31(PartBoundary, { label: `${props.snapshot.type}@${String(props.snapshot.v)}`, children: /* @__PURE__ */ jsx31(Suspense3, { fallback: null, children: /* @__PURE__ */ jsx31(CompositeBody, { ...props }) }) });
1981
2904
  }
1982
2905
 
1983
2906
  // src/custom/factory.ts
@@ -2001,12 +2924,12 @@ var BUILTIN_PACKS = [basicPack];
2001
2924
  var DEFAULT_CUSTOM_WIDGET = customWidgetFactory;
2002
2925
  var customKey = (type, v) => `${type}@${String(v)}`;
2003
2926
  function createRendererRegistry(packs, options = {}) {
2004
- const all = [...BUILTIN_PACKS, ...packs];
2927
+ const all2 = [...BUILTIN_PACKS, ...packs];
2005
2928
  const components = /* @__PURE__ */ new Map();
2006
2929
  const definitions = [];
2007
2930
  const sources = [];
2008
2931
  const resolvers = /* @__PURE__ */ new Map();
2009
- for (const pack of all) {
2932
+ for (const pack of all2) {
2010
2933
  for (const { Component: Component2, ...definition } of pack.widgets) {
2011
2934
  const key = customKey(definition.type, definition.v);
2012
2935
  if (components.has(key)) continue;
@@ -2037,7 +2960,7 @@ function createRendererRegistry(packs, options = {}) {
2037
2960
  if (own !== void 0) return own;
2038
2961
  if (!node.type.startsWith("custom.") || factory === void 0) return void 0;
2039
2962
  const snapshot = snapshots.get(key);
2040
- if (snapshot === void 0) return void 0;
2963
+ if (snapshot === void 0 || snapshot.kind === "code") return void 0;
2041
2964
  if (!built.has(key)) built.set(key, factory(snapshot, registry));
2042
2965
  return built.get(key) ?? void 0;
2043
2966
  },
@@ -2049,8 +2972,8 @@ function createRendererRegistry(packs, options = {}) {
2049
2972
  }
2050
2973
 
2051
2974
  // src/slot.tsx
2052
- import { Suspense as Suspense3 } from "react";
2053
- import { jsx as jsx24 } from "react/jsx-runtime";
2975
+ import { Suspense as Suspense4 } from "react";
2976
+ import { jsx as jsx32 } from "react/jsx-runtime";
2054
2977
  function contextKey(context) {
2055
2978
  if (typeof context !== "object" || context === null) return "";
2056
2979
  return Object.values(context).map((value) => {
@@ -2066,20 +2989,20 @@ function BuilderSlot({ name, context }) {
2066
2989
  if (part === void 0 || part.document.sections.length === 0) return null;
2067
2990
  return (
2068
2991
  // Suspense inside the boundary: see parts.tsx.
2069
- /* @__PURE__ */ jsx24(PartBoundary, { label: `Builder slot ${name}`, resetKey: contextKey(context), 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 }) }) }) })
2992
+ /* @__PURE__ */ jsx32(PartBoundary, { label: `Builder slot ${name}`, resetKey: contextKey(context), children: /* @__PURE__ */ jsx32("div", { "data-throttle-part": "builder-slot", "data-b-slot": name, children: /* @__PURE__ */ jsx32(Suspense4, { fallback: null, children: /* @__PURE__ */ jsx32(PartView, { part, context }) }) }) })
2070
2993
  );
2071
2994
  }
2072
2995
 
2073
2996
  // src/theme.ts
2074
- import { SITE_FONTS, safeUrl as safeUrl12 } from "@usethrottle/builder-schema";
2997
+ import { SITE_FONTS, THEME_CSS_MAX_CHARS, safeUrl as safeUrl12, sanitizeThemeCss } from "@usethrottle/builder-schema";
2075
2998
  import { PRESET_NAMES, PRESET_TOKENS } from "@usethrottle/ui/presets";
2076
- var isRecord4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
2999
+ var isRecord5 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
2077
3000
  var str2 = (v) => typeof v === "string" && v !== "" ? v : void 0;
2078
3001
  var HEX = /^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
2079
3002
  var SCALE = { compact: 0.85, comfortable: 1, roomy: 1.25 };
2080
3003
  var PALETTE_KEYS = Object.keys(PRESET_TOKENS.clean.light);
2081
3004
  function palette(base, over) {
2082
- if (!isRecord4(over)) return base;
3005
+ if (!isRecord5(over)) return base;
2083
3006
  const out = { ...base };
2084
3007
  for (const key of PALETTE_KEYS) {
2085
3008
  const value = over[key];
@@ -2088,13 +3011,13 @@ function palette(base, over) {
2088
3011
  return out;
2089
3012
  }
2090
3013
  function themeTokens(settings) {
2091
- const theme = isRecord4(settings.theme) ? settings.theme : {};
3014
+ const theme = isRecord5(settings.theme) ? settings.theme : {};
2092
3015
  const preset = PRESET_NAMES.includes(theme.preset) ? theme.preset : "clean";
2093
3016
  const customized = theme.customized === true;
2094
3017
  const base = PRESET_TOKENS[preset];
2095
3018
  const colorScheme = theme.colorScheme === "light" || theme.colorScheme === "dark" ? theme.colorScheme : "auto";
2096
3019
  if (!customized) return { preset, customized, tokens: base, colorScheme };
2097
- const fonts = isRecord4(theme.fonts) ? theme.fonts : {};
3020
+ const fonts = isRecord5(theme.fonts) ? theme.fonts : {};
2098
3021
  return {
2099
3022
  preset,
2100
3023
  customized,
@@ -2164,8 +3087,18 @@ function themeCss(settings) {
2164
3087
  if (colorScheme === "dark") return `${light}:root{${dark}}`;
2165
3088
  return `${light}@media (prefers-color-scheme:dark){:root{${dark}}}`;
2166
3089
  }
3090
+ function customCssOf(settings) {
3091
+ const theme = isRecord5(settings.theme) ? settings.theme : {};
3092
+ const css = theme.customCss;
3093
+ if (typeof css !== "string" || css.trim() === "" || css.length > THEME_CSS_MAX_CHARS) return "";
3094
+ const result = sanitizeThemeCss(css);
3095
+ return result.ok ? result.css : "";
3096
+ }
3097
+ function customCssSheet(css) {
3098
+ return css === "" ? "" : `@layer throttle,throttle-custom;@layer throttle-custom{${css}}`;
3099
+ }
2167
3100
  function makeResolveLink(settings, packs) {
2168
- const routes = isRecord4(settings.routes) ? settings.routes : {};
3101
+ const routes = isRecord5(settings.routes) ? settings.routes : {};
2169
3102
  const pageRoute = str2(routes.page) ?? "/pages/{handle}";
2170
3103
  return (target) => {
2171
3104
  for (const pack of packs) {
@@ -2188,7 +3121,7 @@ function menuItems(items, resolve, depth = 0) {
2188
3121
  if (!Array.isArray(items) || depth > 3) return [];
2189
3122
  const out = [];
2190
3123
  for (const item of items) {
2191
- if (!isRecord4(item) || !isRecord4(item.target) || typeof item.target.kind !== "string") continue;
3124
+ if (!isRecord5(item) || !isRecord5(item.target) || typeof item.target.kind !== "string") continue;
2192
3125
  const label = str2(item.label);
2193
3126
  const href = resolve(item.target);
2194
3127
  if (label === void 0 || href === null) continue;
@@ -2204,24 +3137,24 @@ function menuItems(items, resolve, depth = 0) {
2204
3137
  return out;
2205
3138
  }
2206
3139
  var assetUrl = (v, mediaOrigin) => {
2207
- const raw = typeof v === "string" ? v : isRecord4(v) ? v.url : void 0;
3140
+ const raw = typeof v === "string" ? v : isRecord5(v) ? v.url : void 0;
2208
3141
  return typeof raw === "string" ? safeUrl12(raw, "src", { mediaOrigin }) ?? void 0 : void 0;
2209
3142
  };
2210
3143
  function siteDesignOf(settings, resolve, pageOutlet, mediaOrigin) {
2211
3144
  const { preset, customized, tokens, colorScheme } = themeTokens(settings);
2212
- const brand = isRecord4(settings.brand) ? settings.brand : {};
2213
- const logo = isRecord4(brand.logo) ? brand.logo : {};
3145
+ const brand = isRecord5(settings.brand) ? settings.brand : {};
3146
+ const logo = isRecord5(brand.logo) ? brand.logo : {};
2214
3147
  const light = assetUrl(logo.light, mediaOrigin);
2215
3148
  const dark = assetUrl(logo.dark, mediaOrigin);
2216
3149
  const favicon = assetUrl(brand.favicon, mediaOrigin);
2217
- const menus = isRecord4(settings.menus) ? Object.fromEntries(Object.entries(settings.menus).map(([name, items]) => [name, menuItems(items, resolve)])) : {};
2218
- const announcement = isRecord4(settings.announcement) ? settings.announcement : null;
3150
+ const menus = isRecord5(settings.menus) ? Object.fromEntries(Object.entries(settings.menus).map(([name, items]) => [name, menuItems(items, resolve)])) : {};
3151
+ const announcement = isRecord5(settings.announcement) ? settings.announcement : null;
2219
3152
  const message = announcement === null ? void 0 : str2(announcement.message);
2220
- const announcementHref = announcement !== null && isRecord4(announcement.target) && typeof announcement.target.kind === "string" ? resolve(announcement.target) : null;
2221
- const strings = isRecord4(settings.strings) ? Object.fromEntries(Object.entries(settings.strings).filter((entry) => typeof entry[1] === "string")) : {};
2222
- const seo = isRecord4(settings.seo) ? settings.seo : {};
2223
- const routes = isRecord4(settings.routes) ? settings.routes : {};
2224
- const connections = isRecord4(settings.connections) ? settings.connections : {};
3153
+ const announcementHref = announcement !== null && isRecord5(announcement.target) && typeof announcement.target.kind === "string" ? resolve(announcement.target) : null;
3154
+ const strings = isRecord5(settings.strings) ? Object.fromEntries(Object.entries(settings.strings).filter((entry) => typeof entry[1] === "string")) : {};
3155
+ const seo = isRecord5(settings.seo) ? settings.seo : {};
3156
+ const routes = isRecord5(settings.routes) ? settings.routes : {};
3157
+ const connections = isRecord5(settings.connections) ? settings.connections : {};
2225
3158
  const shareImage = assetUrl(seo.shareImage, mediaOrigin);
2226
3159
  const titleTemplate = str2(seo.titleTemplate);
2227
3160
  const defaultDescription = str2(seo.defaultDescription);
@@ -2251,14 +3184,14 @@ function siteDesignOf(settings, resolve, pageOutlet, mediaOrigin) {
2251
3184
  }
2252
3185
 
2253
3186
  // src/provider.tsx
2254
- import { jsx as jsx25, jsxs as jsxs15 } from "react/jsx-runtime";
3187
+ import { jsx as jsx33, jsxs as jsxs21 } from "react/jsx-runtime";
2255
3188
  var EMPTY = {};
2256
3189
  function useParentFont() {
2257
3190
  return useContext2(AppearanceContext)?.variables?.fontFamily;
2258
3191
  }
2259
- function BuilderProvider({ builderKey, client, packs, site, onError, children }) {
3192
+ function BuilderProvider({ builderKey, client, packs, site, onError, interactive = true, pathname, catalogRoutes, mode = "live", children }) {
2260
3193
  const packsKey = packs.map((pack) => `${pack.id}@${pack.version}`).join("|");
2261
- const registryRef = useRef2(null);
3194
+ const registryRef = useRef3(null);
2262
3195
  if (registryRef.current?.key !== packsKey) {
2263
3196
  registryRef.current = { key: packsKey, registry: createRendererRegistry(packs) };
2264
3197
  }
@@ -2270,13 +3203,13 @@ function BuilderProvider({ builderKey, client, packs, site, onError, children })
2270
3203
  const mediaOrigin = site.status === "ok" ? site.mediaOrigin : "";
2271
3204
  const settings = site.status === "ok" ? site.settings : EMPTY;
2272
3205
  const resolveLink = useMemo(() => makeResolveLink(settings, packs), [settings, packs]);
2273
- const outlets = useRef2(/* @__PURE__ */ new Map());
2274
- const renderers = useRef2(/* @__PURE__ */ new Map());
3206
+ const outlets = useRef3(/* @__PURE__ */ new Map());
3207
+ const renderers = useRef3(/* @__PURE__ */ new Map());
2275
3208
  const pageOutlet = useCallback((handle) => {
2276
3209
  let outlet = outlets.current.get(handle);
2277
3210
  if (outlet === void 0) {
2278
3211
  outlet = function PageOutlet() {
2279
- return /* @__PURE__ */ jsx25(PartBoundary, { label: `Builder page ${handle}`, children: /* @__PURE__ */ jsx25(Suspense4, { fallback: null, children: /* @__PURE__ */ jsx25(BuilderPage, { slug: handle }) }) });
3212
+ return /* @__PURE__ */ jsx33(PartBoundary, { label: `Builder page ${handle}`, children: /* @__PURE__ */ jsx33(Suspense5, { fallback: null, children: /* @__PURE__ */ jsx33(BuilderPage, { slug: handle }) }) });
2280
3213
  };
2281
3214
  outlets.current.set(handle, outlet);
2282
3215
  }
@@ -2289,7 +3222,7 @@ function BuilderProvider({ builderKey, client, packs, site, onError, children })
2289
3222
  let renderer = renderers.current.get(name);
2290
3223
  if (renderer === void 0) {
2291
3224
  renderer = function SlotRenderer({ context }) {
2292
- return /* @__PURE__ */ jsx25(BuilderSlot, { name, context });
3225
+ return /* @__PURE__ */ jsx33(BuilderSlot, { name, context });
2293
3226
  };
2294
3227
  renderers.current.set(name, renderer);
2295
3228
  }
@@ -2297,9 +3230,20 @@ function BuilderProvider({ builderKey, client, packs, site, onError, children })
2297
3230
  },
2298
3231
  [site]
2299
3232
  );
3233
+ const customCss = useMemo(() => site.status === "ok" ? customCssOf(site.settings) : "", [site]);
3234
+ const configured = settings.routes?.page;
3235
+ const pageRoute = typeof configured === "string" ? configured : "/pages/{handle}";
3236
+ const catalogKey = catalogRoutes?.join("\n");
3237
+ const codeRoutes = useMemo(
3238
+ () => ({ page: pageRoute, ...catalogRoutes === void 0 ? {} : { catalog: catalogRoutes } }),
3239
+ // `catalogRoutes` is compared by value: a store passes a fresh array each render.
3240
+ [pageRoute, catalogKey]
3241
+ );
3242
+ useLeaveCodeRoutes(pathname, codeRoutes);
3243
+ const leaving = mustLeave(pathname, codeRoutes);
2300
3244
  const value = useMemo(
2301
- () => ({ client: builder, packs, registry, site, locale: site.locale, mediaOrigin, onError, resolveLink }),
2302
- [builder, packs, registry, site, mediaOrigin, onError, resolveLink]
3245
+ () => ({ client: builder, packs, registry, site, locale: site.locale, mediaOrigin, onError, resolveLink, interactive, customCss, mode, pathname, codeRoutes }),
3246
+ [builder, packs, registry, site, mediaOrigin, onError, resolveLink, interactive, customCss, mode, pathname, codeRoutes]
2303
3247
  );
2304
3248
  const design = useMemo(
2305
3249
  () => site.status === "ok" ? siteDesignOf(site.settings, resolveLink, pageOutlet, mediaOrigin) : null,
@@ -2312,15 +3256,16 @@ function BuilderProvider({ builderKey, client, packs, site, onError, children })
2312
3256
  if (own === void 0) return void 0;
2313
3257
  return parentFont === void 0 ? merged : { ...merged, variables: { ...merged.variables, fontFamily: parentFont } };
2314
3258
  }, [own, merged, parentFont]);
2315
- 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: [
2316
- site.status === "ok" ? /* @__PURE__ */ jsx25("style", { children: themeCss(site.settings) }) : null,
2317
- children
3259
+ return /* @__PURE__ */ jsx33(BuilderContext.Provider, { value, children: /* @__PURE__ */ jsx33(ThrottleUIProvider, { ...appearance === void 0 ? {} : { appearance }, children: /* @__PURE__ */ jsx33(SiteDesignProvider, { value: design, children: /* @__PURE__ */ jsxs21(SlotOutletProvider, { resolve: resolveSlot, children: [
3260
+ site.status === "ok" ? /* @__PURE__ */ jsx33("style", { children: themeCss(site.settings) }) : null,
3261
+ customCss === "" ? null : /* @__PURE__ */ jsx33("style", { children: customCssSheet(customCss) }),
3262
+ leaving ? /* @__PURE__ */ jsx33("div", { "data-b-leaving": "", hidden: true }) : children
2318
3263
  ] }) }) }) });
2319
3264
  }
2320
3265
 
2321
3266
  // src/parts.tsx
2322
- import { Suspense as Suspense5 } from "react";
2323
- import { jsx as jsx26 } from "react/jsx-runtime";
3267
+ import { Suspense as Suspense6 } from "react";
3268
+ import { jsx as jsx34 } from "react/jsx-runtime";
2324
3269
  function Part({ name, tag }) {
2325
3270
  const builder = useBuilder();
2326
3271
  if (builder === null || builder.site.status !== "ok") return null;
@@ -2330,11 +3275,11 @@ function Part({ name, tag }) {
2330
3275
  return (
2331
3276
  // Error boundaries do not catch on the server: the Suspense inside turns a throw
2332
3277
  // during SSR into "render nothing here" and the client retries under the boundary.
2333
- /* @__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 }) }) }) })
3278
+ /* @__PURE__ */ jsx34(PartBoundary, { label: `Builder ${name}`, children: /* @__PURE__ */ jsx34(Tag, { "data-throttle-part": `builder-${name}`, children: /* @__PURE__ */ jsx34(Suspense6, { fallback: null, children: /* @__PURE__ */ jsx34(PartView, { part }) }) }) })
2334
3279
  );
2335
3280
  }
2336
- var BuilderHeader = () => /* @__PURE__ */ jsx26(Part, { name: "header", tag: "header" });
2337
- var BuilderFooter = () => /* @__PURE__ */ jsx26(Part, { name: "footer", tag: "footer" });
3281
+ var BuilderHeader = () => /* @__PURE__ */ jsx34(Part, { name: "header", tag: "header" });
3282
+ var BuilderFooter = () => /* @__PURE__ */ jsx34(Part, { name: "footer", tag: "footer" });
2338
3283
 
2339
3284
  // src/index.ts
2340
3285
  import { BuilderNotFoundError, BuilderUnavailableError as BuilderUnavailableError2 } from "@usethrottle/builder";
@@ -2352,9 +3297,13 @@ export {
2352
3297
  BuilderRenderer,
2353
3298
  BuilderSlot,
2354
3299
  BuilderUnavailableError2 as BuilderUnavailableError,
3300
+ CODE_ROUTE_DENY,
2355
3301
  CUSTOM_WIDGET_CONTAINMENT,
3302
+ CodeWidget,
2356
3303
  CompositeWidget,
3304
+ DEFAULT_CATALOG_ROUTES,
2357
3305
  MAX_RENDERED_NODES,
3306
+ MissingSavedSection,
2358
3307
  NodeWrapper,
2359
3308
  RenderBudget,
2360
3309
  RichText,
@@ -2363,14 +3312,18 @@ export {
2363
3312
  basicPack,
2364
3313
  bindingKey,
2365
3314
  bindingsOf,
3315
+ codeScriptUrl,
2366
3316
  collectBindings,
2367
3317
  compileResponsiveCss,
2368
3318
  createRendererRegistry,
2369
3319
  cssValue,
2370
3320
  customWidgetFactory,
2371
3321
  embedSrc,
3322
+ expandSavedSections,
2372
3323
  fitsBudget,
3324
+ isCodeRoute,
2373
3325
  isFrozenAsset,
3326
+ jsonForScript,
2374
3327
  parseRichText,
2375
3328
  parseVideoUrl,
2376
3329
  pickLocale,