@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
@@ -2,7 +2,7 @@
2
2
  import { NextResponse } from "next/server";
3
3
 
4
4
  // src/version.ts
5
- var VERSION = "0.5.0-rc.2";
5
+ var VERSION = "0.5.0-rc.3";
6
6
 
7
7
  // src/core/constants.ts
8
8
  var COOKIE_PREVIEW_MODE = "Prepr-Preview-Mode";
@@ -47,9 +47,9 @@ function sanitizeHeaderValue(value) {
47
47
  return stripped.length > MAX_HEADER_VALUE_LENGTH ? stripped.slice(0, MAX_HEADER_VALUE_LENGTH) : stripped;
48
48
  }
49
49
  function parseCookies(request) {
50
- const cookies = /* @__PURE__ */ new Map();
50
+ const cookies2 = /* @__PURE__ */ new Map();
51
51
  const header = request.headers.get("cookie");
52
- if (!header) return cookies;
52
+ if (!header) return cookies2;
53
53
  for (const part of header.split(";")) {
54
54
  const eq = part.indexOf("=");
55
55
  if (eq === -1) continue;
@@ -57,12 +57,12 @@ function parseCookies(request) {
57
57
  const value = part.slice(eq + 1).trim();
58
58
  if (!name) continue;
59
59
  try {
60
- cookies.set(name, decodeURIComponent(value));
60
+ cookies2.set(name, decodeURIComponent(value));
61
61
  } catch {
62
- cookies.set(name, value);
62
+ cookies2.set(name, value);
63
63
  }
64
64
  }
65
- return cookies;
65
+ return cookies2;
66
66
  }
67
67
  function processFrameworkRequest(request, opts, framework) {
68
68
  const requestHeaders = new Headers(request.headers);
@@ -227,7 +227,1037 @@ function createPreprMiddleware(request, responseOrOptions, maybeOptions) {
227
227
  }
228
228
 
229
229
  // src/nextjs/server.ts
230
- import { headers } from "next/headers";
230
+ import { cookies, headers } from "next/headers";
231
+ import * as navigation from "next/navigation";
232
+
233
+ // src/core/live-preview/normalize-query.ts
234
+ import {
235
+ vercelStegaCombine,
236
+ vercelStegaDecode,
237
+ vercelStegaSplit as vercelStegaSplit2
238
+ } from "@vercel/stega";
239
+
240
+ // src/core/utils.ts
241
+ var DebugLogger = class {
242
+ constructor(options) {
243
+ this.options = {
244
+ prefix: "[Prepr]",
245
+ ...options
246
+ };
247
+ }
248
+ // A local `enabled` wins; otherwise defer to the global logger so scoped
249
+ // loggers created before initDebugLogger() still pick up the setting.
250
+ isEnabled() {
251
+ if (this.options.enabled !== void 0) {
252
+ return this.options.enabled;
253
+ }
254
+ return globalDebugLogger?.options?.enabled ?? false;
255
+ }
256
+ log(message, ...args) {
257
+ if (!this.isEnabled()) return;
258
+ const prefix = this.options.prefix;
259
+ console.log(`${prefix} ${message}`, ...args);
260
+ }
261
+ warn(message, ...args) {
262
+ if (!this.isEnabled()) return;
263
+ const prefix = this.options.prefix;
264
+ console.warn(`${prefix} ${message}`, ...args);
265
+ }
266
+ error(message, ...args) {
267
+ if (!this.isEnabled()) return;
268
+ const prefix = this.options.prefix;
269
+ console.error(`${prefix} ${message}`, ...args);
270
+ }
271
+ };
272
+ var globalDebugLogger = null;
273
+ function createScopedLogger(scopeName) {
274
+ return new DebugLogger({
275
+ prefix: `[Prepr][${scopeName}]`
276
+ });
277
+ }
278
+
279
+ // src/core/live-preview/field-name.ts
280
+ var UPPERCASE_BOUNDARY = /(.)(?=[A-Z])/g;
281
+ function graphqlFieldName(apiId) {
282
+ return apiId.replace(UPPERCASE_BOUNDARY, "$1_").toLowerCase();
283
+ }
284
+
285
+ // src/core/live-preview/index-snapshot.ts
286
+ var debug = createScopedLogger("live-preview");
287
+ function indexSnapshot(data) {
288
+ const index = /* @__PURE__ */ new Map();
289
+ const visited = /* @__PURE__ */ new WeakSet();
290
+ const path = [];
291
+ function walk(node) {
292
+ if (node === null || typeof node !== "object") return;
293
+ if (visited.has(node)) return;
294
+ visited.add(node);
295
+ if (Array.isArray(node)) {
296
+ for (let i = 0; i < node.length; i++) {
297
+ path.push(i);
298
+ walk(node[i]);
299
+ path.pop();
300
+ }
301
+ return;
302
+ }
303
+ const record = node;
304
+ if (typeof record._id === "string") {
305
+ const paths = index.get(record._id);
306
+ if (paths) paths.push([...path]);
307
+ else index.set(record._id, [[...path]]);
308
+ } else if (typeof record.__typename === "string") {
309
+ debug.log("item without _id will not live-update", {
310
+ __typename: record.__typename
311
+ });
312
+ }
313
+ for (const key in record) {
314
+ if (!Object.prototype.hasOwnProperty.call(record, key)) continue;
315
+ path.push(key);
316
+ walk(record[key]);
317
+ path.pop();
318
+ }
319
+ }
320
+ walk(data);
321
+ return index;
322
+ }
323
+
324
+ // src/core/live-preview/patch.ts
325
+ import { vercelStegaSplit } from "@vercel/stega";
326
+ var FORBIDDEN_SEGMENTS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
327
+ function isPlainObject(value) {
328
+ return value !== null && typeof value === "object" && !Array.isArray(value);
329
+ }
330
+ function mergeObject(current, incoming) {
331
+ let changed = false;
332
+ const next = { ...current };
333
+ for (const key of Object.keys(current)) {
334
+ if (!(key in incoming) || incoming[key] === void 0) continue;
335
+ const value = isPlainObject(current[key]) && isPlainObject(incoming[key]) ? mergeObject(current[key], incoming[key]) : incoming[key];
336
+ if (value !== current[key]) {
337
+ next[key] = value;
338
+ changed = true;
339
+ }
340
+ }
341
+ return changed ? next : current;
342
+ }
343
+ function shapeLike(template, incoming) {
344
+ const out = {};
345
+ for (const key of Object.keys(template)) {
346
+ const value = incoming[key];
347
+ out[key] = value === void 0 ? null : isPlainObject(template[key]) && isPlainObject(value) ? shapeLike(template[key], value) : value;
348
+ }
349
+ return out;
350
+ }
351
+ function mergeStructured(current, incoming) {
352
+ if (incoming === null || Array.isArray(incoming) && !incoming.length) {
353
+ if (Array.isArray(current)) return current.length ? [] : current;
354
+ return null;
355
+ }
356
+ const list = Array.isArray(incoming) ? incoming : [incoming];
357
+ if (current === null || current === void 0) return incoming;
358
+ if (Array.isArray(current)) {
359
+ const template = current.find(isPlainObject);
360
+ return list.map((entry) => {
361
+ const match = current.find(
362
+ (c) => isPlainObject(c) && c._id !== void 0 && c._id === entry._id
363
+ );
364
+ if (isPlainObject(match)) return mergeObject(match, entry);
365
+ return isPlainObject(template) ? shapeLike(template, entry) : entry;
366
+ });
367
+ }
368
+ if (isPlainObject(current)) return mergeObject(current, list[0]);
369
+ return current;
370
+ }
371
+ function isPatchable(current) {
372
+ return current === null || typeof current === "string" || typeof current === "number" || typeof current === "boolean";
373
+ }
374
+ function cloneNode(node) {
375
+ return Array.isArray(node) ? [...node] : { ...node };
376
+ }
377
+ function writeAtPath(root, fullPath, value, markChanged = () => {
378
+ }) {
379
+ if (!fullPath.length) return root;
380
+ if (fullPath.some((s) => FORBIDDEN_SEGMENTS.has(String(s)))) return root;
381
+ const last = fullPath.length - 1;
382
+ let node = root;
383
+ for (let i = 0; i < last; i++) {
384
+ if (node === null || typeof node !== "object") return root;
385
+ node = node[fullPath[i]];
386
+ }
387
+ if (node === null || typeof node !== "object") return root;
388
+ const container = node;
389
+ const key = fullPath[last];
390
+ if (!(key in container)) return root;
391
+ let next;
392
+ if (value === null || typeof value === "object") {
393
+ next = mergeStructured(container[key], value);
394
+ } else if (!isPatchable(container[key])) {
395
+ return root;
396
+ } else {
397
+ next = keepEditLink(container[key], value);
398
+ }
399
+ if (container[key] === next) return root;
400
+ const newRoot = cloneNode(root);
401
+ let cursor = newRoot;
402
+ for (let i = 0; i < last; i++) {
403
+ const child = cloneNode(cursor[fullPath[i]]);
404
+ cursor[fullPath[i]] = child;
405
+ cursor = child;
406
+ }
407
+ cursor[key] = next;
408
+ markChanged();
409
+ return newRoot;
410
+ }
411
+ function listKeysOf(entry) {
412
+ if (!isPlainObject(entry)) return [];
413
+ const keys = [];
414
+ if (typeof entry._id === "string") keys.push(entry._id);
415
+ const first = Array.isArray(entry.items) ? entry.items[0] : null;
416
+ if (isPlainObject(first) && typeof first._id === "string") {
417
+ keys.push(first._id);
418
+ }
419
+ return keys;
420
+ }
421
+ var TAG_PATTERN = /<[^>]+>/g;
422
+ function buildText(entry, template) {
423
+ const body = typeof entry.body === "string" ? entry.body : "";
424
+ const full = {
425
+ __typename: "Text",
426
+ _id: entry._id,
427
+ body,
428
+ html: body,
429
+ text: body.replace(TAG_PATTERN, ""),
430
+ format: entry.format ?? null
431
+ };
432
+ if (!template) return full;
433
+ const out = {};
434
+ for (const key of Object.keys(template)) {
435
+ out[key] = key in full ? full[key] : null;
436
+ }
437
+ return out;
438
+ }
439
+ function syncList(current, entries, build) {
440
+ if (current === null || current === void 0) {
441
+ const built = syncList([], entries, build);
442
+ return built.length ? built : current;
443
+ }
444
+ if (!Array.isArray(current)) return current;
445
+ const byKey = /* @__PURE__ */ new Map();
446
+ const templates = /* @__PURE__ */ new Map();
447
+ for (const c of current) {
448
+ for (const key of listKeysOf(c)) byKey.set(key, c);
449
+ if (isPlainObject(c) && typeof c.__typename === "string") {
450
+ if (!templates.has(c.__typename)) templates.set(c.__typename, c);
451
+ }
452
+ }
453
+ if (!entries.length) return current.length ? [] : current;
454
+ if (current.length && !byKey.size) return current;
455
+ if (current.length && !entries.some((e) => byKey.has(e._id))) return current;
456
+ const next = [];
457
+ for (const entry of entries) {
458
+ const existing = byKey.get(entry._id);
459
+ const built = existing === void 0 && entry.fields ? build?.(entry) : void 0;
460
+ if (existing !== void 0) {
461
+ next.push(existing);
462
+ } else if (built) {
463
+ next.push(built);
464
+ } else if (entry.__typename === "Text") {
465
+ next.push(buildText(entry, templates.get("Text")));
466
+ }
467
+ }
468
+ const same = next.length === current.length && next.every((n, i) => n === current[i]);
469
+ return same ? current : next;
470
+ }
471
+ function syncListAtPath(root, fullPath, entries, build) {
472
+ if (!fullPath.length) return root;
473
+ if (fullPath.some((s) => FORBIDDEN_SEGMENTS.has(String(s)))) return root;
474
+ let node = root;
475
+ for (const key of fullPath) {
476
+ node = node !== null && typeof node === "object" ? node[key] : void 0;
477
+ }
478
+ const next = syncList(node, entries, build);
479
+ if (next === node) return root;
480
+ const newRoot = cloneNode(root);
481
+ let cursor = newRoot;
482
+ for (let i = 0; i < fullPath.length - 1; i++) {
483
+ const child = cloneNode(cursor[fullPath[i]]);
484
+ cursor[fullPath[i]] = child;
485
+ cursor = child;
486
+ }
487
+ cursor[fullPath[fullPath.length - 1]] = next;
488
+ return newRoot;
489
+ }
490
+ function keepEditLink(current, value) {
491
+ if (typeof current !== "string" || typeof value !== "string") return value;
492
+ const { encoded } = vercelStegaSplit(current);
493
+ if (!encoded || vercelStegaSplit(value).encoded) return value;
494
+ return value + encoded;
495
+ }
496
+
497
+ // src/core/live-preview/query-document.ts
498
+ var NAME_START = /[_A-Za-z]/;
499
+ var NAME_CONTINUE = /[_0-9A-Za-z]/;
500
+ var PUNCT = /* @__PURE__ */ new Set([
501
+ "!",
502
+ "$",
503
+ "&",
504
+ "(",
505
+ ")",
506
+ ":",
507
+ "=",
508
+ "@",
509
+ "[",
510
+ "]",
511
+ "{",
512
+ "|",
513
+ "}"
514
+ ]);
515
+ function tokenize(source) {
516
+ const tokens = [];
517
+ let i = 0;
518
+ const n = source.length;
519
+ while (i < n) {
520
+ const ch = source[i];
521
+ if (ch === " " || ch === " " || ch === "\n" || ch === "\r" || ch === "," || ch === "\uFEFF") {
522
+ i++;
523
+ } else if (ch === "#") {
524
+ while (i < n && source[i] !== "\n" && source[i] !== "\r") i++;
525
+ } else if (ch === "." && source.startsWith("...", i)) {
526
+ tokens.push({ type: "punct", value: "..." });
527
+ i += 3;
528
+ } else if (PUNCT.has(ch)) {
529
+ tokens.push({ type: "punct", value: ch });
530
+ i++;
531
+ } else if (NAME_START.test(ch)) {
532
+ const start = i;
533
+ while (i < n && NAME_CONTINUE.test(source[i])) i++;
534
+ tokens.push({ type: "name", value: source.slice(start, i) });
535
+ } else if (ch === '"') {
536
+ if (source.startsWith('"""', i)) {
537
+ i += 3;
538
+ while (i < n && !source.startsWith('"""', i)) {
539
+ i += source.startsWith('\\"""', i) ? 4 : 1;
540
+ }
541
+ if (i >= n) throw new SyntaxError("Unterminated block string");
542
+ i += 3;
543
+ } else {
544
+ i++;
545
+ while (i < n && source[i] !== '"') {
546
+ if (source[i] === "\n" || source[i] === "\r") {
547
+ throw new SyntaxError("Unterminated string");
548
+ }
549
+ i += source[i] === "\\" ? 2 : 1;
550
+ }
551
+ if (i >= n) throw new SyntaxError("Unterminated string");
552
+ i++;
553
+ }
554
+ tokens.push({ type: "value" });
555
+ } else if (ch === "-" || ch >= "0" && ch <= "9") {
556
+ i++;
557
+ while (i < n && /[0-9.eE+-]/.test(source[i])) i++;
558
+ tokens.push({ type: "value" });
559
+ } else {
560
+ throw new SyntaxError(`Unexpected character "${ch}"`);
561
+ }
562
+ }
563
+ return tokens;
564
+ }
565
+ function parseSource(source, operationName) {
566
+ const tokens = tokenize(source);
567
+ let pos = 0;
568
+ const peek = () => tokens[pos];
569
+ const isPunct = (value) => {
570
+ const t = tokens[pos];
571
+ return t?.type === "punct" && t.value === value;
572
+ };
573
+ const expectPunct = (value) => {
574
+ if (!isPunct(value)) throw new SyntaxError(`Expected "${value}"`);
575
+ pos++;
576
+ };
577
+ const expectName = () => {
578
+ const t = tokens[pos];
579
+ if (t?.type !== "name") throw new SyntaxError("Expected a name");
580
+ pos++;
581
+ return t.value;
582
+ };
583
+ const skipParens = () => {
584
+ expectPunct("(");
585
+ let depth = 1;
586
+ while (depth > 0) {
587
+ const t = tokens[pos++];
588
+ if (!t) throw new SyntaxError("Unbalanced parentheses");
589
+ if (t.type === "punct" && t.value === "(") depth++;
590
+ else if (t.type === "punct" && t.value === ")") depth--;
591
+ }
592
+ };
593
+ const skipDirectives = () => {
594
+ while (isPunct("@")) {
595
+ pos++;
596
+ expectName();
597
+ if (isPunct("(")) skipParens();
598
+ }
599
+ };
600
+ const parseSelectionSet = () => {
601
+ expectPunct("{");
602
+ const selections = [];
603
+ while (!isPunct("}")) {
604
+ if (!peek()) throw new SyntaxError("Unterminated selection set");
605
+ selections.push(parseSelection());
606
+ }
607
+ pos++;
608
+ return selections;
609
+ };
610
+ const parseSelection = () => {
611
+ if (isPunct("...")) {
612
+ pos++;
613
+ const t = peek();
614
+ if (t?.type === "name" && t.value !== "on") {
615
+ pos++;
616
+ skipDirectives();
617
+ return { kind: "spread", name: t.value };
618
+ }
619
+ let on = null;
620
+ if (t?.type === "name") {
621
+ pos++;
622
+ on = expectName();
623
+ }
624
+ skipDirectives();
625
+ return { kind: "inline", on, selections: parseSelectionSet() };
626
+ }
627
+ let name = expectName();
628
+ const key = name;
629
+ if (isPunct(":")) {
630
+ pos++;
631
+ name = expectName();
632
+ }
633
+ let hasArgs = false;
634
+ if (isPunct("(")) {
635
+ hasArgs = true;
636
+ skipParens();
637
+ }
638
+ skipDirectives();
639
+ const selections = isPunct("{") ? parseSelectionSet() : null;
640
+ return { kind: "field", name, key, hasArgs, selections };
641
+ };
642
+ const fragments = /* @__PURE__ */ new Map();
643
+ const operations = [];
644
+ while (pos < tokens.length) {
645
+ if (isPunct("{")) {
646
+ operations.push({ name: null, selections: parseSelectionSet() });
647
+ continue;
648
+ }
649
+ const keyword = expectName();
650
+ if (keyword === "fragment") {
651
+ const name = expectName();
652
+ if (expectName() !== "on") throw new SyntaxError('Expected "on"');
653
+ const on = expectName();
654
+ skipDirectives();
655
+ fragments.set(name, { on, selections: parseSelectionSet() });
656
+ } else if (keyword === "query" || keyword === "mutation" || keyword === "subscription") {
657
+ const t = peek();
658
+ let name = null;
659
+ if (t?.type === "name") name = expectName();
660
+ if (isPunct("(")) skipParens();
661
+ skipDirectives();
662
+ operations.push({ name, selections: parseSelectionSet() });
663
+ } else {
664
+ throw new SyntaxError(`Unexpected "${keyword}"`);
665
+ }
666
+ }
667
+ return { operation: pickOperation(operations, operationName), fragments };
668
+ }
669
+ function pickOperation(operations, operationName) {
670
+ const op = operationName ? operations.find((o) => o.name === operationName) : operations[0];
671
+ if (!op) throw new SyntaxError("The document has no operation");
672
+ return op.selections;
673
+ }
674
+ function fromAstSelections(set) {
675
+ return set.selections.map((s) => {
676
+ if (s.kind === "FragmentSpread")
677
+ return { kind: "spread", name: s.name.value };
678
+ if (s.kind === "InlineFragment") {
679
+ return {
680
+ kind: "inline",
681
+ on: s.typeCondition?.name.value ?? null,
682
+ selections: fromAstSelections(s.selectionSet)
683
+ };
684
+ }
685
+ const name = s.name.value;
686
+ return {
687
+ kind: "field",
688
+ name,
689
+ key: s.alias?.value ?? name,
690
+ hasArgs: Boolean(s.arguments?.length),
691
+ selections: s.selectionSet ? fromAstSelections(s.selectionSet) : null
692
+ };
693
+ });
694
+ }
695
+ function fromAst(doc, operationName) {
696
+ const fragments = /* @__PURE__ */ new Map();
697
+ const operations = [];
698
+ for (const def of doc.definitions ?? []) {
699
+ if (def.kind === "FragmentDefinition" && def.name && def.typeCondition && def.selectionSet) {
700
+ fragments.set(def.name.value, {
701
+ on: def.typeCondition.name.value,
702
+ selections: fromAstSelections(def.selectionSet)
703
+ });
704
+ } else if (def.kind === "OperationDefinition" && def.selectionSet) {
705
+ operations.push({
706
+ name: def.name?.value ?? null,
707
+ selections: fromAstSelections(def.selectionSet)
708
+ });
709
+ }
710
+ }
711
+ return { operation: pickOperation(operations, operationName), fragments };
712
+ }
713
+ var astCache = /* @__PURE__ */ new WeakMap();
714
+ var sourceCache = /* @__PURE__ */ new Map();
715
+ var SOURCE_CACHE_LIMIT = 200;
716
+ function readQueryDocument(query, operationName) {
717
+ const cacheKey = operationName ?? "";
718
+ if (typeof query === "object" && query !== null && query.kind === "Document") {
719
+ let byName = astCache.get(query);
720
+ if (!byName) astCache.set(query, byName = /* @__PURE__ */ new Map());
721
+ let parsed2 = byName.get(cacheKey);
722
+ if (!parsed2) {
723
+ parsed2 = fromAst(
724
+ query,
725
+ operationName
726
+ );
727
+ byName.set(cacheKey, parsed2);
728
+ }
729
+ return parsed2;
730
+ }
731
+ const source = String(query);
732
+ const sourceKey = `${cacheKey}
733
+ ${source}`;
734
+ let parsed = sourceCache.get(sourceKey);
735
+ if (!parsed) {
736
+ parsed = parseSource(source, operationName);
737
+ if (sourceCache.size >= SOURCE_CACHE_LIMIT) {
738
+ sourceCache.delete(sourceCache.keys().next().value);
739
+ }
740
+ sourceCache.set(sourceKey, parsed);
741
+ }
742
+ return parsed;
743
+ }
744
+ var fieldsCache = /* @__PURE__ */ new WeakMap();
745
+ function collectFields(selections, typename, doc, options = {}) {
746
+ const cacheKey = `${options.strict ? "s" : "l"}:${typename ?? ""}`;
747
+ let cached = fieldsCache.get(selections);
748
+ if (!cached) {
749
+ cached = /* @__PURE__ */ new Map();
750
+ fieldsCache.set(selections, cached);
751
+ }
752
+ const hit = cached.get(cacheKey);
753
+ if (hit) return hit;
754
+ const fields = resolveFields(selections, typename, doc, options);
755
+ cached.set(cacheKey, fields);
756
+ return fields;
757
+ }
758
+ function resolveFields(selections, typename, doc, options) {
759
+ const exact = /* @__PURE__ */ new Map();
760
+ const loose = /* @__PURE__ */ new Map();
761
+ const merged = /* @__PURE__ */ new Map();
762
+ const walkedMatched = /* @__PURE__ */ new Set();
763
+ const walkedLoose = /* @__PURE__ */ new Set();
764
+ const add = (target, s) => {
765
+ let field = target.get(s.key);
766
+ if (!field) {
767
+ field = { name: s.name, key: s.key, hasArgs: s.hasArgs, selections: [] };
768
+ target.set(s.key, field);
769
+ merged.set(field, /* @__PURE__ */ new Set());
770
+ }
771
+ const done = merged.get(field);
772
+ if (s.selections && !done.has(s.selections)) {
773
+ done.add(s.selections);
774
+ field.selections = [...field.selections, ...s.selections];
775
+ }
776
+ };
777
+ const applies = (on, list) => conditionMatches(on, typename) || typename !== void 0 && typeConditions(list, doc).includes(typename);
778
+ const walk = (list, matched) => {
779
+ for (const s of list) {
780
+ if (s.kind === "field") {
781
+ add(matched ? exact : loose, s);
782
+ } else if (s.kind === "inline") {
783
+ walk(s.selections, matched && applies(s.on, s.selections));
784
+ } else {
785
+ const fragment = doc.fragments.get(s.name);
786
+ if (!fragment) continue;
787
+ const asMatched = matched && applies(fragment.on, fragment.selections);
788
+ if (walkedMatched.has(fragment)) continue;
789
+ if (!asMatched && walkedLoose.has(fragment)) continue;
790
+ (asMatched ? walkedMatched : walkedLoose).add(fragment);
791
+ walk(fragment.selections, asMatched);
792
+ }
793
+ }
794
+ };
795
+ walk(selections, true);
796
+ if (!options.strict) {
797
+ for (const [key, field] of loose) {
798
+ if (!exact.has(key)) exact.set(key, field);
799
+ }
800
+ }
801
+ return exact;
802
+ }
803
+ function conditionMatches(on, typename) {
804
+ return on === null || typename === void 0 || on === typename;
805
+ }
806
+ var conditionsCache = /* @__PURE__ */ new WeakMap();
807
+ function typeConditions(selections, doc) {
808
+ const hit = conditionsCache.get(selections);
809
+ if (hit) return hit;
810
+ const names = /* @__PURE__ */ new Set();
811
+ const seen = /* @__PURE__ */ new Set();
812
+ const walk = (list) => {
813
+ for (const s of list) {
814
+ if (s.kind === "inline") {
815
+ if (s.on) names.add(s.on);
816
+ walk(s.selections);
817
+ } else if (s.kind === "spread") {
818
+ const fragment = doc.fragments.get(s.name);
819
+ if (!fragment || seen.has(fragment)) continue;
820
+ seen.add(fragment);
821
+ names.add(fragment.on);
822
+ walk(fragment.selections);
823
+ }
824
+ }
825
+ };
826
+ walk(selections);
827
+ const conditions = [...names];
828
+ conditionsCache.set(selections, conditions);
829
+ return conditions;
830
+ }
831
+
832
+ // src/core/live-preview/validate.ts
833
+ function isPlainRecord(v) {
834
+ return v !== null && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype;
835
+ }
836
+
837
+ // src/core/live-preview/normalize-query.ts
838
+ var debug2 = createScopedLogger("live-preview:normalize");
839
+ var INDEX_SEGMENT = /^\d+$/;
840
+ var FORBIDDEN_SEGMENTS2 = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
841
+ var ENVELOPE_KEYS = /* @__PURE__ */ new Set(["data", "errors", "extensions"]);
842
+ function applyPatchLog(query, result, log, operationName) {
843
+ if (!log.length || result === null || typeof result !== "object") {
844
+ return result;
845
+ }
846
+ if (isEnvelope(result)) {
847
+ const data = applyPatchLog(query, result.data, log, operationName);
848
+ return data === result.data ? result : { ...result, data };
849
+ }
850
+ let doc = null;
851
+ try {
852
+ doc = readQueryDocument(query, operationName);
853
+ } catch (error) {
854
+ debug2.log("could not read the query; applying fields by literal path", {
855
+ error: String(error)
856
+ });
857
+ }
858
+ let root = result;
859
+ let index = null;
860
+ for (const patch of log) {
861
+ try {
862
+ index ?? (index = indexSnapshot(root));
863
+ const next = applyPatch(root, index, patch, doc, result);
864
+ if (next !== root) {
865
+ root = next;
866
+ if (patch.type === "list" || !isScalarValue(patch.value)) {
867
+ index = null;
868
+ }
869
+ }
870
+ } catch (error) {
871
+ debug2.log("could not apply a change", {
872
+ itemId: patch.itemId,
873
+ field: patch.field,
874
+ error: String(error)
875
+ });
876
+ }
877
+ }
878
+ return root;
879
+ }
880
+ function isScalarValue(value) {
881
+ return value === null || typeof value !== "object";
882
+ }
883
+ function applyPatch(root, index, patch, doc, result) {
884
+ const ownerPaths = index.get(patch.itemId);
885
+ if (!ownerPaths?.length) return root;
886
+ const segments = patch.field.split(".");
887
+ if (segments.some((s) => !s || FORBIDDEN_SEGMENTS2.has(s))) return root;
888
+ const targets = [];
889
+ for (const ownerPath of ownerPaths) {
890
+ if (doc) {
891
+ const resolved = resolveTargets(root, doc, ownerPath, segments);
892
+ root = resolved.root;
893
+ targets.push(...resolved.targets);
894
+ } else {
895
+ targets.push([...ownerPath, ...segments.map(toPathSegment)]);
896
+ }
897
+ }
898
+ if (!targets.length) {
899
+ debug2.log("no field in the query matches", {
900
+ itemId: patch.itemId,
901
+ field: patch.field
902
+ });
903
+ return root;
904
+ }
905
+ if (patch.type === "field") {
906
+ for (const target of targets) {
907
+ let value = keepEditLink(readAtPath(root, target), patch.value);
908
+ if (patch.edit && typeof value === "string" && !vercelStegaSplit2(value).encoded) {
909
+ value = editLinksFor(result, patch.edit.item)?.encode(
910
+ value,
911
+ patch.edit.field
912
+ ) ?? value;
913
+ }
914
+ root = writeAtPath(root, target, value);
915
+ }
916
+ } else {
917
+ for (const target of targets) {
918
+ const selections = doc ? selectionsAt(root, doc, target) : null;
919
+ const build = doc && selections ? (entry) => buildEntry(doc, selections, entry, {
920
+ links: editLinks(result, entry),
921
+ lists: listKeysIn(result)
922
+ }) : void 0;
923
+ root = syncListAtPath(root, target, patch.entries, build);
924
+ }
925
+ }
926
+ return root;
927
+ }
928
+ function readAtPath(root, path) {
929
+ let node = root;
930
+ for (const step of path) {
931
+ if (node === null || typeof node !== "object") return void 0;
932
+ node = node[step];
933
+ }
934
+ return node;
935
+ }
936
+ function isEnvelope(value) {
937
+ if (Array.isArray(value) || !("data" in value)) return false;
938
+ return Object.keys(value).every((key) => ENVELOPE_KEYS.has(key));
939
+ }
940
+ function toPathSegment(segment) {
941
+ return INDEX_SEGMENT.test(segment) ? Number(segment) : segment;
942
+ }
943
+ function typenameOf(node) {
944
+ const typename = node.__typename;
945
+ return typeof typename === "string" ? typename : void 0;
946
+ }
947
+ function selectionsAt(root, doc, path) {
948
+ let node = root;
949
+ let selections = doc.operation;
950
+ for (const step of path) {
951
+ if (Array.isArray(node)) {
952
+ node = node[step];
953
+ continue;
954
+ }
955
+ if (node === null || typeof node !== "object") return null;
956
+ const field = collectFields(selections, typenameOf(node), doc).get(
957
+ String(step)
958
+ );
959
+ if (!field) return null;
960
+ selections = field.selections;
961
+ node = node[String(step)];
962
+ }
963
+ return selections;
964
+ }
965
+ function resolveTargets(root, doc, ownerPath, segments) {
966
+ let owner = root;
967
+ for (const step of ownerPath) {
968
+ owner = owner[step];
969
+ }
970
+ const selections = selectionsAt(root, doc, ownerPath);
971
+ if (!selections) return { root, targets: [] };
972
+ let current = root;
973
+ const out = [];
974
+ const walk = (node, sel, i, path) => {
975
+ if (i === segments.length) {
976
+ out.push(path);
977
+ return;
978
+ }
979
+ const segment = segments[i];
980
+ if (Array.isArray(node)) {
981
+ if (INDEX_SEGMENT.test(segment)) {
982
+ const position = Number(segment);
983
+ if (position < node.length) {
984
+ walk(node[position], sel, i + 1, [...path, position]);
985
+ }
986
+ } else if (segment === "items") {
987
+ walk(node, sel, i + 1, path);
988
+ }
989
+ return;
990
+ }
991
+ if (node === null || typeof node !== "object") return;
992
+ const record = node;
993
+ const wanted = graphqlFieldName(segment);
994
+ let matched = false;
995
+ for (const field of collectFields(sel, typenameOf(node), doc).values()) {
996
+ if (field.name !== segment && field.name !== wanted) continue;
997
+ if (!Object.prototype.hasOwnProperty.call(record, field.key)) continue;
998
+ matched = true;
999
+ const fieldPath = [...path, field.key];
1000
+ let value = record[field.key];
1001
+ const next = segments[i + 1];
1002
+ if (value === null && field.selections.length && next !== void 0 && next !== "items" && !INDEX_SEGMENT.test(next)) {
1003
+ const typename = resolveTypename(
1004
+ doc,
1005
+ field.selections,
1006
+ void 0,
1007
+ void 0
1008
+ );
1009
+ if (typename !== void 0) {
1010
+ value = fillObject(doc, field.selections, typename, {}, void 0, {
1011
+ links: null,
1012
+ lists: listKeysIn(root)
1013
+ });
1014
+ current = writeAtPath(current, fieldPath, value);
1015
+ }
1016
+ }
1017
+ walk(value, field.selections, i + 1, fieldPath);
1018
+ }
1019
+ if (!matched && segment === "items") walk(node, sel, i + 1, path);
1020
+ };
1021
+ walk(owner, selections, 0, ownerPath);
1022
+ return { root: current, targets: out };
1023
+ }
1024
+ var NON_ALPHANUMERIC = /[^a-z0-9]/gi;
1025
+ var typeKey = (name) => name.replace(NON_ALPHANUMERIC, "").toLowerCase();
1026
+ function resolveTypename(doc, selections, typename, typeName) {
1027
+ const known = typeConditions(selections, doc);
1028
+ const explicit = typeof typename === "string" ? typename : void 0;
1029
+ if (!known.length) return explicit ?? null;
1030
+ if (explicit && known.includes(explicit)) return explicit;
1031
+ for (const candidate of [explicit, typeName]) {
1032
+ if (typeof candidate !== "string" || !candidate) continue;
1033
+ const match = known.find((name) => typeKey(name) === typeKey(candidate));
1034
+ if (match) return match;
1035
+ }
1036
+ const named = explicit !== void 0 || typeof typeName === "string";
1037
+ return known.length === 1 && !named ? known[0] : void 0;
1038
+ }
1039
+ function buildEntry(doc, selections, entry, ctx) {
1040
+ const typename = resolveTypename(
1041
+ doc,
1042
+ selections,
1043
+ entry.__typename,
1044
+ entry.typeName
1045
+ );
1046
+ if (typename === void 0) return void 0;
1047
+ return fillObject(
1048
+ doc,
1049
+ selections,
1050
+ typename,
1051
+ entry.fields ?? {},
1052
+ entry._id,
1053
+ ctx
1054
+ );
1055
+ }
1056
+ function fillObject(doc, selections, typename, values, id, ctx) {
1057
+ const out = {};
1058
+ const { links } = ctx;
1059
+ const lists = ctx.lists(typename);
1060
+ const edit = isPlainRecord(values.__edit) ? values.__edit : null;
1061
+ const apiIdOf = /* @__PURE__ */ new Map();
1062
+ for (const key of Object.keys(values)) {
1063
+ apiIdOf.set(key, key);
1064
+ const name = graphqlFieldName(key);
1065
+ if (!apiIdOf.has(name)) apiIdOf.set(name, key);
1066
+ }
1067
+ if (edit && isPlainRecord(edit.apiIds)) {
1068
+ for (const [name, apiId] of Object.entries(edit.apiIds)) {
1069
+ if (typeof apiId === "string") apiIdOf.set(name, apiId);
1070
+ }
1071
+ }
1072
+ const valueOf = (name) => {
1073
+ if (Object.prototype.hasOwnProperty.call(values, name)) return values[name];
1074
+ const key = apiIdOf.get(name);
1075
+ return key !== void 0 && key in values ? values[key] : void 0;
1076
+ };
1077
+ const editField = (name) => {
1078
+ if (!edit) return null;
1079
+ if (typeof edit.field === "string")
1080
+ return name === "body" ? edit.field : null;
1081
+ if (typeof edit.path !== "string") return null;
1082
+ const apiId = apiIdOf.get(name) ?? name;
1083
+ const text = Array.isArray(edit.text) ? edit.text : [];
1084
+ if (!text.includes(apiId) && !text.includes(name)) return null;
1085
+ return `${edit.path}.items.${apiId}`;
1086
+ };
1087
+ const fields = collectFields(selections, typename ?? void 0, doc, {
1088
+ strict: true
1089
+ });
1090
+ for (const field of fields.values()) {
1091
+ if (field.name === "__typename") {
1092
+ out[field.key] = typename;
1093
+ } else if (field.name === "_id") {
1094
+ out[field.key] = typeof id === "string" ? id : values._id ?? null;
1095
+ } else if (field.selections.length) {
1096
+ const value = valueOf(field.name);
1097
+ out[field.key] = value == null && lists.has(field.key) ? [] : fillNested(doc, field.selections, value, ctx);
1098
+ } else {
1099
+ const value = valueOf(field.name);
1100
+ if (Array.isArray(value) && value.every(isScalarItem)) {
1101
+ out[field.key] = value;
1102
+ continue;
1103
+ }
1104
+ if (value == null && lists.has(field.key)) {
1105
+ out[field.key] = [];
1106
+ continue;
1107
+ }
1108
+ const scalar = value === void 0 || value !== null && typeof value === "object" ? null : value;
1109
+ const target = typeof scalar === "string" ? editField(field.name) : null;
1110
+ out[field.key] = target && links ? links.encode(scalar, target) : scalar;
1111
+ }
1112
+ }
1113
+ return out;
1114
+ }
1115
+ function fillNested(doc, selections, value, ctx) {
1116
+ const one = (item) => {
1117
+ if (!isPlainRecord(item)) return null;
1118
+ const typename = resolveTypename(
1119
+ doc,
1120
+ selections,
1121
+ item.__typename,
1122
+ item.typeName
1123
+ );
1124
+ if (typename === void 0) return null;
1125
+ return fillObject(doc, selections, typename, item, item._id, ctx);
1126
+ };
1127
+ if (Array.isArray(value)) return value.map(one).filter((v) => v !== null);
1128
+ return value === void 0 ? null : one(value);
1129
+ }
1130
+ function isScalarItem(value) {
1131
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
1132
+ }
1133
+ var NO_KEYS = /* @__PURE__ */ new Set();
1134
+ var listKeysCache = /* @__PURE__ */ new WeakMap();
1135
+ function listKeysIn(result) {
1136
+ return (typename) => {
1137
+ if (!typename || result === null || typeof result !== "object") {
1138
+ return NO_KEYS;
1139
+ }
1140
+ let byType = listKeysCache.get(result);
1141
+ if (!byType) {
1142
+ byType = /* @__PURE__ */ new Map();
1143
+ const seen = /* @__PURE__ */ new WeakSet();
1144
+ const walk = (node) => {
1145
+ if (node === null || typeof node !== "object" || seen.has(node)) return;
1146
+ seen.add(node);
1147
+ if (Array.isArray(node)) {
1148
+ node.forEach(walk);
1149
+ return;
1150
+ }
1151
+ const record = node;
1152
+ const type = typeof record.__typename === "string" ? record.__typename : null;
1153
+ for (const [key, value] of Object.entries(record)) {
1154
+ if (type && Array.isArray(value)) {
1155
+ let keys = byType.get(type);
1156
+ if (!keys) byType.set(type, keys = /* @__PURE__ */ new Set());
1157
+ keys.add(key);
1158
+ }
1159
+ walk(value);
1160
+ }
1161
+ };
1162
+ walk(result);
1163
+ listKeysCache.set(result, byType);
1164
+ }
1165
+ return byType.get(typename) ?? NO_KEYS;
1166
+ };
1167
+ }
1168
+ var EDIT_PATH = /\/content\/edit\/[^/?#]+/;
1169
+ function editLinks(result, entry) {
1170
+ const edit = entry.fields?.__edit;
1171
+ if (!isPlainRecord(edit) || typeof edit.item !== "string") return null;
1172
+ return editLinksFor(result, edit.item);
1173
+ }
1174
+ var ITEM_ID = /^[A-Za-z0-9_-]+$/;
1175
+ function editLinksFor(result, item) {
1176
+ if (!ITEM_ID.test(item)) return null;
1177
+ const template = findEditLink(result);
1178
+ if (!template) return null;
1179
+ return {
1180
+ encode(text, field) {
1181
+ if (vercelStegaSplit2(text).encoded) return text;
1182
+ let href;
1183
+ try {
1184
+ href = new URL(template.href);
1185
+ } catch {
1186
+ return text;
1187
+ }
1188
+ href.pathname = href.pathname.replace(
1189
+ EDIT_PATH,
1190
+ () => `/content/edit/${item}`
1191
+ );
1192
+ href.searchParams.set("field", field);
1193
+ const link = href.toString().replace(/%2E/gi, ".").replace(/%2F/gi, "/");
1194
+ return vercelStegaCombine(text, { origin: template.origin, href: link });
1195
+ }
1196
+ };
1197
+ }
1198
+ var linkCache = /* @__PURE__ */ new WeakMap();
1199
+ function findEditLink(root) {
1200
+ if (root === null || typeof root !== "object") return null;
1201
+ if (linkCache.has(root)) return linkCache.get(root) ?? null;
1202
+ let found = null;
1203
+ const seen = /* @__PURE__ */ new WeakSet();
1204
+ const walk = (node) => {
1205
+ if (found) return;
1206
+ if (typeof node === "string") {
1207
+ if (!vercelStegaSplit2(node).encoded) return;
1208
+ try {
1209
+ const decoded = vercelStegaDecode(node);
1210
+ if (typeof decoded?.origin === "string" && typeof decoded.href === "string" && EDIT_PATH.test(decoded.href)) {
1211
+ found = { origin: decoded.origin, href: decoded.href };
1212
+ }
1213
+ } catch {
1214
+ }
1215
+ return;
1216
+ }
1217
+ if (node === null || typeof node !== "object" || seen.has(node)) return;
1218
+ seen.add(node);
1219
+ for (const value of Object.values(node)) walk(value);
1220
+ };
1221
+ walk(root);
1222
+ linkCache.set(root, found);
1223
+ return found;
1224
+ }
1225
+
1226
+ // src/nextjs/server.ts
1227
+ import * as React from "react";
1228
+
1229
+ // src/nextjs/live-log.ts
1230
+ var LIVE_LOG_COOKIE = "__prepr_live";
1231
+ var MAX_SLOTS = 50;
1232
+ var TOKEN_PATTERN = /^[0-9a-f]{32}$/;
1233
+ var KEY = /* @__PURE__ */ Symbol.for("@preprio/toolkit/live-log");
1234
+ function slots() {
1235
+ const holder = globalThis;
1236
+ let map = holder[KEY];
1237
+ if (!map) {
1238
+ map = /* @__PURE__ */ new Map();
1239
+ holder[KEY] = map;
1240
+ }
1241
+ return map;
1242
+ }
1243
+ function prune(map, now) {
1244
+ for (const [token, slot] of map) {
1245
+ if (slot.expires <= now) map.delete(token);
1246
+ }
1247
+ while (map.size >= MAX_SLOTS) {
1248
+ map.delete(map.keys().next().value);
1249
+ }
1250
+ }
1251
+ function takeLiveLog(token) {
1252
+ if (!token || !TOKEN_PATTERN.test(token)) return [];
1253
+ const map = slots();
1254
+ const slot = map.get(token);
1255
+ map.delete(token);
1256
+ const now = Date.now();
1257
+ prune(map, now);
1258
+ if (!slot || slot.expires <= now) return [];
1259
+ return slot.log;
1260
+ }
231
1261
 
232
1262
  // src/core/server.ts
233
1263
  var PreprError = class extends Error {
@@ -416,6 +1446,27 @@ async function getToolbarProps(token, features) {
416
1446
  const h = await readHeaders();
417
1447
  return getToolbarPropsFromHeaders(h, token, features);
418
1448
  }
1449
+ var HEADER_NEXT_ACTION = "next-action";
1450
+ var cacheForRender = React.cache ?? ((fn) => fn);
1451
+ var getPreprLiveLog = cacheForRender(
1452
+ async () => {
1453
+ let token;
1454
+ try {
1455
+ if (!(await headers()).has(HEADER_NEXT_ACTION)) return [];
1456
+ token = (await cookies()).get(LIVE_LOG_COOKIE)?.value;
1457
+ } catch (error) {
1458
+ navigation.unstable_rethrow?.(error);
1459
+ return [];
1460
+ }
1461
+ return takeLiveLog(token);
1462
+ }
1463
+ );
1464
+ async function normalizeQuery(query, result, options = {}) {
1465
+ if (!options.enabled) return result;
1466
+ const log = await getPreprLiveLog();
1467
+ if (!log.length) return result;
1468
+ return applyPatchLog(query, result, log, options.operationName);
1469
+ }
419
1470
 
420
1471
  // src/nextjs/index.ts
421
1472
  import {
@@ -433,5 +1484,6 @@ export {
433
1484
  getPreprHeaders,
434
1485
  getPreprUUID,
435
1486
  getToolbarProps,
1487
+ normalizeQuery,
436
1488
  validatePreprToken
437
1489
  };