@preprio/toolkit 0.5.0-rc.1 → 0.5.0-rc.3

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 (50) hide show
  1. package/README.md +207 -10
  2. package/dist/astro/index.cjs +1174 -1
  3. package/dist/astro/index.d.cts +47 -1
  4. package/dist/astro/index.d.ts +47 -1
  5. package/dist/astro/index.js +1177 -1
  6. package/dist/chunk-42Z2VW7G.js +1161 -0
  7. package/dist/chunk-6WY3MWCX.js +246 -0
  8. package/dist/chunk-MDAV2FLM.js +26 -0
  9. package/dist/{chunk-4JNKYIEV.js → chunk-PP3O7RB4.js} +1370 -617
  10. package/dist/chunk-S3VT4UWM.js +75 -0
  11. package/dist/chunk-SXUDBGLZ.js +184 -0
  12. package/dist/chunk-URXSDJOU.js +356 -0
  13. package/dist/index.cjs +3113 -391
  14. package/dist/index.d.cts +240 -5
  15. package/dist/index.d.ts +240 -5
  16. package/dist/index.js +189 -149
  17. package/dist/live-preview-EADA3ZL4.js +18 -0
  18. package/dist/nextjs/components.cjs +1530 -361
  19. package/dist/nextjs/components.d.cts +1 -1
  20. package/dist/nextjs/components.d.ts +1 -1
  21. package/dist/nextjs/components.js +4 -1
  22. package/dist/nextjs/index.cjs +1065 -6
  23. package/dist/nextjs/index.d.cts +81 -3
  24. package/dist/nextjs/index.d.ts +81 -3
  25. package/dist/nextjs/index.js +1059 -7
  26. package/dist/nextjs/live-action.cjs +285 -0
  27. package/dist/nextjs/live-action.d.cts +12 -0
  28. package/dist/nextjs/live-action.d.ts +12 -0
  29. package/dist/nextjs/live-action.js +68 -0
  30. package/dist/nextjs/live.cjs +1838 -0
  31. package/dist/nextjs/live.d.cts +52 -0
  32. package/dist/nextjs/live.d.ts +52 -0
  33. package/dist/nextjs/live.js +265 -0
  34. package/dist/nuxt/index.cjs +1 -1
  35. package/dist/nuxt/index.js +1 -1
  36. package/dist/nuxt/live-preview-PTEC3GPC.js +1462 -0
  37. package/dist/nuxt/live.cjs +1662 -0
  38. package/dist/nuxt/live.d.cts +43 -0
  39. package/dist/nuxt/live.d.ts +43 -0
  40. package/dist/nuxt/live.js +94 -0
  41. package/dist/{pixel-e1fUWl2Y.d.cts → pixel-CX422dCO.d.cts} +18 -3
  42. package/dist/{pixel-e1fUWl2Y.d.ts → pixel-CX422dCO.d.ts} +18 -3
  43. package/dist/react/components.cjs +1530 -361
  44. package/dist/react/components.d.cts +17 -2
  45. package/dist/react/components.d.ts +17 -2
  46. package/dist/react/components.js +1530 -361
  47. package/dist/sveltekit/index.cjs +1 -1
  48. package/dist/sveltekit/index.js +1 -1
  49. package/package.json +12 -1
  50. package/src/astro/PreprToolbar.astro +7 -1
@@ -1,5 +1,5 @@
1
1
  // src/version.ts
2
- var VERSION = "0.5.0-rc.1";
2
+ var VERSION = "0.5.0-rc.3";
3
3
 
4
4
  // src/core/features.ts
