@usethrottle/builder-react 0.3.0 → 0.4.0

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