@orion-studios/payload-studio 0.6.0-beta.5 → 0.6.0-beta.50

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.
Files changed (55) hide show
  1. package/dist/admin/client.d.mts +1 -0
  2. package/dist/admin/client.d.ts +1 -0
  3. package/dist/admin/client.js +3923 -1354
  4. package/dist/admin/client.mjs +4089 -1532
  5. package/dist/admin/index.d.mts +2 -3
  6. package/dist/admin/index.d.ts +2 -3
  7. package/dist/admin/index.js +141 -1522
  8. package/dist/admin/index.mjs +2 -4
  9. package/dist/admin-app/client.js +11 -4
  10. package/dist/admin-app/client.mjs +1 -1
  11. package/dist/admin-app/index.d.mts +2 -2
  12. package/dist/admin-app/index.d.ts +2 -2
  13. package/dist/admin-app/index.mjs +4 -4
  14. package/dist/admin-app/styles.css +343 -41
  15. package/dist/admin.css +18 -2
  16. package/dist/builder-v2/client.d.mts +18 -0
  17. package/dist/builder-v2/client.d.ts +18 -0
  18. package/dist/builder-v2/client.js +1158 -0
  19. package/dist/builder-v2/client.mjs +1033 -0
  20. package/dist/builder-v2/index.d.mts +236 -0
  21. package/dist/builder-v2/index.d.ts +236 -0
  22. package/dist/builder-v2/index.js +735 -0
  23. package/dist/builder-v2/index.mjs +685 -0
  24. package/dist/builder-v2/styles.css +1005 -0
  25. package/dist/{chunk-KPIX7OSV.mjs → chunk-2XH7X34N.mjs} +11 -4
  26. package/dist/{chunk-PF3EBZXF.mjs → chunk-7ZMXZRBP.mjs} +39 -3
  27. package/dist/chunk-JC3UV74N.mjs +1033 -0
  28. package/dist/{chunk-XKUTZ7IU.mjs → chunk-NGLIA2OE.mjs} +53 -2
  29. package/dist/{chunk-EHUE4LCT.mjs → chunk-RKTIFEUY.mjs} +33 -3
  30. package/dist/chunk-W2UOCJDX.mjs +32 -0
  31. package/dist/{chunk-OTHERBGX.mjs → chunk-ZADL33R6.mjs} +1 -1
  32. package/dist/{index-bbA3HSxa.d.ts → index-BV0vEGl6.d.ts} +6 -9
  33. package/dist/{index-Cv-6qnrw.d.mts → index-D5zrOdyv.d.mts} +3 -1
  34. package/dist/{index-52HdVLQq.d.ts → index-DAdN56fM.d.ts} +1 -1
  35. package/dist/{index-DEkV-sMs.d.mts → index-DLfPOqYA.d.mts} +6 -9
  36. package/dist/{index-Crx_MtPw.d.ts → index-Dv-Alx4h.d.ts} +3 -1
  37. package/dist/{index-DEQC3Dwj.d.mts → index-G_uTNffQ.d.mts} +1 -1
  38. package/dist/index.d.mts +5 -5
  39. package/dist/index.d.ts +5 -5
  40. package/dist/index.js +294 -1542
  41. package/dist/index.mjs +6 -6
  42. package/dist/nextjs/index.js +39 -3
  43. package/dist/nextjs/index.mjs +2 -2
  44. package/dist/{sitePreviewTypes-BkHCWxNW.d.mts → sitePreviewTypes-BrJwGzJj.d.mts} +1 -1
  45. package/dist/{sitePreviewTypes-BkHCWxNW.d.ts → sitePreviewTypes-BrJwGzJj.d.ts} +1 -1
  46. package/dist/studio-pages/builder.css +24 -5
  47. package/dist/studio-pages/client.js +574 -64
  48. package/dist/studio-pages/client.mjs +574 -64
  49. package/dist/studio-pages/index.d.mts +1 -1
  50. package/dist/studio-pages/index.d.ts +1 -1
  51. package/dist/studio-pages/index.js +91 -4
  52. package/dist/studio-pages/index.mjs +2 -2
  53. package/package.json +22 -3
  54. package/dist/chunk-PKVTM6DY.mjs +0 -2372
  55. package/dist/chunk-Z6L5K5MH.mjs +0 -64