5
5
  function isEnabled(config) {
@@ -162,6 +162,7 @@ var PARAM_SEGMENT = "prepr_preview_segment";
162
162
  var PARAM_VARIANT = "prepr_preview_ab";
163
163
  var PARAM_HIDE_BAR = "prepr_hide_bar";
164
164
  var ONE_YEAR_SECONDS = 60 * 60 * 24 * 365;
165
+ var HEADER_LIVE_RENDER = "x-prepr-live";
165
166
 
166
167
  // src/core/middleware.ts
167
168
  var UTM_PARAMS = [
@@ -329,7 +330,1165 @@ function processFrameworkRequest(request, opts, framework) {
329
330
  return { requestHeaders, responseCookies };
330
331
  }
331
332
 
333
+ // src/core/live-preview/normalize-query.ts
334
+ import {
335
+ vercelStegaCombine,
336
+ vercelStegaDecode,
337
+ vercelStegaSplit as vercelStegaSplit2
338
+ } from "@vercel/stega";
339
+
340
+ // src/core/utils.ts
341
+ var DebugLogger = class {
342
+ constructor(options) {
343
+ this.options = {
344
+ prefix: "[Prepr]",
345
+ ...options
346
+ };
347
+ }
348
+ // A local `enabled` wins; otherwise defer to the global logger so scoped
349
+ // loggers created before initDebugLogger() still pick up the setting.
350
+ isEnabled() {
351
+ if (this.options.enabled !== void 0) {
352
+ return this.options.enabled;
353
+ }
354
+ return globalDebugLogger?.options?.enabled ?? false;
355
+ }
356
+ log(message, ...args) {
357
+ if (!this.isEnabled()) return;
358
+ const prefix = this.options.prefix;
359
+ console.log(`${prefix} ${message}`, ...args);
360
+ }
361
+ warn(message, ...args) {
362
+ if (!this.isEnabled()) return;
363
+ const prefix = this.options.prefix;
364
+ console.warn(`${prefix} ${message}`, ...args);
365
+ }
366
+ error(message, ...args) {
367
+ if (!this.isEnabled()) return;
368
+ const prefix = this.options.prefix;
369
+ console.error(`${prefix} ${message}`, ...args);
370
+ }
371
+ };
372
+ var globalDebugLogger = null;
373
+ function createScopedLogger(scopeName) {
374
+ return new DebugLogger({
375
+ prefix: `[Prepr][${scopeName}]`
376
+ });
377
+ }
378
+
379
+ // src/core/live-preview/field-name.ts
380
+ var UPPERCASE_BOUNDARY = /(.)(?=[A-Z])/g;
381
+ function graphqlFieldName(apiId) {
382
+ return apiId.replace(UPPERCASE_BOUNDARY, "$1_").toLowerCase();
383
+ }
384
+
385
+ // src/core/live-preview/index-snapshot.ts
386
+ var debug = createScopedLogger("live-preview");
387
+ function indexSnapshot(data) {
388
+ const index = /* @__PURE__ */ new Map();
389
+ const visited = /* @__PURE__ */ new WeakSet();
390
+ const path = [];
391
+ function walk(node) {
392
+ if (node === null || typeof node !== "object") return;
393
+ if (visited.has(node)) return;
394
+ visited.add(node);
395
+ if (Array.isArray(node)) {
396
+ for (let i = 0; i < node.length; i++) {
397
+ path.push(i);
398
+ walk(node[i]);
399
+ path.pop();
400
+ }
401
+ return;
402
+ }
403
+ const record = node;
404
+ if (typeof record._id === "string") {
405
+ const paths = index.get(record._id);
406
+ if (paths) paths.push([...path]);
407
+ else index.set(record._id, [[...path]]);
408
+ } else if (typeof record.__typename === "string") {
409
+ debug.log("item without _id will not live-update", {
410
+ __typename: record.__typename
411
+ });
412
+ }
413
+ for (const key in record) {
414
+ if (!Object.prototype.hasOwnProperty.call(record, key)) continue;
415
+ path.push(key);
416
+ walk(record[key]);
417
+ path.pop();
418
+ }
419
+ }
420
+ walk(data);
421
+ return index;
422
+ }
423
+
424
+ // src/core/live-preview/patch.ts
425
+ import { vercelStegaSplit } from "@vercel/stega";
426
+ var FORBIDDEN_SEGMENTS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
427
+ function isPlainObject(value) {
428
+ return value !== null && typeof value === "object" && !Array.isArray(value);
429
+ }
430
+ function mergeObject(current, incoming) {
431
+ let changed = false;
432
+ const next = { ...current };
433
+ for (const key of Object.keys(current)) {
434
+ if (!(key in incoming) || incoming[key] === void 0) continue;
435
+ const value = isPlainObject(current[key]) && isPlainObject(incoming[key]) ? mergeObject(current[key], incoming[key]) : incoming[key];
436
+ if (value !== current[key]) {
437
+ next[key] = value;
438
+ changed = true;
439
+ }
440
+ }
441
+ return changed ? next : current;
442
+ }
443
+ function shapeLike(template, incoming) {
444
+ const out = {};
445
+ for (const key of Object.keys(template)) {
446
+ const value = incoming[key];
447
+ out[key] = value === void 0 ? null : isPlainObject(template[key]) && isPlainObject(value) ? shapeLike(template[key], value) : value;
448
+ }
449
+ return out;
450
+ }
451
+ function mergeStructured(current, incoming) {
452
+ if (incoming === null || Array.isArray(incoming) && !incoming.length) {
453
+ if (Array.isArray(current)) return current.length ? [] : current;
454
+ return null;
455
+ }
456
+ const list = Array.isArray(incoming) ? incoming : [incoming];
457
+ if (current === null || current === void 0) return incoming;
458
+ if (Array.isArray(current)) {
459
+ const template = current.find(isPlainObject);
460
+ return list.map((entry) => {
461
+ const match = current.find(
462
+ (c) => isPlainObject(c) && c._id !== void 0 && c._id === entry._id
463
+ );
464
+ if (isPlainObject(match)) return mergeObject(match, entry);
465
+ return isPlainObject(template) ? shapeLike(template, entry) : entry;
466
+ });
467
+ }
468
+ if (isPlainObject(current)) return mergeObject(current, list[0]);
469
+ return current;
470
+ }
471
+ function isPatchable(current) {
472
+ return current === null || typeof current === "string" || typeof current === "number" || typeof current === "boolean";
473
+ }
474
+ function cloneNode(node) {
475
+ return Array.isArray(node) ? [...node] : { ...node };
476
+ }
477
+ function writeAtPath(root, fullPath, value, markChanged = () => {
478
+ }) {
479
+ if (!fullPath.length) return root;
480
+ if (fullPath.some((s) => FORBIDDEN_SEGMENTS.has(String(s)))) return root;
481
+ const last = fullPath.length - 1;
482
+ let node = root;
483
+ for (let i = 0; i < last; i++) {
484
+ if (node === null || typeof node !== "object") return root;
485
+ node = node[fullPath[i]];
486
+ }
487
+ if (node === null || typeof node !== "object") return root;
488
+ const container = node;
489
+ const key = fullPath[last];
490
+ if (!(key in container)) return root;
491
+ let next;
492
+ if (value === null || typeof value === "object") {
493
+ next = mergeStructured(container[key], value);
494
+ } else if (!isPatchable(container[key])) {
495
+ return root;
496
+ } else {
497
+ next = keepEditLink(container[key], value);
498
+ }
499
+ if (container[key] === next) return root;
500
+ const newRoot = cloneNode(root);
501
+ let cursor = newRoot;
502
+ for (let i = 0; i < last; i++) {
503
+ const child = cloneNode(cursor[fullPath[i]]);
504
+ cursor[fullPath[i]] = child;
505
+ cursor = child;
506
+ }
507
+ cursor[key] = next;
508
+ markChanged();
509
+ return newRoot;
510
+ }
511
+ function listKeysOf(entry) {
512
+ if (!isPlainObject(entry)) return [];
513
+ const keys = [];
514
+ if (typeof entry._id === "string") keys.push(entry._id);
515
+ const first = Array.isArray(entry.items) ? entry.items[0] : null;
516
+ if (isPlainObject(first) && typeof first._id === "string") {
517
+ keys.push(first._id);
518
+ }
519
+ return keys;
520
+ }
521
+ var TAG_PATTERN = /<[^>]+>/g;
522
+ function buildText(entry, template) {
523
+ const body = typeof entry.body === "string" ? entry.body : "";
524
+ const full = {
525
+ __typename: "Text",
526
+ _id: entry._id,
527
+ body,
528
+ html: body,
529
+ text: body.replace(TAG_PATTERN, ""),
530
+ format: entry.format ?? null
531
+ };
532
+ if (!template) return full;
533
+ const out = {};
534
+ for (const key of Object.keys(template)) {
535
+ out[key] = key in full ? full[key] : null;
536
+ }
537
+ return out;
538
+ }
539
+ function syncList(current, entries, build) {
540
+ if (current === null || current === void 0) {
541
+ const built = syncList([], entries, build);
542
+ return built.length ? built : current;
543
+ }
544
+ if (!Array.isArray(current)) return current;
545
+ const byKey = /* @__PURE__ */ new Map();
546
+ const templates = /* @__PURE__ */ new Map();
547
+ for (const c of current) {
548
+ for (const key of listKeysOf(c)) byKey.set(key, c);
549
+ if (isPlainObject(c) && typeof c.__typename === "string") {
550
+ if (!templates.has(c.__typename)) templates.set(c.__typename, c);
551
+ }
552
+ }
553
+ if (!entries.length) return current.length ? [] : current;
554
+ if (current.length && !byKey.size) return current;
555
+ if (current.length && !entries.some((e) => byKey.has(e._id))) return current;
556
+ const next = [];
557
+ for (const entry of entries) {
558
+ const existing = byKey.get(entry._id);
559
+ const built = existing === void 0 && entry.fields ? build?.(entry) : void 0;
560
+ if (existing !== void 0) {
561
+ next.push(existing);
562
+ } else if (built) {
563
+ next.push(built);
564
+ } else if (entry.__typename === "Text") {
565
+ next.push(buildText(entry, templates.get("Text")));
566
+ }
567
+ }
568
+ const same = next.length === current.length && next.every((n, i) => n === current[i]);
569
+ return same ? current : next;
570
+ }
571
+ function syncListAtPath(root, fullPath, entries, build) {
572
+ if (!fullPath.length) return root;
573
+ if (fullPath.some((s) => FORBIDDEN_SEGMENTS.has(String(s)))) return root;
574
+ let node = root;
575
+ for (const key of fullPath) {
576
+ node = node !== null && typeof node === "object" ? node[key] : void 0;
577
+ }
578
+ const next = syncList(node, entries, build);
579
+ if (next === node) return root;
580
+ const newRoot = cloneNode(root);
581
+ let cursor = newRoot;
582
+ for (let i = 0; i < fullPath.length - 1; i++) {
583
+ const child = cloneNode(cursor[fullPath[i]]);
584
+ cursor[fullPath[i]] = child;
585
+ cursor = child;
586
+ }
587
+ cursor[fullPath[fullPath.length - 1]] = next;
588
+ return newRoot;
589
+ }
590
+ function keepEditLink(current, value) {
591
+ if (typeof current !== "string" || typeof value !== "string") return value;
592
+ const { encoded } = vercelStegaSplit(current);
593
+ if (!encoded || vercelStegaSplit(value).encoded) return value;
594
+ return value + encoded;
595
+ }
596
+
597
+ // src/core/live-preview/query-document.ts
598
+ var NAME_START = /[_A-Za-z]/;
599
+ var NAME_CONTINUE = /[_0-9A-Za-z]/;
600
+ var PUNCT = /* @__PURE__ */ new Set([
601
+ "!",
602
+ "$",
603
+ "&",
604
+ "(",
605
+ ")",
606
+ ":",
607
+ "=",
608
+ "@",
609
+ "[",
610
+ "]",
611
+ "{",
612
+ "|",
613
+ "}"
614
+ ]);
615
+ function tokenize(source) {
616
+ const tokens = [];
617
+ let i = 0;
618
+ const n = source.length;
619
+ while (i < n) {
620
+ const ch = source[i];
621
+ if (ch === " " || ch === " " || ch === "\n" || ch === "\r" || ch === "," || ch === "\uFEFF") {
622
+ i++;
623
+ } else if (ch === "#") {
624
+ while (i < n && source[i] !== "\n" && source[i] !== "\r") i++;
625
+ } else if (ch === "." && source.startsWith("...", i)) {
626
+ tokens.push({ type: "punct", value: "..." });
627
+ i += 3;
628
+ } else if (PUNCT.has(ch)) {
629
+ tokens.push({ type: "punct", value: ch });
630
+ i++;
631
+ } else if (NAME_START.test(ch)) {
632
+ const start = i;
633
+ while (i < n && NAME_CONTINUE.test(source[i])) i++;
634
+ tokens.push({ type: "name", value: source.slice(start, i) });
635
+ } else if (ch === '"') {
636
+ if (source.startsWith('"""', i)) {
637
+ i += 3;
638
+ while (i < n && !source.startsWith('"""', i)) {
639
+ i += source.startsWith('\\"""', i) ? 4 : 1;
640
+ }
641
+ if (i >= n) throw new SyntaxError("Unterminated block string");
642
+ i += 3;
643
+ } else {
644
+ i++;
645
+ while (i < n && source[i] !== '"') {
646
+ if (source[i] === "\n" || source[i] === "\r") {
647
+ throw new SyntaxError("Unterminated string");
648
+ }
649
+ i += source[i] === "\\" ? 2 : 1;
650
+ }
651
+ if (i >= n) throw new SyntaxError("Unterminated string");
652
+ i++;
653
+ }
654
+ tokens.push({ type: "value" });
655
+ } else if (ch === "-" || ch >= "0" && ch <= "9") {
656
+ i++;
657
+ while (i < n && /[0-9.eE+-]/.test(source[i])) i++;
658
+ tokens.push({ type: "value" });
659
+ } else {
660
+ throw new SyntaxError(`Unexpected character "${ch}"`);
661
+ }
662
+ }
663
+ return tokens;
664
+ }
665
+ function parseSource(source, operationName) {
666
+ const tokens = tokenize(source);
667
+ let pos = 0;
668
+ const peek = () => tokens[pos];
669
+ const isPunct = (value) => {
670
+ const t = tokens[pos];
671
+ return t?.type === "punct" && t.value === value;
672
+ };
673
+ const expectPunct = (value) => {
674
+ if (!isPunct(value)) throw new SyntaxError(`Expected "${value}"`);
675
+ pos++;
676
+ };
677
+ const expectName = () => {
678
+ const t = tokens[pos];
679
+ if (t?.type !== "name") throw new SyntaxError("Expected a name");
680
+ pos++;
681
+ return t.value;
682
+ };
683
+ const skipParens = () => {
684
+ expectPunct("(");
685
+ let depth = 1;
686
+ while (depth > 0) {
687
+ const t = tokens[pos++];
688
+ if (!t) throw new SyntaxError("Unbalanced parentheses");
689
+ if (t.type === "punct" && t.value === "(") depth++;
690
+ else if (t.type === "punct" && t.value === ")") depth--;
691
+ }
692
+ };
693
+ const skipDirectives = () => {
694
+ while (isPunct("@")) {
695
+ pos++;
696
+ expectName();
697
+ if (isPunct("(")) skipParens();
698
+ }
699
+ };
700
+ const parseSelectionSet = () => {
701
+ expectPunct("{");
702
+ const selections = [];
703
+ while (!isPunct("}")) {
704
+ if (!peek()) throw new SyntaxError("Unterminated selection set");
705
+ selections.push(parseSelection());
706
+ }
707
+ pos++;
708
+ return selections;
709
+ };
710
+ const parseSelection = () => {
711
+ if (isPunct("...")) {
712
+ pos++;
713
+ const t = peek();
714
+ if (t?.type === "name" && t.value !== "on") {
715
+ pos++;
716
+ skipDirectives();
717
+ return { kind: "spread", name: t.value };
718
+ }
719
+ let on = null;
720
+ if (t?.type === "name") {
721
+ pos++;
722
+ on = expectName();
723
+ }
724
+ skipDirectives();
725
+ return { kind: "inline", on, selections: parseSelectionSet() };
726
+ }
727
+ let name = expectName();
728
+ const key = name;
729
+ if (isPunct(":")) {
730
+ pos++;
731
+ name = expectName();
732
+ }
733
+ let hasArgs = false;
734
+ if (isPunct("(")) {
735
+ hasArgs = true;
736
+ skipParens();
737
+ }
738
+ skipDirectives();
739
+ const selections = isPunct("{") ? parseSelectionSet() : null;
740
+ return { kind: "field", name, key, hasArgs, selections };
741
+ };
742
+ const fragments = /* @__PURE__ */ new Map();
743
+ const operations = [];
744
+ while (pos < tokens.length) {
745
+ if (isPunct("{")) {
746
+ operations.push({ name: null, selections: parseSelectionSet() });
747
+ continue;
748
+ }
749
+ const keyword = expectName();
750
+ if (keyword === "fragment") {
751
+ const name = expectName();
752
+ if (expectName() !== "on") throw new SyntaxError('Expected "on"');
753
+ const on = expectName();
754
+ skipDirectives();
755
+ fragments.set(name, { on, selections: parseSelectionSet() });
756
+ } else if (keyword === "query" || keyword === "mutation" || keyword === "subscription") {
757
+ const t = peek();
758
+ let name = null;
759
+ if (t?.type === "name") name = expectName();
760
+ if (isPunct("(")) skipParens();
761
+ skipDirectives();
762
+ operations.push({ name, selections: parseSelectionSet() });
763
+ } else {
764
+ throw new SyntaxError(`Unexpected "${keyword}"`);
765
+ }
766
+ }
767
+ return { operation: pickOperation(operations, operationName), fragments };
768
+ }
769
+ function pickOperation(operations, operationName) {
770
+ const op = operationName ? operations.find((o) => o.name === operationName) : operations[0];
771
+ if (!op) throw new SyntaxError("The document has no operation");
772
+ return op.selections;
773
+ }
774
+ function fromAstSelections(set) {
775
+ return set.selections.map((s) => {
776
+ if (s.kind === "FragmentSpread")
777
+ return { kind: "spread", name: s.name.value };
778
+ if (s.kind === "InlineFragment") {
779
+ return {
780
+ kind: "inline",
781
+ on: s.typeCondition?.name.value ?? null,
782
+ selections: fromAstSelections(s.selectionSet)
783
+ };
784
+ }
785
+ const name = s.name.value;
786
+ return {
787
+ kind: "field",
788
+ name,
789
+ key: s.alias?.value ?? name,
790
+ hasArgs: Boolean(s.arguments?.length),
791
+ selections: s.selectionSet ? fromAstSelections(s.selectionSet) : null
792
+ };
793
+ });
794
+ }
795
+ function fromAst(doc, operationName) {
796
+ const fragments = /* @__PURE__ */ new Map();
797
+ const operations = [];
798
+ for (const def of doc.definitions ?? []) {
799
+ if (def.kind === "FragmentDefinition" && def.name && def.typeCondition && def.selectionSet) {
800
+ fragments.set(def.name.value, {
801
+ on: def.typeCondition.name.value,
802
+ selections: fromAstSelections(def.selectionSet)
803
+ });
804
+ } else if (def.kind === "OperationDefinition" && def.selectionSet) {
805
+ operations.push({
806
+ name: def.name?.value ?? null,
807
+ selections: fromAstSelections(def.selectionSet)
808
+ });
809
+ }
810
+ }
811
+ return { operation: pickOperation(operations, operationName), fragments };
812
+ }
813
+ var astCache = /* @__PURE__ */ new WeakMap();
814
+ var sourceCache = /* @__PURE__ */ new Map();
815
+ var SOURCE_CACHE_LIMIT = 200;
816
+ function readQueryDocument(query, operationName) {
817
+ const cacheKey = operationName ?? "";
818
+ if (typeof query === "object" && query !== null && query.kind === "Document") {
819
+ let byName = astCache.get(query);
820
+ if (!byName) astCache.set(query, byName = /* @__PURE__ */ new Map());
821
+ let parsed2 = byName.get(cacheKey);
822
+ if (!parsed2) {
823
+ parsed2 = fromAst(
824
+ query,
825
+ operationName
826
+ );
827
+ byName.set(cacheKey, parsed2);
828
+ }
829
+ return parsed2;
830
+ }
831
+ const source = String(query);
832
+ const sourceKey = `${cacheKey}
833
+ ${source}`;
834
+ let parsed = sourceCache.get(sourceKey);
835
+ if (!parsed) {
836
+ parsed = parseSource(source, operationName);
837
+ if (sourceCache.size >= SOURCE_CACHE_LIMIT) {
838
+ sourceCache.delete(sourceCache.keys().next().value);
839
+ }
840
+ sourceCache.set(sourceKey, parsed);
841
+ }
842
+ return parsed;
843
+ }
844
+ var fieldsCache = /* @__PURE__ */ new WeakMap();
845
+ function collectFields(selections, typename, doc, options = {}) {
846
+ const cacheKey = `${options.strict ? "s" : "l"}:${typename ?? ""}`;
847
+ let cached = fieldsCache.get(selections);
848
+ if (!cached) {
849
+ cached = /* @__PURE__ */ new Map();
850
+ fieldsCache.set(selections, cached);
851
+ }
852
+ const hit = cached.get(cacheKey);
853
+ if (hit) return hit;
854
+ const fields = resolveFields(selections, typename, doc, options);
855
+ cached.set(cacheKey, fields);
856
+ return fields;
857
+ }
858
+ function resolveFields(selections, typename, doc, options) {
859
+ const exact = /* @__PURE__ */ new Map();
860
+ const loose = /* @__PURE__ */ new Map();
861
+ const merged = /* @__PURE__ */ new Map();
862
+ const walkedMatched = /* @__PURE__ */ new Set();
863
+ const walkedLoose = /* @__PURE__ */ new Set();
864
+ const add = (target, s) => {
865
+ let field = target.get(s.key);
866
+ if (!field) {
867
+ field = { name: s.name, key: s.key, hasArgs: s.hasArgs, selections: [] };
868
+ target.set(s.key, field);
869
+ merged.set(field, /* @__PURE__ */ new Set());
870
+ }
871
+ const done = merged.get(field);
872
+ if (s.selections && !done.has(s.selections)) {
873
+ done.add(s.selections);
874
+ field.selections = [...field.selections, ...s.selections];
875
+ }
876
+ };
877
+ const applies = (on, list) => conditionMatches(on, typename) || typename !== void 0 && typeConditions(list, doc).includes(typename);
878
+ const walk = (list, matched) => {
879
+ for (const s of list) {
880
+ if (s.kind === "field") {
881
+ add(matched ? exact : loose, s);
882
+ } else if (s.kind === "inline") {
883
+ walk(s.selections, matched && applies(s.on, s.selections));
884
+ } else {
885
+ const fragment = doc.fragments.get(s.name);
886
+ if (!fragment) continue;
887
+ const asMatched = matched && applies(fragment.on, fragment.selections);
888
+ if (walkedMatched.has(fragment)) continue;
889
+ if (!asMatched && walkedLoose.has(fragment)) continue;
890
+ (asMatched ? walkedMatched : walkedLoose).add(fragment);
891
+ walk(fragment.selections, asMatched);
892
+ }
893
+ }
894
+ };
895
+ walk(selections, true);
896
+ if (!options.strict) {
897
+ for (const [key, field] of loose) {
898
+ if (!exact.has(key)) exact.set(key, field);
899
+ }
900
+ }
901
+ return exact;
902
+ }
903
+ function conditionMatches(on, typename) {
904
+ return on === null || typename === void 0 || on === typename;
905
+ }
906
+ var conditionsCache = /* @__PURE__ */ new WeakMap();
907
+ function typeConditions(selections, doc) {
908
+ const hit = conditionsCache.get(selections);
909
+ if (hit) return hit;
910
+ const names = /* @__PURE__ */ new Set();
911
+ const seen = /* @__PURE__ */ new Set();
912
+ const walk = (list) => {
913
+ for (const s of list) {
914
+ if (s.kind === "inline") {
915
+ if (s.on) names.add(s.on);
916
+ walk(s.selections);
917
+ } else if (s.kind === "spread") {
918
+ const fragment = doc.fragments.get(s.name);
919
+ if (!fragment || seen.has(fragment)) continue;
920
+ seen.add(fragment);
921
+ names.add(fragment.on);
922
+ walk(fragment.selections);
923
+ }
924
+ }
925
+ };
926
+ walk(selections);
927
+ const conditions = [...names];
928
+ conditionsCache.set(selections, conditions);
929
+ return conditions;
930
+ }
931
+
932
+ // src/core/live-preview/validate.ts
933
+ function isScalar(v) {
934
+ return typeof v === "string" || typeof v === "number" || typeof v === "boolean";
935
+ }
936
+ var MAX_DEPTH = 3;
937
+ var MAX_ENTRIES = 50;
938
+ var FORBIDDEN_KEYS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
939
+ var SAFE_URL = /^https?:\/\//i;
940
+ var URL_KEY = /^(?:url|href|src|link)$|(?:_url|Url)$/;
941
+ var URL_IGNORED_ANYWHERE = /[\t\n\r]/g;
942
+ var SCRIPT_SCHEME = /^(?:javascript|vbscript|data):/i;
943
+ function isSafeLinkValue(value) {
944
+ const stripped = value.replace(URL_IGNORED_ANYWHERE, "");
945
+ let start = 0;
946
+ while (start < stripped.length && stripped.charCodeAt(start) <= 32) start++;
947
+ return !SCRIPT_SCHEME.test(stripped.slice(start));
948
+ }
949
+ function isUrlKey(key) {
950
+ return URL_KEY.test(key);
951
+ }
952
+ function isSafeKeyValue(key, value) {
953
+ if (typeof value !== "string") return true;
954
+ if (key === "url") return SAFE_URL.test(value);
955
+ return !isUrlKey(key) || isSafeLinkValue(value);
956
+ }
957
+ function isLiveValue(v, depth = 0) {
958
+ if (v === null || isScalar(v)) return true;
959
+ if (depth >= MAX_DEPTH) return false;
960
+ if (Array.isArray(v)) {
961
+ return depth === 0 && v.length <= MAX_ENTRIES && v.every((entry) => isPlainRecord(entry) && isLiveValue(entry, depth + 1));
962
+ }
963
+ if (!isPlainRecord(v)) return false;
964
+ const keys = Object.keys(v);
965
+ if (keys.length > MAX_ENTRIES) return false;
966
+ return keys.every((key) => {
967
+ if (FORBIDDEN_KEYS.has(key)) return false;
968
+ const value = v[key];
969
+ if (!isSafeKeyValue(key, value)) return false;
970
+ return !Array.isArray(value) && isLiveValue(value, depth + 1);
971
+ });
972
+ }
973
+ function isLiveFieldChange(field, value) {
974
+ if (!isLiveValue(value)) return false;
975
+ const name = field.slice(field.lastIndexOf(".") + 1);
976
+ return typeof value !== "string" || !isUrlKey(name) || isSafeLinkValue(value);
977
+ }
978
+ var MAX_LIST_ENTRIES = 200;
979
+ function parseListEntries(value) {
980
+ if (!Array.isArray(value) || value.length > MAX_LIST_ENTRIES) return null;
981
+ const list = [];
982
+ for (const raw of value) {
983
+ if (!isPlainRecord(raw) || typeof raw._id !== "string" || !raw._id) {
984
+ return null;
985
+ }
986
+ const entry = { _id: raw._id };
987
+ if (typeof raw.__typename === "string") entry.__typename = raw.__typename;
988
+ if (typeof raw.body === "string") entry.body = raw.body;
989
+ if (typeof raw.format === "string" || raw.format === null) {
990
+ entry.format = raw.format;
991
+ }
992
+ if (typeof raw.typeName === "string" && raw.typeName.length <= 200) {
993
+ entry.typeName = raw.typeName;
994
+ }
995
+ if (raw.fields !== void 0) {
996
+ if (!isPlainRecord(raw.fields) || !isFieldValue(raw.fields, 0)) {
997
+ return null;
998
+ }
999
+ entry.fields = raw.fields;
1000
+ }
1001
+ list.push(entry);
1002
+ }
1003
+ return list;
1004
+ }
1005
+ function isPlainRecord(v) {
1006
+ return v !== null && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype;
1007
+ }
1008
+ var MAX_FIELD_DEPTH = 6;
1009
+ var MAX_FIELD_KEYS = 100;
1010
+ function isFieldValue(v, depth) {
1011
+ if (v === null || isScalar(v)) return true;
1012
+ if (depth >= MAX_FIELD_DEPTH) return false;
1013
+ if (Array.isArray(v)) {
1014
+ return v.length <= MAX_ENTRIES && v.every(
1015
+ (entry) => isScalar(entry) || isPlainRecord(entry) && isFieldValue(entry, depth + 1)
1016
+ );
1017
+ }
1018
+ if (!isPlainRecord(v)) return false;
1019
+ const keys = Object.keys(v);
1020
+ if (keys.length > MAX_FIELD_KEYS) return false;
1021
+ return keys.every((key) => {
1022
+ if (FORBIDDEN_KEYS.has(key)) return false;
1023
+ const value = v[key];
1024
+ if (!isSafeKeyValue(key, value)) return false;
1025
+ return isFieldValue(value, depth + 1);
1026
+ });
1027
+ }
1028
+ var MAX_EDIT_LENGTH = 1e3;
1029
+ function parseEditTarget(raw) {
1030
+ if (!isPlainRecord(raw)) return void 0;
1031
+ const { item, field } = raw;
1032
+ if (typeof item !== "string" || !item || item.length > MAX_EDIT_LENGTH) {
1033
+ return void 0;
1034
+ }
1035
+ if (typeof field !== "string" || !field || field.length > MAX_EDIT_LENGTH) {
1036
+ return void 0;
1037
+ }
1038
+ return { item, field };
1039
+ }
1040
+
1041
+ // src/core/live-preview/normalize-query.ts
1042
+ var debug2 = createScopedLogger("live-preview:normalize");
1043
+ var MAX_LOG_ENTRIES = 500;
1044
+ var MAX_LOG_SOURCE_LENGTH = 1e6;
1045
+ var INDEX_SEGMENT = /^\d+$/;
1046
+ var FORBIDDEN_SEGMENTS2 = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
1047
+ var ENVELOPE_KEYS = /* @__PURE__ */ new Set(["data", "errors", "extensions"]);
1048
+ function parsePatchLog(raw) {
1049
+ let value = raw;
1050
+ if (typeof value === "string") {
1051
+ if (!value || value.length > MAX_LOG_SOURCE_LENGTH) return [];
1052
+ try {
1053
+ value = JSON.parse(value);
1054
+ } catch {
1055
+ return [];
1056
+ }
1057
+ }
1058
+ if (!Array.isArray(value)) return [];
1059
+ const log = [];
1060
+ for (const entry of value.slice(-MAX_LOG_ENTRIES)) {
1061
+ if (!isPlainRecord(entry)) continue;
1062
+ const { type, itemId, field } = entry;
1063
+ if (typeof itemId !== "string" || !itemId) continue;
1064
+ if (typeof field !== "string" || !field) continue;
1065
+ if (type === "field" && isLiveFieldChange(field, entry.value)) {
1066
+ const edit = parseEditTarget(entry.edit);
1067
+ log.push(
1068
+ edit ? { type, itemId, field, value: entry.value, edit } : { type, itemId, field, value: entry.value }
1069
+ );
1070
+ } else if (type === "list") {
1071
+ const entries = parseListEntries(entry.entries);
1072
+ if (entries) log.push({ type, itemId, field, entries });
1073
+ }
1074
+ }
1075
+ return log;
1076
+ }
1077
+ function normalizeQuery(query, result, options = {}) {
1078
+ return applyPatchLog(
1079
+ query,
1080
+ result,
1081
+ parsePatchLog(options.log),
1082
+ options.operationName
1083
+ );
1084
+ }
1085
+ function applyPatchLog(query, result, log, operationName) {
1086
+ if (!log.length || result === null || typeof result !== "object") {
1087
+ return result;
1088
+ }
1089
+ if (isEnvelope(result)) {
1090
+ const data = applyPatchLog(query, result.data, log, operationName);
1091
+ return data === result.data ? result : { ...result, data };
1092
+ }
1093
+ let doc = null;
1094
+ try {
1095
+ doc = readQueryDocument(query, operationName);
1096
+ } catch (error) {
1097
+ debug2.log("could not read the query; applying fields by literal path", {
1098
+ error: String(error)
1099
+ });
1100
+ }
1101
+ let root = result;
1102
+ let index = null;
1103
+ for (const patch of log) {
1104
+ try {
1105
+ index ?? (index = indexSnapshot(root));
1106
+ const next = applyPatch(root, index, patch, doc, result);
1107
+ if (next !== root) {
1108
+ root = next;
1109
+ if (patch.type === "list" || !isScalarValue(patch.value)) {
1110
+ index = null;
1111
+ }
1112
+ }
1113
+ } catch (error) {
1114
+ debug2.log("could not apply a change", {
1115
+ itemId: patch.itemId,
1116
+ field: patch.field,
1117
+ error: String(error)
1118
+ });
1119
+ }
1120
+ }
1121
+ return root;
1122
+ }
1123
+ function isScalarValue(value) {
1124
+ return value === null || typeof value !== "object";
1125
+ }
1126
+ function applyPatch(root, index, patch, doc, result) {
1127
+ const ownerPaths = index.get(patch.itemId);
1128
+ if (!ownerPaths?.length) return root;
1129
+ const segments = patch.field.split(".");
1130
+ if (segments.some((s) => !s || FORBIDDEN_SEGMENTS2.has(s))) return root;
1131
+ const targets = [];
1132
+ for (const ownerPath of ownerPaths) {
1133
+ if (doc) {
1134
+ const resolved = resolveTargets(root, doc, ownerPath, segments);
1135
+ root = resolved.root;
1136
+ targets.push(...resolved.targets);
1137
+ } else {
1138
+ targets.push([...ownerPath, ...segments.map(toPathSegment)]);
1139
+ }
1140
+ }
1141
+ if (!targets.length) {
1142
+ debug2.log("no field in the query matches", {
1143
+ itemId: patch.itemId,
1144
+ field: patch.field
1145
+ });
1146
+ return root;
1147
+ }
1148
+ if (patch.type === "field") {
1149
+ for (const target of targets) {
1150
+ let value = keepEditLink(readAtPath(root, target), patch.value);
1151
+ if (patch.edit && typeof value === "string" && !vercelStegaSplit2(value).encoded) {
1152
+ value = editLinksFor(result, patch.edit.item)?.encode(
1153
+ value,
1154
+ patch.edit.field
1155
+ ) ?? value;
1156
+ }
1157
+ root = writeAtPath(root, target, value);
1158
+ }
1159
+ } else {
1160
+ for (const target of targets) {
1161
+ const selections = doc ? selectionsAt(root, doc, target) : null;
1162
+ const build = doc && selections ? (entry) => buildEntry(doc, selections, entry, {
1163
+ links: editLinks(result, entry),
1164
+ lists: listKeysIn(result)
1165
+ }) : void 0;
1166
+ root = syncListAtPath(root, target, patch.entries, build);
1167
+ }
1168
+ }
1169
+ return root;
1170
+ }
1171
+ function readAtPath(root, path) {
1172
+ let node = root;
1173
+ for (const step of path) {
1174
+ if (node === null || typeof node !== "object") return void 0;
1175
+ node = node[step];
1176
+ }
1177
+ return node;
1178
+ }
1179
+ function isEnvelope(value) {
1180
+ if (Array.isArray(value) || !("data" in value)) return false;
1181
+ return Object.keys(value).every((key) => ENVELOPE_KEYS.has(key));
1182
+ }
1183
+ function toPathSegment(segment) {
1184
+ return INDEX_SEGMENT.test(segment) ? Number(segment) : segment;
1185
+ }
1186
+ function typenameOf(node) {
1187
+ const typename = node.__typename;
1188
+ return typeof typename === "string" ? typename : void 0;
1189
+ }
1190
+ function selectionsAt(root, doc, path) {
1191
+ let node = root;
1192
+ let selections = doc.operation;
1193
+ for (const step of path) {
1194
+ if (Array.isArray(node)) {
1195
+ node = node[step];
1196
+ continue;
1197
+ }
1198
+ if (node === null || typeof node !== "object") return null;
1199
+ const field = collectFields(selections, typenameOf(node), doc).get(
1200
+ String(step)
1201
+ );
1202
+ if (!field) return null;
1203
+ selections = field.selections;
1204
+ node = node[String(step)];
1205
+ }
1206
+ return selections;
1207
+ }
1208
+ function resolveTargets(root, doc, ownerPath, segments) {
1209
+ let owner = root;
1210
+ for (const step of ownerPath) {
1211
+ owner = owner[step];
1212
+ }
1213
+ const selections = selectionsAt(root, doc, ownerPath);
1214
+ if (!selections) return { root, targets: [] };
1215
+ let current = root;
1216
+ const out = [];
1217
+ const walk = (node, sel, i, path) => {
1218
+ if (i === segments.length) {
1219
+ out.push(path);
1220
+ return;
1221
+ }
1222
+ const segment = segments[i];
1223
+ if (Array.isArray(node)) {
1224
+ if (INDEX_SEGMENT.test(segment)) {
1225
+ const position = Number(segment);
1226
+ if (position < node.length) {
1227
+ walk(node[position], sel, i + 1, [...path, position]);
1228
+ }
1229
+ } else if (segment === "items") {
1230
+ walk(node, sel, i + 1, path);
1231
+ }
1232
+ return;
1233
+ }
1234
+ if (node === null || typeof node !== "object") return;
1235
+ const record = node;
1236
+ const wanted = graphqlFieldName(segment);
1237
+ let matched = false;
1238
+ for (const field of collectFields(sel, typenameOf(node), doc).values()) {
1239
+ if (field.name !== segment && field.name !== wanted) continue;
1240
+ if (!Object.prototype.hasOwnProperty.call(record, field.key)) continue;
1241
+ matched = true;
1242
+ const fieldPath = [...path, field.key];
1243
+ let value = record[field.key];
1244
+ const next = segments[i + 1];
1245
+ if (value === null && field.selections.length && next !== void 0 && next !== "items" && !INDEX_SEGMENT.test(next)) {
1246
+ const typename = resolveTypename(
1247
+ doc,
1248
+ field.selections,
1249
+ void 0,
1250
+ void 0
1251
+ );
1252
+ if (typename !== void 0) {
1253
+ value = fillObject(doc, field.selections, typename, {}, void 0, {
1254
+ links: null,
1255
+ lists: listKeysIn(root)
1256
+ });
1257
+ current = writeAtPath(current, fieldPath, value);
1258
+ }
1259
+ }
1260
+ walk(value, field.selections, i + 1, fieldPath);
1261
+ }
1262
+ if (!matched && segment === "items") walk(node, sel, i + 1, path);
1263
+ };
1264
+ walk(owner, selections, 0, ownerPath);
1265
+ return { root: current, targets: out };
1266
+ }
1267
+ var NON_ALPHANUMERIC = /[^a-z0-9]/gi;
1268
+ var typeKey = (name) => name.replace(NON_ALPHANUMERIC, "").toLowerCase();
1269
+ function resolveTypename(doc, selections, typename, typeName) {
1270
+ const known = typeConditions(selections, doc);
1271
+ const explicit = typeof typename === "string" ? typename : void 0;
1272
+ if (!known.length) return explicit ?? null;
1273
+ if (explicit && known.includes(explicit)) return explicit;
1274
+ for (const candidate of [explicit, typeName]) {
1275
+ if (typeof candidate !== "string" || !candidate) continue;
1276
+ const match = known.find((name) => typeKey(name) === typeKey(candidate));
1277
+ if (match) return match;
1278
+ }
1279
+ const named = explicit !== void 0 || typeof typeName === "string";
1280
+ return known.length === 1 && !named ? known[0] : void 0;
1281
+ }
1282
+ function buildEntry(doc, selections, entry, ctx) {
1283
+ const typename = resolveTypename(
1284
+ doc,
1285
+ selections,
1286
+ entry.__typename,
1287
+ entry.typeName
1288
+ );
1289
+ if (typename === void 0) return void 0;
1290
+ return fillObject(
1291
+ doc,
1292
+ selections,
1293
+ typename,
1294
+ entry.fields ?? {},
1295
+ entry._id,
1296
+ ctx
1297
+ );
1298
+ }
1299
+ function fillObject(doc, selections, typename, values, id, ctx) {
1300
+ const out = {};
1301
+ const { links } = ctx;
1302
+ const lists = ctx.lists(typename);
1303
+ const edit = isPlainRecord(values.__edit) ? values.__edit : null;
1304
+ const apiIdOf = /* @__PURE__ */ new Map();
1305
+ for (const key of Object.keys(values)) {
1306
+ apiIdOf.set(key, key);
1307
+ const name = graphqlFieldName(key);
1308
+ if (!apiIdOf.has(name)) apiIdOf.set(name, key);
1309
+ }
1310
+ if (edit && isPlainRecord(edit.apiIds)) {
1311
+ for (const [name, apiId] of Object.entries(edit.apiIds)) {
1312
+ if (typeof apiId === "string") apiIdOf.set(name, apiId);
1313
+ }
1314
+ }
1315
+ const valueOf = (name) => {
1316
+ if (Object.prototype.hasOwnProperty.call(values, name)) return values[name];
1317
+ const key = apiIdOf.get(name);
1318
+ return key !== void 0 && key in values ? values[key] : void 0;
1319
+ };
1320
+ const editField = (name) => {
1321
+ if (!edit) return null;
1322
+ if (typeof edit.field === "string")
1323
+ return name === "body" ? edit.field : null;
1324
+ if (typeof edit.path !== "string") return null;
1325
+ const apiId = apiIdOf.get(name) ?? name;
1326
+ const text = Array.isArray(edit.text) ? edit.text : [];
1327
+ if (!text.includes(apiId) && !text.includes(name)) return null;
1328
+ return `${edit.path}.items.${apiId}`;
1329
+ };
1330
+ const fields = collectFields(selections, typename ?? void 0, doc, {
1331
+ strict: true
1332
+ });
1333
+ for (const field of fields.values()) {
1334
+ if (field.name === "__typename") {
1335
+ out[field.key] = typename;
1336
+ } else if (field.name === "_id") {
1337
+ out[field.key] = typeof id === "string" ? id : values._id ?? null;
1338
+ } else if (field.selections.length) {
1339
+ const value = valueOf(field.name);
1340
+ out[field.key] = value == null && lists.has(field.key) ? [] : fillNested(doc, field.selections, value, ctx);
1341
+ } else {
1342
+ const value = valueOf(field.name);
1343
+ if (Array.isArray(value) && value.every(isScalarItem)) {
1344
+ out[field.key] = value;
1345
+ continue;
1346
+ }
1347
+ if (value == null && lists.has(field.key)) {
1348
+ out[field.key] = [];
1349
+ continue;
1350
+ }
1351
+ const scalar = value === void 0 || value !== null && typeof value === "object" ? null : value;
1352
+ const target = typeof scalar === "string" ? editField(field.name) : null;
1353
+ out[field.key] = target && links ? links.encode(scalar, target) : scalar;
1354
+ }
1355
+ }
1356
+ return out;
1357
+ }
1358
+ function fillNested(doc, selections, value, ctx) {
1359
+ const one = (item) => {
1360
+ if (!isPlainRecord(item)) return null;
1361
+ const typename = resolveTypename(
1362
+ doc,
1363
+ selections,
1364
+ item.__typename,
1365
+ item.typeName
1366
+ );
1367
+ if (typename === void 0) return null;
1368
+ return fillObject(doc, selections, typename, item, item._id, ctx);
1369
+ };
1370
+ if (Array.isArray(value)) return value.map(one).filter((v) => v !== null);
1371
+ return value === void 0 ? null : one(value);
1372
+ }
1373
+ function isScalarItem(value) {
1374
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
1375
+ }
1376
+ var NO_KEYS = /* @__PURE__ */ new Set();
1377
+ var listKeysCache = /* @__PURE__ */ new WeakMap();
1378
+ function listKeysIn(result) {
1379
+ return (typename) => {
1380
+ if (!typename || result === null || typeof result !== "object") {
1381
+ return NO_KEYS;
1382
+ }
1383
+ let byType = listKeysCache.get(result);
1384
+ if (!byType) {
1385
+ byType = /* @__PURE__ */ new Map();
1386
+ const seen = /* @__PURE__ */ new WeakSet();
1387
+ const walk = (node) => {
1388
+ if (node === null || typeof node !== "object" || seen.has(node)) return;
1389
+ seen.add(node);
1390
+ if (Array.isArray(node)) {
1391
+ node.forEach(walk);
1392
+ return;
1393
+ }
1394
+ const record = node;
1395
+ const type = typeof record.__typename === "string" ? record.__typename : null;
1396
+ for (const [key, value] of Object.entries(record)) {
1397
+ if (type && Array.isArray(value)) {
1398
+ let keys = byType.get(type);
1399
+ if (!keys) byType.set(type, keys = /* @__PURE__ */ new Set());
1400
+ keys.add(key);
1401
+ }
1402
+ walk(value);
1403
+ }
1404
+ };
1405
+ walk(result);
1406
+ listKeysCache.set(result, byType);
1407
+ }
1408
+ return byType.get(typename) ?? NO_KEYS;
1409
+ };
1410
+ }
1411
+ var EDIT_PATH = /\/content\/edit\/[^/?#]+/;
1412
+ function editLinks(result, entry) {
1413
+ const edit = entry.fields?.__edit;
1414
+ if (!isPlainRecord(edit) || typeof edit.item !== "string") return null;
1415
+ return editLinksFor(result, edit.item);
1416
+ }
1417
+ var ITEM_ID = /^[A-Za-z0-9_-]+$/;
1418
+ function editLinksFor(result, item) {
1419
+ if (!ITEM_ID.test(item)) return null;
1420
+ const template = findEditLink(result);
1421
+ if (!template) return null;
1422
+ return {
1423
+ encode(text, field) {
1424
+ if (vercelStegaSplit2(text).encoded) return text;
1425
+ let href;
1426
+ try {
1427
+ href = new URL(template.href);
1428
+ } catch {
1429
+ return text;
1430
+ }
1431
+ href.pathname = href.pathname.replace(
1432
+ EDIT_PATH,
1433
+ () => `/content/edit/${item}`
1434
+ );
1435
+ href.searchParams.set("field", field);
1436
+ const link = href.toString().replace(/%2E/gi, ".").replace(/%2F/gi, "/");
1437
+ return vercelStegaCombine(text, { origin: template.origin, href: link });
1438
+ }
1439
+ };
1440
+ }
1441
+ var linkCache = /* @__PURE__ */ new WeakMap();
1442
+ function findEditLink(root) {
1443
+ if (root === null || typeof root !== "object") return null;
1444
+ if (linkCache.has(root)) return linkCache.get(root) ?? null;
1445
+ let found = null;
1446
+ const seen = /* @__PURE__ */ new WeakSet();
1447
+ const walk = (node) => {
1448
+ if (found) return;
1449
+ if (typeof node === "string") {
1450
+ if (!vercelStegaSplit2(node).encoded) return;
1451
+ try {
1452
+ const decoded = vercelStegaDecode(node);
1453
+ if (typeof decoded?.origin === "string" && typeof decoded.href === "string" && EDIT_PATH.test(decoded.href)) {
1454
+ found = { origin: decoded.origin, href: decoded.href };
1455
+ }
1456
+ } catch {
1457
+ }
1458
+ return;
1459
+ }
1460
+ if (node === null || typeof node !== "object" || seen.has(node)) return;
1461
+ seen.add(node);
1462
+ for (const value of Object.values(node)) walk(value);
1463
+ };
1464
+ walk(root);
1465
+ linkCache.set(root, found);
1466
+ return found;
1467
+ }
1468
+
1469
+ // src/core/live-preview/live-request.ts
1470
+ var MAX_BODY_BYTES = 1e6;
1471
+ async function readLiveLogFromRequest(request) {
1472
+ try {
1473
+ if (request.method !== "POST") return [];
1474
+ if (request.headers.get(HEADER_LIVE_RENDER) !== "1") return [];
1475
+ const origin = request.headers.get("origin");
1476
+ if (!origin || origin !== new URL(request.url).origin) return [];
1477
+ const type = request.headers.get("content-type") ?? "";
1478
+ if (!type.toLowerCase().startsWith("application/json")) return [];
1479
+ const length = Number(request.headers.get("content-length") ?? "0");
1480
+ if (length > MAX_BODY_BYTES) return [];
1481
+ const text = await request.clone().text();
1482
+ if (text.length > MAX_BODY_BYTES) return [];
1483
+ const body = JSON.parse(text);
1484
+ return parsePatchLog(body?.log);
1485
+ } catch {
1486
+ return [];
1487
+ }
1488
+ }
1489
+
332
1490
  // src/astro/index.ts
1491
+ var LIVE_LOG = /* @__PURE__ */ Symbol.for("@preprio/toolkit/astro-live-log");
333
1492
  async function onPreprRequest(context, next, options) {
334
1493
  const { requestHeaders, responseCookies } = processFrameworkRequest(
335
1494
  context.request,
@@ -339,7 +1498,14 @@ async function onPreprRequest(context, next, options) {
339
1498
  requestHeaders.forEach((value, key) => {
340
1499
  context.request.headers.set(key, value);
341
1500
  });
1501
+ const log = options?.preview && context.locals ? await readLiveLogFromRequest(context.request) : [];
1502
+ if (log.length && context.locals) {
1503
+ context.locals[LIVE_LOG] = log;
1504
+ }
342
1505
  const response = await next();
1506
+ if (log.length) {
1507
+ response.headers.set("Cache-Control", "private, no-store");
1508
+ }
343
1509
  for (const cookie of responseCookies) {
344
1510
  response.headers.append("Set-Cookie", serializeCookie(cookie));
345
1511
  }
@@ -360,11 +1526,21 @@ function getPreprHeaders(headers) {
360
1526
  async function getToolbarProps(headers, token, features) {
361
1527
  return getToolbarPropsFromHeaders(headers, token, features);
362
1528
  }
1529
+ function normalizeQuery2(query, result, options = {}) {
1530
+ if (!options.enabled || !options.locals) return result;
1531
+ const log = options.locals[LIVE_LOG];
1532
+ if (!log?.length) return result;
1533
+ return normalizeQuery(query, result, {
1534
+ log,
1535
+ operationName: options.operationName
1536
+ });
1537
+ }
363
1538
  export {
364
1539
  getActiveSegment,
365
1540
  getActiveVariant,
366
1541
  getPreprHeaders,
367
1542
  getPreprUUID,
368
1543
  getToolbarProps,
1544
+ normalizeQuery2 as normalizeQuery,
369
1545
  onPreprRequest
370
1546
  };