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