@@ -0,0 +1,1033 @@
1
+ 'use client';
2
+ "use client";
3
+ import {
4
+ MAX_DIRECT_UPLOAD_BYTES,
5
+ optimizeImageForUpload
6
+ } from "../chunk-ROTPP5CU.mjs";
7
+
8
+ // src/builder-v2/editor/GrapesPageEditor.tsx
9
+ import { useEffect, useRef, useState } from "react";
10
+
11
+ // src/builder-v2/projectData.ts
12
+ var isRecord = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
13
+ var createEmptyBuilderV2ProjectData = (title = "Untitled Page") => ({
14
+ assets: [],
15
+ pages: [
16
+ {
17
+ component: {
18
+ components: [
19
+ {
20
+ attributes: {
21
+ class: "orion-builder-v2-section"
22
+ },
23
+ components: [
24
+ {
25
+ content: title,
26
+ tagName: "h1",
27
+ type: "text"
28
+ },
29
+ {
30
+ content: "Start building this page by dragging blocks from the panel.",
31
+ tagName: "p",
32
+ type: "text"
33
+ }
34
+ ],
35
+ tagName: "section"
36
+ }
37
+ ],
38
+ type: "wrapper"
39
+ },
40
+ id: "page",
41
+ name: title
42
+ }
43
+ ],
44
+ styles: []
45
+ });
46
+ var normalizeBuilderV2ProjectData = (value, fallbackTitle = "Untitled Page") => {
47
+ if (!isRecord(value)) {
48
+ return createEmptyBuilderV2ProjectData(fallbackTitle);
49
+ }
50
+ return value;
51
+ };
52
+
53
+ // src/builder-v2/runtime/placeholders.ts
54
+ var placeholderPattern = /<(?<tag>[a-zA-Z][a-zA-Z0-9-]*)\b(?<attrs>[^>]*)data-orion-component=["'](?<component>[^"']+)["'](?<rest>[^>]*)>(?<content>.*?)<\/\k<tag>>/gis;
55
+ var attrPattern = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)=(?:"([^"]*)"|'([^']*)')/g;
56
+ var decodeHtmlAttribute = (value) => value.replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">");
57
+ var parseAttributes = (value) => {
58
+ const props = {};
59
+ let match;
60
+ while ((match = attrPattern.exec(value)) !== null) {
61
+ const name = match[1];
62
+ const rawValue = match[2] ?? match[3] ?? "";
63
+ if (!name.startsWith("data-")) {
64
+ continue;
65
+ }
66
+ if (name === "data-orion-component" || name === "data-orion-id") {
67
+ continue;
68
+ }
69
+ if (name === "data-orion-props") {
70
+ const decoded = decodeHtmlAttribute(rawValue);
71
+ try {
72
+ const parsed = JSON.parse(decoded);
73
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
74
+ Object.assign(props, parsed);
75
+ }
76
+ } catch {
77
+ props.propsJson = decoded;
78
+ }
79
+ continue;
80
+ }
81
+ const propName = name.replace(/^data-orion-/, "").replace(/^data-/, "").replace(/-([a-z])/g, (_, char) => char.toUpperCase());
82
+ props[propName] = decodeHtmlAttribute(rawValue);
83
+ }
84
+ return props;
85
+ };
86
+ var extractAttribute = (attrs, name) => {
87
+ const pattern = new RegExp(`${name}=["']([^"']+)["']`, "i");
88
+ const match = attrs.match(pattern);
89
+ return match ? decodeHtmlAttribute(match[1]) : null;
90
+ };
91
+ var parseBuilderV2DynamicComponents = (html) => {
92
+ const instances = [];
93
+ let match;
94
+ while ((match = placeholderPattern.exec(html)) !== null) {
95
+ const attrs = `${match.groups?.attrs ?? ""} ${match.groups?.rest ?? ""}`;
96
+ const component = match.groups?.component ?? "";
97
+ if (!component) {
98
+ continue;
99
+ }
100
+ instances.push({
101
+ component,
102
+ id: extractAttribute(attrs, "data-orion-id") || `component-${instances.length + 1}`,
103
+ props: parseAttributes(attrs)
104
+ });
105
+ }
106
+ return instances;
107
+ };
108
+
109
+ // src/builder-v2/sanitize.ts
110
+ import sanitizeHtml from "sanitize-html";
111
+ var allowedTags = sanitizeHtml.defaults.allowedTags.concat([
112
+ "article",
113
+ "aside",
114
+ "button",
115
+ "figure",
116
+ "figcaption",
117
+ "footer",
118
+ "header",
119
+ "main",
120
+ "nav",
121
+ "section",
122
+ "source",
123
+ "video"
124
+ ]);
125
+ var allowedAttributes = {
126
+ ...sanitizeHtml.defaults.allowedAttributes,
127
+ "*": [
128
+ "aria-*",
129
+ "class",
130
+ "data-*",
131
+ "id",
132
+ "role",
133
+ "style",
134
+ "title"
135
+ ],
136
+ a: ["aria-*", "class", "data-*", "href", "id", "name", "rel", "style", "target", "title"],
137
+ button: ["aria-*", "class", "data-*", "disabled", "id", "style", "title", "type"],
138
+ iframe: ["allow", "allowfullscreen", "class", "data-*", "height", "loading", "src", "style", "title", "width"],
139
+ img: ["alt", "class", "data-*", "height", "id", "loading", "sizes", "src", "srcset", "style", "title", "width"],
140
+ source: ["media", "src", "srcset", "type"],
141
+ video: ["autoplay", "class", "controls", "height", "loop", "muted", "playsinline", "poster", "preload", "src", "style", "width"]
142
+ };
143
+ var allowedIframeHosts = [
144
+ "calendar.google.com",
145
+ "calendly.com",
146
+ "player.vimeo.com",
147
+ "www.google.com",
148
+ "www.youtube.com",
149
+ "youtube.com"
150
+ ];
151
+ var sanitizeBuilderHtml = (value) => {
152
+ if (typeof value !== "string" || value.trim().length === 0) {
153
+ return "";
154
+ }
155
+ return sanitizeHtml(value, {
156
+ allowedAttributes,
157
+ allowedIframeHostnames: allowedIframeHosts,
158
+ allowedSchemes: ["http", "https", "mailto", "tel"],
159
+ allowedSchemesByTag: {
160
+ img: ["http", "https", "data"]
161
+ },
162
+ allowedTags,
163
+ allowProtocolRelative: false,
164
+ parseStyleAttributes: false
165
+ });
166
+ };
167
+ var sanitizeBuilderCss = (value) => {
168
+ if (typeof value !== "string" || value.trim().length === 0) {
169
+ return "";
170
+ }
171
+ return value.replace(/@import\s+[^;]+;/gi, "").replace(/expression\s*\(/gi, "").replace(/javascript\s*:/gi, "");
172
+ };
173
+ var scopeSelector = (selector, scope) => selector.split(",").map((part) => {
174
+ const trimmed = part.trim();
175
+ if (!trimmed || trimmed.startsWith(scope) || trimmed.startsWith("@")) {
176
+ return trimmed;
177
+ }
178
+ if (/^(html|body|:root)\b/i.test(trimmed)) {
179
+ return trimmed.replace(/^(html|body|:root)\b/i, scope);
180
+ }
181
+ return `${scope} ${trimmed}`;
182
+ }).filter(Boolean).join(", ");
183
+ var scopeBuilderCss = (value, scope = ".orion-builder-v2-runtime") => {
184
+ const css = sanitizeBuilderCss(value);
185
+ if (!css) {
186
+ return "";
187
+ }
188
+ let output = "";
189
+ let cursor = 0;
190
+ const rulePattern = /([^{}]+)\{/g;
191
+ let match;
192
+ while ((match = rulePattern.exec(css)) !== null) {
193
+ const selectorStart = match.index;
194
+ const selector = match[1];
195
+ output += css.slice(cursor, selectorStart);
196
+ const trimmedSelector = selector.trim();
197
+ if (trimmedSelector.startsWith("@keyframes") || trimmedSelector.startsWith("@font-face") || trimmedSelector.startsWith("@page")) {
198
+ output += `${selector}{`;
199
+ } else if (trimmedSelector.startsWith("@media") || trimmedSelector.startsWith("@supports")) {
200
+ output += `${selector}{`;
201
+ } else {
202
+ output += `${scopeSelector(selector, scope)} {`;
203
+ }
204
+ cursor = rulePattern.lastIndex;
205
+ }
206
+ output += css.slice(cursor);
207
+ return output;
208
+ };
209
+
210
+ // src/builder-v2/validation.ts
211
+ var hasMatch = (value, pattern) => pattern.test(value);
212
+ var validateBuilderV2Output = (input) => {
213
+ const html = typeof input.html === "string" ? input.html : "";
214
+ const css = typeof input.css === "string" ? input.css : "";
215
+ const issues = [];
216
+ if (!html.trim()) {
217
+ issues.push({
218
+ code: "empty-page",
219
+ message: "This page has no rendered content.",
220
+ path: "compiledHtml",
221
+ severity: "error"
222
+ });
223
+ }
224
+ if (!hasMatch(html, /<h1\b/i)) {
225
+ issues.push({
226
+ code: "missing-h1",
227
+ message: "Add one H1 so the published page has a clear primary heading.",
228
+ path: "compiledHtml",
229
+ severity: "warning"
230
+ });
231
+ }
232
+ if (hasMatch(html, /\son[a-z]+\s*=/i)) {
233
+ issues.push({
234
+ code: "inline-event-handler",
235
+ message: "Inline event handlers are not allowed in published builder HTML.",
236
+ path: "compiledHtml",
237
+ severity: "error"
238
+ });
239
+ }
240
+ if (hasMatch(html, /<(script|object|embed)\b/i)) {
241
+ issues.push({
242
+ code: "unsafe-element",
243
+ message: "Script, object, and embed tags are not allowed in builder content.",
244
+ path: "compiledHtml",
245
+ severity: "error"
246
+ });
247
+ }
248
+ if (hasMatch(html, /\b(?:href|src)=["']\s*javascript:/i)) {
249
+ issues.push({
250
+ code: "unsafe-url",
251
+ message: "Links and media cannot use javascript URLs.",
252
+ path: "compiledHtml",
253
+ severity: "error"
254
+ });
255
+ }
256
+ if (hasMatch(css, /@import\s/i)) {
257
+ issues.push({
258
+ code: "css-import",
259
+ message: "CSS imports are removed at publish time. Use the site font and theme managers instead.",
260
+ path: "compiledCss",
261
+ severity: "warning"
262
+ });
263
+ }
264
+ if (hasMatch(css, /position\s*:\s*fixed/i)) {
265
+ issues.push({
266
+ code: "fixed-position",
267
+ message: "Fixed positioning can cover site navigation or dialogs. Review this before publishing.",
268
+ path: "compiledCss",
269
+ severity: "warning"
270
+ });
271
+ }
272
+ return issues;
273
+ };
274
+ var hasBlockingBuilderV2Issues = (issues) => issues.some((issue) => issue.severity === "error");
275
+
276
+ // src/builder-v2/editor/defaultBlocks.ts
277
+ var registerOrionBuilderV2Blocks = (editor) => {
278
+ const blocks = editor.Blocks;
279
+ blocks.add("orion-nav", {
280
+ category: "Chrome",
281
+ content: `
282
+ <header class="orion-builder-v2-nav">
283
+ <a class="orion-builder-v2-logo" href="/">Brand</a>
284
+ <nav aria-label="Primary">
285
+ <a href="/">Home</a>
286
+ <a href="/about">About</a>
287
+ <a href="/contact">Contact</a>
288
+ </nav>
289
+ <a class="orion-builder-v2-button" href="/contact">Start</a>
290
+ </header>
291
+ `,
292
+ label: "Nav"
293
+ });
294
+ blocks.add("orion-section", {
295
+ category: "Layout",
296
+ content: `
297
+ <section class="orion-builder-v2-section">
298
+ <div class="orion-builder-v2-container">
299
+ <h2>Section Heading</h2>
300
+ <p>Add supporting content here.</p>
301
+ </div>
302
+ </section>
303
+ `,
304
+ label: "Section"
305
+ });
306
+ blocks.add("orion-hero", {
307
+ category: "Sections",
308
+ content: `
309
+ <section class="orion-builder-v2-hero">
310
+ <div class="orion-builder-v2-container">
311
+ <p class="orion-builder-v2-kicker">Optional kicker</p>
312
+ <h1>Build a stronger website</h1>
313
+ <p>Use this area for a clear value proposition and call to action.</p>
314
+ <a class="orion-builder-v2-button" href="/contact">Get started</a>
315
+ </div>
316
+ </section>
317
+ `,
318
+ label: "Hero"
319
+ });
320
+ blocks.add("orion-columns", {
321
+ category: "Layout",
322
+ content: `
323
+ <section class="orion-builder-v2-section">
324
+ <div class="orion-builder-v2-container orion-builder-v2-grid is-3">
325
+ <article class="orion-builder-v2-card"><h3>Column One</h3><p>Add content.</p></article>
326
+ <article class="orion-builder-v2-card"><h3>Column Two</h3><p>Add content.</p></article>
327
+ <article class="orion-builder-v2-card"><h3>Column Three</h3><p>Add content.</p></article>
328
+ </div>
329
+ </section>
330
+ `,
331
+ label: "Columns"
332
+ });
333
+ blocks.add("orion-card-grid", {
334
+ category: "Sections",
335
+ content: `
336
+ <section class="orion-builder-v2-section">
337
+ <div class="orion-builder-v2-container">
338
+ <p class="orion-builder-v2-kicker">Featured</p>
339
+ <h2>Cards that explain the offer</h2>
340
+ <div class="orion-builder-v2-grid is-3">
341
+ <article class="orion-builder-v2-card"><h3>Service One</h3><p>Describe the outcome clients care about.</p><a href="/contact">Learn more</a></article>
342
+ <article class="orion-builder-v2-card"><h3>Service Two</h3><p>Keep the card concise and scannable.</p><a href="/contact">Learn more</a></article>
343
+ <article class="orion-builder-v2-card"><h3>Service Three</h3><p>Use the same structure for visual rhythm.</p><a href="/contact">Learn more</a></article>
344
+ </div>
345
+ </div>
346
+ </section>
347
+ `,
348
+ label: "Card grid"
349
+ });
350
+ blocks.add("orion-gallery", {
351
+ category: "Media",
352
+ content: `
353
+ <section class="orion-builder-v2-section">
354
+ <div class="orion-builder-v2-container">
355
+ <h2>Gallery</h2>
356
+ <div class="orion-builder-v2-gallery">
357
+ <img alt="Gallery item" src="https://placehold.co/900x700" />
358
+ <img alt="Gallery item" src="https://placehold.co/900x700" />
359
+ <img alt="Gallery item" src="https://placehold.co/900x700" />
360
+ <img alt="Gallery item" src="https://placehold.co/900x700" />
361
+ </div>
362
+ </div>
363
+ </section>
364
+ `,
365
+ label: "Gallery"
366
+ });
367
+ blocks.add("orion-testimonials", {
368
+ category: "Sections",
369
+ content: `
370
+ <section class="orion-builder-v2-section is-muted">
371
+ <div class="orion-builder-v2-container">
372
+ <p class="orion-builder-v2-kicker">Testimonials</p>
373
+ <h2>What clients say</h2>
374
+ <div class="orion-builder-v2-grid is-3">
375
+ <blockquote class="orion-builder-v2-card"><p>"A clear, warm experience from start to finish."</p><cite>Client Name</cite></blockquote>
376
+ <blockquote class="orion-builder-v2-card"><p>"Exactly what we needed, without friction."</p><cite>Client Name</cite></blockquote>
377
+ <blockquote class="orion-builder-v2-card"><p>"The site made every next step obvious."</p><cite>Client Name</cite></blockquote>
378
+ </div>
379
+ </div>
380
+ </section>
381
+ `,
382
+ label: "Testimonials"
383
+ });
384
+ blocks.add("orion-faq", {
385
+ category: "Sections",
386
+ content: `
387
+ <section class="orion-builder-v2-section">
388
+ <div class="orion-builder-v2-container is-narrow">
389
+ <p class="orion-builder-v2-kicker">FAQ</p>
390
+ <h2>Questions answered</h2>
391
+ <details open><summary>What should visitors know first?</summary><p>Give a short, useful answer that removes hesitation.</p></details>
392
+ <details><summary>How does the process work?</summary><p>Explain the next step clearly.</p></details>
393
+ <details><summary>How do we get started?</summary><p>Point people to the strongest call to action.</p></details>
394
+ </div>
395
+ </section>
396
+ `,
397
+ label: "FAQ"
398
+ });
399
+ blocks.add("orion-pricing", {
400
+ category: "Commerce",
401
+ content: `
402
+ <section class="orion-builder-v2-section">
403
+ <div class="orion-builder-v2-container">
404
+ <p class="orion-builder-v2-kicker">Pricing</p>
405
+ <h2>Simple package options</h2>
406
+ <div class="orion-builder-v2-grid is-3">
407
+ <article class="orion-builder-v2-card"><h3>Starter</h3><p class="orion-builder-v2-price">$500</p><p>Best for focused launches.</p><a class="orion-builder-v2-button" href="/contact">Choose Starter</a></article>
408
+ <article class="orion-builder-v2-card is-featured"><h3>Growth</h3><p class="orion-builder-v2-price">$1,500</p><p>Best for expanding teams.</p><a class="orion-builder-v2-button" href="/contact">Choose Growth</a></article>
409
+ <article class="orion-builder-v2-card"><h3>Custom</h3><p class="orion-builder-v2-price">Quote</p><p>Best for complex builds.</p><a class="orion-builder-v2-button" href="/contact">Talk with us</a></article>
410
+ </div>
411
+ </div>
412
+ </section>
413
+ `,
414
+ label: "Pricing"
415
+ });
416
+ blocks.add("orion-button", {
417
+ category: "Basic",
418
+ content: '<a class="orion-builder-v2-button" href="/contact">Button</a>',
419
+ label: "Button"
420
+ });
421
+ blocks.add("orion-image", {
422
+ category: "Basic",
423
+ content: '<img alt="Image" class="orion-builder-v2-image" src="https://placehold.co/1200x700" />',
424
+ label: "Image"
425
+ });
426
+ blocks.add("orion-form-embed", {
427
+ category: "Dynamic",
428
+ content: `
429
+ <div
430
+ class="orion-builder-v2-dynamic-placeholder"
431
+ data-orion-component="formEmbed"
432
+ data-orion-form-slug="contact"
433
+ >
434
+ <strong>Form Embed</strong>
435
+ <span>contact</span>
436
+ </div>
437
+ `,
438
+ label: "Form"
439
+ });
440
+ blocks.add("orion-footer", {
441
+ category: "Chrome",
442
+ content: `
443
+ <footer class="orion-builder-v2-footer">
444
+ <div>
445
+ <strong>Brand</strong>
446
+ <p>Short positioning line for the site footer.</p>
447
+ </div>
448
+ <nav aria-label="Footer">
449
+ <a href="/privacy">Privacy</a>
450
+ <a href="/contact">Contact</a>
451
+ </nav>
452
+ </footer>
453
+ `,
454
+ label: "Footer"
455
+ });
456
+ };
457
+
458
+ // src/builder-v2/editor/projectComponents.ts
459
+ var normalizeDefinition = (type, value) => {
460
+ if (!value || typeof value === "function") {
461
+ return null;
462
+ }
463
+ return {
464
+ ...value,
465
+ type: value.type || type
466
+ };
467
+ };
468
+ var decodeHtmlAttribute2 = (value) => typeof value === "string" ? value.replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">") : "";
469
+ var attrToPropName = (name) => name.replace(/^data-orion-/, "").replace(/^data-/, "").replace(/-([a-z])/g, (_, char) => char.toUpperCase());
470
+ var propsFromAttributes = (attributes = {}) => {
471
+ const props = {};
472
+ Object.keys(attributes).forEach((name) => {
473
+ if (!name.startsWith("data-") || name === "data-orion-component" || name === "data-orion-id") {
474
+ return;
475
+ }
476
+ const value = decodeHtmlAttribute2(attributes[name]);
477
+ if (name === "data-orion-props") {
478
+ try {
479
+ const parsed = JSON.parse(value);
480
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
481
+ Object.assign(props, parsed);
482
+ }
483
+ } catch {
484
+ props.propsJson = value;
485
+ }
486
+ return;
487
+ }
488
+ props[attrToPropName(name)] = value;
489
+ });
490
+ return props;
491
+ };
492
+ var previewForDefinition = (definition, props) => definition.editorPreview?.(props) || `<div class="orion-builder-v2-dynamic-placeholder"><strong>${definition.label}</strong></div>`;
493
+ var registerProjectDynamicComponents = (editor, adapter) => {
494
+ const components = adapter?.components || {};
495
+ Object.keys(components).forEach((type) => {
496
+ const definition = normalizeDefinition(type, components[type]);
497
+ if (!definition) {
498
+ return;
499
+ }
500
+ editor.DomComponents.addType(`orion-${type}`, {
501
+ model: {
502
+ defaults: {
503
+ attributes: {
504
+ "data-orion-component": type,
505
+ "data-orion-id": `${type}-${Date.now()}`
506
+ },
507
+ components: "",
508
+ droppable: false,
509
+ tagName: "div",
510
+ traits: [
511
+ {
512
+ label: "Component",
513
+ name: "data-orion-component",
514
+ type: "text"
515
+ },
516
+ ...(definition.traits || []).map((trait) => ({
517
+ label: trait.label,
518
+ name: `data-orion-${trait.name.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`)}`,
519
+ options: trait.options,
520
+ placeholder: trait.placeholder,
521
+ type: trait.type
522
+ }))
523
+ ]
524
+ }
525
+ },
526
+ view: {
527
+ init() {
528
+ this.listenTo(this.model, "change:attributes", this.renderPreview);
529
+ this.renderPreview();
530
+ },
531
+ renderPreview() {
532
+ const attributes = this.model.getAttributes?.() || {};
533
+ const props = propsFromAttributes(attributes);
534
+ this.model.components(previewForDefinition(definition, props));
535
+ }
536
+ }
537
+ });
538
+ editor.Blocks.add(`orion-dynamic-${type}`, {
539
+ category: "Project",
540
+ content: {
541
+ type: `orion-${type}`
542
+ },
543
+ label: definition.label
544
+ });
545
+ });
546
+ };
547
+
548
+ // src/builder-v2/editor/GrapesPageEditor.tsx
549
+ import { jsx, jsxs } from "react/jsx-runtime";
550
+ var postToParent = (payload) => {
551
+ window.parent?.postMessage(
552
+ {
553
+ source: "payload-visual-builder-child",
554
+ ...payload
555
+ },
556
+ "*"
557
+ );
558
+ };
559
+ var buildSavePayload = (editor, status, projectData) => ({
560
+ builderMode: "grapes-v2",
561
+ compiledCss: scopeBuilderCss(editor.getCss()),
562
+ compiledHtml: sanitizeBuilderHtml(editor.getHtml()),
563
+ projectData,
564
+ status
565
+ });
566
+ var parsePayloadErrorMessage = async (response, fallback) => {
567
+ try {
568
+ const json = await response.json();
569
+ return json.errors?.[0]?.message || json.message || fallback;
570
+ } catch {
571
+ const raw = await response.text();
572
+ return raw.trim() || fallback;
573
+ }
574
+ };
575
+ var getRelationID = (value) => {
576
+ if (typeof value === "number" || typeof value === "string") {
577
+ return value;
578
+ }
579
+ if (!value || typeof value !== "object") {
580
+ return null;
581
+ }
582
+ const id = value.id;
583
+ return typeof id === "number" || typeof id === "string" ? id : null;
584
+ };
585
+ var mediaDocToAsset = (doc) => {
586
+ const id = getRelationID(doc);
587
+ const filename = typeof doc.filename === "string" ? doc.filename : "";
588
+ const src = typeof doc.url === "string" && doc.url.length > 0 ? doc.url : filename ? `/api/media/file/${encodeURIComponent(filename)}` : "";
589
+ if (id === null || !src) {
590
+ return null;
591
+ }
592
+ return {
593
+ alt: typeof doc.alt === "string" ? doc.alt : "",
594
+ id,
595
+ name: filename || String(id),
596
+ src,
597
+ type: "image"
598
+ };
599
+ };
600
+ var extractUploadedMedia = (value) => {
601
+ const candidate = value && typeof value === "object" && "doc" in value ? value.doc : value;
602
+ if (!candidate || typeof candidate !== "object") {
603
+ return null;
604
+ }
605
+ const id = getRelationID(candidate);
606
+ if (id === null) {
607
+ return null;
608
+ }
609
+ const typed = candidate;
610
+ return {
611
+ alt: typeof typed.alt === "string" ? typed.alt : "",
612
+ filename: typeof typed.filename === "string" ? typed.filename : "",
613
+ id,
614
+ url: typeof typed.url === "string" ? typed.url : ""
615
+ };
616
+ };
617
+ var loadPayloadMediaAssets = async (editor) => {
618
+ const response = await fetch(`/api/media?depth=1&limit=100&sort=-updatedAt&_=${Date.now()}`, {
619
+ cache: "no-store",
620
+ credentials: "include"
621
+ });
622
+ if (!response.ok) {
623
+ return;
624
+ }
625
+ const json = await response.json();
626
+ const assets = (Array.isArray(json.docs) ? json.docs : []).map((doc) => mediaDocToAsset(doc)).filter((asset) => asset !== null);
627
+ editor.AssetManager.add(assets);
628
+ };
629
+ var uploadPayloadMediaAssets = async (editor, files) => {
630
+ const fileArray = Array.from(files);
631
+ const uploadedAssets = [];
632
+ for (const file of fileArray) {
633
+ const optimizedFile = await optimizeImageForUpload(file);
634
+ if (optimizedFile.size > MAX_DIRECT_UPLOAD_BYTES) {
635
+ throw new Error("Image is too large. Use an image under 4MB or lower-resolution export.");
636
+ }
637
+ const fallbackAlt = file.name.replace(/\.[^/.]+$/, "").trim();
638
+ const formData = new FormData();
639
+ formData.set("_payload", JSON.stringify({ alt: fallbackAlt || "Uploaded image" }));
640
+ formData.set("alt", fallbackAlt || "Uploaded image");
641
+ formData.set("file", optimizedFile);
642
+ const response = await fetch("/api/media", {
643
+ body: formData,
644
+ credentials: "include",
645
+ method: "POST"
646
+ });
647
+ if (!response.ok) {
648
+ throw new Error(await parsePayloadErrorMessage(response, "Could not upload image."));
649
+ }
650
+ const uploaded = extractUploadedMedia(await response.json());
651
+ const asset = uploaded ? mediaDocToAsset(uploaded) : null;
652
+ if (asset) {
653
+ uploadedAssets.push(asset);
654
+ }
655
+ }
656
+ if (uploadedAssets.length > 0) {
657
+ editor.AssetManager.add(uploadedAssets);
658
+ }
659
+ };
660
+ function GrapesPageEditor({
661
+ adapter,
662
+ autosaveIntervalMs = 3e4,
663
+ initialData,
664
+ pageID
665
+ }) {
666
+ const containerRef = useRef(null);
667
+ const editorRef = useRef(null);
668
+ const autosaveTimerRef = useRef(null);
669
+ const saveRef = useRef(async () => void 0);
670
+ const [error, setError] = useState("");
671
+ const [historyState, setHistoryState] = useState({ canRedo: false, canUndo: false });
672
+ const [lastSavedAt, setLastSavedAt] = useState("");
673
+ const [loading, setLoading] = useState(true);
674
+ const [selectedDevice, setSelectedDevice] = useState("desktop");
675
+ const [saving, setSaving] = useState(null);
676
+ const [saveMessage, setSaveMessage] = useState("");
677
+ const [validationIssues, setValidationIssues] = useState([]);
678
+ const pageTree = initialData?.meta?.pageTree || [];
679
+ const updateHistoryState = (editor) => {
680
+ const next = {
681
+ canRedo: editor.UndoManager.hasRedo(),
682
+ canUndo: editor.UndoManager.hasUndo()
683
+ };
684
+ setHistoryState(next);
685
+ postToParent({
686
+ ...next,
687
+ type: "history-state"
688
+ });
689
+ };
690
+ const runValidation = (editor) => {
691
+ const issues = validateBuilderV2Output({
692
+ css: editor.getCss(),
693
+ html: editor.getHtml()
694
+ });
695
+ setValidationIssues(issues);
696
+ postToParent({ issues, type: "validation-state" });
697
+ return issues;
698
+ };
699
+ const setDevice = (device) => {
700
+ const editor = editorRef.current;
701
+ if (!editor) {
702
+ return;
703
+ }
704
+ editor.setDevice(device);
705
+ setSelectedDevice(device);
706
+ };
707
+ useEffect(() => {
708
+ let active = true;
709
+ const init = async () => {
710
+ if (!containerRef.current || editorRef.current) {
711
+ return;
712
+ }
713
+ try {
714
+ const grapesjs = (await import("grapesjs")).default;
715
+ if (!active || !containerRef.current) {
716
+ return;
717
+ }
718
+ const projectData = normalizeBuilderV2ProjectData(initialData?.projectData, initialData?.title);
719
+ const editor = grapesjs.init({
720
+ assetManager: {
721
+ uploadFile: async (event) => {
722
+ const target = event.target;
723
+ const dataTransfer = "dataTransfer" in event ? event.dataTransfer : null;
724
+ const files = dataTransfer?.files || target?.files;
725
+ if (!files || files.length === 0) {
726
+ return void 0;
727
+ }
728
+ await uploadPayloadMediaAssets(editorRef.current || editor, files).catch((uploadError) => {
729
+ setError(uploadError instanceof Error ? uploadError.message : "Could not upload image.");
730
+ });
731
+ }
732
+ },
733
+ blockManager: {
734
+ appendTo: "#orion-builder-v2-blocks"
735
+ },
736
+ container: containerRef.current,
737
+ deviceManager: {
738
+ devices: [
739
+ { id: "desktop", name: "Desktop", width: "" },
740
+ { id: "tablet", name: "Tablet", width: "768px" },
741
+ { id: "mobile", name: "Mobile", width: "390px" }
742
+ ]
743
+ },
744
+ fromElement: false,
745
+ height: "100%",
746
+ panels: {
747
+ defaults: []
748
+ },
749
+ selectorManager: {
750
+ componentFirst: true
751
+ },
752
+ storageManager: false,
753
+ styleManager: {
754
+ sectors: [
755
+ {
756
+ name: "Layout",
757
+ open: true,
758
+ properties: ["display", "position", "top", "right", "bottom", "left", "width", "height", "min-height", "margin", "padding"]
759
+ },
760
+ {
761
+ name: "Typography",
762
+ open: true,
763
+ properties: ["font-family", "font-size", "font-weight", "line-height", "letter-spacing", "color", "text-align"]
764
+ },
765
+ {
766
+ name: "Decoration",
767
+ open: true,
768
+ properties: ["background-color", "background", "border", "border-radius", "box-shadow", "opacity"]
769
+ },
770
+ {
771
+ name: "Flex",
772
+ open: false,
773
+ properties: ["flex-direction", "justify-content", "align-items", "gap", "flex-wrap"]
774
+ }
775
+ ]
776
+ },
777
+ traitManager: {
778
+ appendTo: "#orion-builder-v2-traits"
779
+ },
780
+ width: "auto"
781
+ });
782
+ editorRef.current = editor;
783
+ registerOrionBuilderV2Blocks(editor);
784
+ registerProjectDynamicComponents(editor, adapter);
785
+ editor.loadProjectData(projectData);
786
+ void loadPayloadMediaAssets(editor);
787
+ editor.on("update", () => {
788
+ postToParent({ dirty: editor.getDirtyCount() > 0, type: "dirty-state" });
789
+ updateHistoryState(editor);
790
+ runValidation(editor);
791
+ setSaveMessage("Unsaved changes");
792
+ if (autosaveTimerRef.current) {
793
+ window.clearTimeout(autosaveTimerRef.current);
794
+ }
795
+ autosaveTimerRef.current = window.setTimeout(() => {
796
+ if (editor.getDirtyCount() > 0) {
797
+ void saveRef.current("draft", { autosave: true });
798
+ }
799
+ }, autosaveIntervalMs);
800
+ });
801
+ editor.on("component:selected", () => {
802
+ setSaveMessage("Selection ready");
803
+ });
804
+ setSelectedDevice(editor.getDevice() || "desktop");
805
+ runValidation(editor);
806
+ updateHistoryState(editor);
807
+ setLoading(false);
808
+ } catch (initError) {
809
+ setError(initError instanceof Error ? initError.message : "Could not load the website builder.");
810
+ setLoading(false);
811
+ }
812
+ };
813
+ void init();
814
+ return () => {
815
+ active = false;
816
+ if (autosaveTimerRef.current) {
817
+ window.clearTimeout(autosaveTimerRef.current);
818
+ }
819
+ editorRef.current?.destroy();
820
+ editorRef.current = null;
821
+ };
822
+ }, [adapter, autosaveIntervalMs, initialData?.projectData, initialData?.title]);
823
+ const save = async (status, options = {}) => {
824
+ const editor = editorRef.current;
825
+ if (!editor || saving) {
826
+ return;
827
+ }
828
+ const issues = runValidation(editor);
829
+ if (status === "published" && hasBlockingBuilderV2Issues(issues)) {
830
+ const message = "Resolve blocking validation errors before publishing.";
831
+ setSaveMessage(message);
832
+ postToParent({
833
+ message,
834
+ ok: false,
835
+ status,
836
+ type: "save-result"
837
+ });
838
+ return;
839
+ }
840
+ setSaving(status);
841
+ try {
842
+ const projectData = editor.getProjectData();
843
+ const payload = buildSavePayload(editor, status, projectData);
844
+ const dynamicComponents = parseBuilderV2DynamicComponents(String(payload.compiledHtml || ""));
845
+ const endpoint = status === "draft" ? `/api/pages/${pageID}?draft=true` : `/api/pages/${pageID}`;
846
+ const response = await fetch(endpoint, {
847
+ body: JSON.stringify(
848
+ status === "published" ? {
849
+ _status: "published",
850
+ builderDynamicComponents: dynamicComponents,
851
+ builderMode: "grapes-v2",
852
+ builderProjectData: projectData,
853
+ builderPublishedProjectData: projectData,
854
+ builderLastPublishedAt: (/* @__PURE__ */ new Date()).toISOString(),
855
+ builderLastSavedAt: (/* @__PURE__ */ new Date()).toISOString(),
856
+ builderValidationIssues: issues,
857
+ compiledCss: payload.compiledCss,
858
+ compiledHtml: payload.compiledHtml
859
+ } : {
860
+ _status: "draft",
861
+ builderAutosaveProjectData: options.autosave ? projectData : null,
862
+ builderDynamicComponents: dynamicComponents,
863
+ builderMode: "grapes-v2",
864
+ builderProjectData: projectData,
865
+ builderLastSavedAt: (/* @__PURE__ */ new Date()).toISOString(),
866
+ builderValidationIssues: issues,
867
+ compiledCss: payload.compiledCss,
868
+ compiledHtml: payload.compiledHtml
869
+ }
870
+ ),
871
+ credentials: "include",
872
+ headers: {
873
+ "Content-Type": "application/json"
874
+ },
875
+ method: "PATCH"
876
+ });
877
+ if (!response.ok) {
878
+ if (response.status === 401 || response.status === 403) {
879
+ postToParent({ type: "session-expired" });
880
+ }
881
+ throw new Error(await parsePayloadErrorMessage(response, "Could not save this page."));
882
+ }
883
+ editor.clearDirtyCount();
884
+ postToParent({
885
+ dirty: false,
886
+ type: "dirty-state"
887
+ });
888
+ postToParent({
889
+ message: status === "published" ? "Published." : options.autosave ? "Autosaved." : "Draft saved.",
890
+ ok: true,
891
+ status,
892
+ type: "save-result"
893
+ });
894
+ setLastSavedAt((/* @__PURE__ */ new Date()).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" }));
895
+ setSaveMessage(status === "published" ? "Published" : options.autosave ? "Autosaved" : "Draft saved");
896
+ } catch (saveError) {
897
+ const message = saveError instanceof Error ? saveError.message : "Could not save.";
898
+ setSaveMessage(message);
899
+ postToParent({
900
+ message,
901
+ ok: false,
902
+ status,
903
+ type: "save-result"
904
+ });
905
+ } finally {
906
+ setSaving(null);
907
+ }
908
+ };
909
+ useEffect(() => {
910
+ saveRef.current = save;
911
+ }, [saving]);
912
+ useEffect(() => {
913
+ const onMessage = (event) => {
914
+ const data = event.data;
915
+ const editor = editorRef.current;
916
+ if (!data || data.source !== "payload-visual-builder-parent" || !editor) {
917
+ return;
918
+ }
919
+ if (data.type === "dirty-check-request") {
920
+ postToParent({ dirty: editor.getDirtyCount() > 0, type: "dirty-state" });
921
+ updateHistoryState(editor);
922
+ return;
923
+ }
924
+ if (data.type === "history-check-request") {
925
+ updateHistoryState(editor);
926
+ return;
927
+ }
928
+ if (data.type === "undo") {
929
+ editor.UndoManager.undo();
930
+ return;
931
+ }
932
+ if (data.type === "redo") {
933
+ editor.UndoManager.redo();
934
+ return;
935
+ }
936
+ if (data.type === "save" && (data.status === "draft" || data.status === "published")) {
937
+ void save(data.status);
938
+ }
939
+ };
940
+ window.addEventListener("message", onMessage);
941
+ return () => window.removeEventListener("message", onMessage);
942
+ }, [saving]);
943
+ return /* @__PURE__ */ jsxs("div", { className: "orion-builder-v2-editor", children: [
944
+ /* @__PURE__ */ jsxs("header", { className: "orion-builder-v2-topbar", children: [
945
+ /* @__PURE__ */ jsxs("div", { children: [
946
+ /* @__PURE__ */ jsx("p", { className: "orion-builder-v2-eyebrow", children: "Website Builder V2" }),
947
+ /* @__PURE__ */ jsx("h1", { children: initialData?.title || "Untitled page" })
948
+ ] }),
949
+ /* @__PURE__ */ jsxs("div", { className: "orion-builder-v2-toolbar", "aria-label": "Builder controls", children: [
950
+ ["desktop", "tablet", "mobile"].map((device) => /* @__PURE__ */ jsx(
951
+ "button",
952
+ {
953
+ "aria-pressed": selectedDevice === device,
954
+ className: "orion-builder-v2-tool",
955
+ onClick: () => setDevice(device),
956
+ type: "button",
957
+ children: device
958
+ },
959
+ device
960
+ )),
961
+ /* @__PURE__ */ jsx(
962
+ "button",
963
+ {
964
+ className: "orion-builder-v2-tool",
965
+ disabled: !historyState.canUndo,
966
+ onClick: () => {
967
+ editorRef.current?.UndoManager.undo();
968
+ editorRef.current && updateHistoryState(editorRef.current);
969
+ },
970
+ type: "button",
971
+ children: "Undo"
972
+ }
973
+ ),
974
+ /* @__PURE__ */ jsx(
975
+ "button",
976
+ {
977
+ className: "orion-builder-v2-tool",
978
+ disabled: !historyState.canRedo,
979
+ onClick: () => {
980
+ editorRef.current?.UndoManager.redo();
981
+ editorRef.current && updateHistoryState(editorRef.current);
982
+ },
983
+ type: "button",
984
+ children: "Redo"
985
+ }
986
+ ),
987
+ /* @__PURE__ */ jsx("button", { className: "orion-builder-v2-tool is-primary", disabled: Boolean(saving), onClick: () => void save("draft"), type: "button", children: saving === "draft" ? "Saving..." : "Save draft" }),
988
+ /* @__PURE__ */ jsx("button", { className: "orion-builder-v2-tool is-publish", disabled: Boolean(saving), onClick: () => void save("published"), type: "button", children: saving === "published" ? "Publishing..." : "Publish" })
989
+ ] })
990
+ ] }),
991
+ /* @__PURE__ */ jsxs("aside", { className: "orion-builder-v2-sidebar", children: [
992
+ /* @__PURE__ */ jsxs("div", { className: "orion-builder-v2-panel", children: [
993
+ /* @__PURE__ */ jsx("h2", { children: "Pages" }),
994
+ /* @__PURE__ */ jsx("div", { className: "orion-builder-v2-page-tree", children: pageTree.length === 0 ? /* @__PURE__ */ jsx("p", { children: "No pages loaded." }) : pageTree.map((page) => /* @__PURE__ */ jsxs("a", { className: "orion-builder-v2-page-link", href: `#page-${page.id}`, children: [
995
+ /* @__PURE__ */ jsx("span", { children: page.title }),
996
+ /* @__PURE__ */ jsx("small", { children: page.path })
997
+ ] }, page.id)) })
998
+ ] }),
999
+ /* @__PURE__ */ jsxs("div", { className: "orion-builder-v2-panel", children: [
1000
+ /* @__PURE__ */ jsx("h2", { children: "Blocks" }),
1001
+ /* @__PURE__ */ jsx("p", { children: "Drag sections into the page. Dynamic blocks render through the project adapter." }),
1002
+ /* @__PURE__ */ jsx("div", { id: "orion-builder-v2-blocks" })
1003
+ ] }),
1004
+ /* @__PURE__ */ jsxs("div", { className: "orion-builder-v2-panel", children: [
1005
+ /* @__PURE__ */ jsx("h2", { children: "Inspector" }),
1006
+ /* @__PURE__ */ jsx("p", { children: "Selection settings, dynamic bindings, links, and labels." }),
1007
+ /* @__PURE__ */ jsx("div", { id: "orion-builder-v2-traits" })
1008
+ ] }),
1009
+ /* @__PURE__ */ jsxs("div", { className: "orion-builder-v2-panel", children: [
1010
+ /* @__PURE__ */ jsx("h2", { children: "Validation" }),
1011
+ /* @__PURE__ */ jsx("div", { className: "orion-builder-v2-validation-list", children: validationIssues.length === 0 ? /* @__PURE__ */ jsx("p", { children: "No issues found." }) : validationIssues.map((issue) => /* @__PURE__ */ jsxs("div", { className: `orion-builder-v2-validation is-${issue.severity}`, children: [
1012
+ /* @__PURE__ */ jsx("strong", { children: issue.message }),
1013
+ /* @__PURE__ */ jsx("span", { children: issue.severity })
1014
+ ] }, `${issue.code}-${issue.path}`)) })
1015
+ ] })
1016
+ ] }),
1017
+ /* @__PURE__ */ jsxs("main", { className: "orion-builder-v2-main", children: [
1018
+ loading ? /* @__PURE__ */ jsx("div", { className: "orion-builder-v2-status", children: "Loading builder..." }) : null,
1019
+ error ? /* @__PURE__ */ jsx("div", { className: "orion-builder-v2-error", children: error }) : null,
1020
+ saveMessage || lastSavedAt ? /* @__PURE__ */ jsxs("div", { className: "orion-builder-v2-save-status", children: [
1021
+ /* @__PURE__ */ jsx("strong", { children: saveMessage || "Ready" }),
1022
+ lastSavedAt ? /* @__PURE__ */ jsxs("span", { children: [
1023
+ "Last saved ",
1024
+ lastSavedAt
1025
+ ] }) : null
1026
+ ] }) : null,
1027
+ /* @__PURE__ */ jsx("div", { className: "orion-builder-v2-canvas", ref: containerRef })
1028
+ ] })
1029
+ ] });
1030
+ }
1031
+ export {
1032
+ GrapesPageEditor
1033
+ };