@preprio/toolkit 0.6.0-alpha.9 → 1.0.0-rc.1

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 (116) hide show
  1. package/README.md +111 -1363
  2. package/dist/astro/index.cjs +1555 -182
  3. package/dist/astro/index.d.cts +201 -1
  4. package/dist/astro/index.d.ts +201 -1
  5. package/dist/astro/index.js +1557 -29
  6. package/dist/{chunk-5QIWVDP2.js → chunk-33GWVTRJ.js} +1 -1
  7. package/dist/chunk-A2J7R4LR.js +256 -0
  8. package/dist/{chunk-WQBKQG4R.js → chunk-DSJ22P6J.js} +6 -1
  9. package/dist/chunk-KM2GME62.js +1255 -0
  10. package/dist/chunk-UTKH7DOI.js +58 -0
  11. package/dist/chunk-V7MCHPE7.js +85 -0
  12. package/dist/{chunk-J66UOCK6.js → chunk-WBMN4L7G.js} +1680 -579
  13. package/dist/chunk-Y7JWV7WV.js +374 -0
  14. package/dist/codegen/index.cjs +82 -0
  15. package/dist/codegen/index.d.cts +70 -0
  16. package/dist/codegen/index.d.ts +70 -0
  17. package/dist/codegen/index.js +64 -0
  18. package/dist/index.cjs +3729 -553
  19. package/dist/index.d.cts +403 -19
  20. package/dist/index.d.ts +403 -19
  21. package/dist/index.js +345 -24
  22. package/dist/live-preview-HCBNBC6C.js +19 -0
  23. package/dist/nextjs/components.cjs +1872 -754
  24. package/dist/nextjs/components.d.cts +5 -51
  25. package/dist/nextjs/components.d.ts +5 -51
  26. package/dist/nextjs/components.js +8 -299
  27. package/dist/nextjs/index.cjs +1228 -181
  28. package/dist/nextjs/index.d.cts +247 -92
  29. package/dist/nextjs/index.d.ts +247 -92
  30. package/dist/nextjs/index.js +1629 -111
  31. package/dist/nextjs/live-action.cjs +298 -0
  32. package/dist/nextjs/live-action.d.cts +12 -0
  33. package/dist/nextjs/live-action.d.ts +12 -0
  34. package/dist/nextjs/live-action.js +68 -0
  35. package/dist/nextjs/live.cjs +2010 -0
  36. package/dist/nextjs/live.d.cts +54 -0
  37. package/dist/nextjs/live.d.ts +54 -0
  38. package/dist/nextjs/live.js +287 -0
  39. package/dist/nuxt/chunk-5RBZPRQN.js +350 -0
  40. package/dist/nuxt/chunk-LUKVPOJ2.js +32 -0
  41. package/dist/nuxt/index.cjs +15 -16
  42. package/dist/nuxt/index.d.cts +167 -6
  43. package/dist/nuxt/index.d.ts +167 -6
  44. package/dist/nuxt/index.js +402 -15
  45. package/dist/nuxt/live-preview-KO4IKWTX.js +1234 -0
  46. package/dist/nuxt/live.cjs +1928 -0
  47. package/dist/nuxt/live.d.cts +45 -0
  48. package/dist/nuxt/live.d.ts +45 -0
  49. package/dist/nuxt/live.js +216 -0
  50. package/dist/{types-BYH9XqmN.d.cts → pixel-DqU7NvgW.d.cts} +102 -5
  51. package/dist/{types-BYH9XqmN.d.ts → pixel-DqU7NvgW.d.ts} +102 -5
  52. package/dist/react/components.cjs +1865 -480
  53. package/dist/react/components.d.cts +43 -8
  54. package/dist/react/components.d.ts +43 -8
  55. package/dist/react/components.js +1865 -480
  56. package/dist/sveltekit/chunk-5RBZPRQN.js +350 -0
  57. package/dist/sveltekit/chunk-LUKVPOJ2.js +32 -0
  58. package/dist/sveltekit/index.cjs +15 -16
  59. package/dist/sveltekit/index.d.cts +111 -10
  60. package/dist/sveltekit/index.d.ts +111 -10
  61. package/dist/sveltekit/index.js +398 -15
  62. package/dist/sveltekit/live-preview-KO4IKWTX.js +1234 -0
  63. package/dist/sveltekit/live.cjs +1940 -0
  64. package/dist/sveltekit/live.d.cts +61 -0
  65. package/dist/sveltekit/live.d.ts +61 -0
  66. package/dist/sveltekit/live.js +220 -0
  67. package/package.json +132 -71
  68. package/src/astro/PreprToolbar.astro +7 -1
  69. package/src/astro/PreprTrackingPixel.astro +2 -4
  70. package/src/nuxt/PreprToolbar.vue +12 -1
  71. package/src/nuxt/PreprTrackingPixel.vue +2 -4
  72. package/src/sveltekit/PreprToolbar.svelte +17 -2
  73. package/src/sveltekit/PreprTrackingPixel.svelte +2 -4
  74. package/dist/astro/chunk-UN4JADNU.js +0 -173
  75. package/dist/astro/graphql.cjs +0 -1078
  76. package/dist/astro/graphql.d.cts +0 -300
  77. package/dist/astro/graphql.d.ts +0 -300
  78. package/dist/astro/graphql.js +0 -984
  79. package/dist/astro/index-XT_z-RYT.d.cts +0 -130
  80. package/dist/astro/index-XT_z-RYT.d.ts +0 -130
  81. package/dist/chunk-3NCEVJJ3.js +0 -10
  82. package/dist/chunk-S5RWVMDJ.js +0 -148
  83. package/dist/chunk-XL4Y7FGW.js +0 -499
  84. package/dist/graphql/codegen.cjs +0 -557
  85. package/dist/graphql/codegen.d.cts +0 -23
  86. package/dist/graphql/codegen.d.ts +0 -23
  87. package/dist/graphql/codegen.js +0 -99
  88. package/dist/graphql.cjs +0 -1020
  89. package/dist/graphql.d.cts +0 -335
  90. package/dist/graphql.d.ts +0 -335
  91. package/dist/graphql.js +0 -448
  92. package/dist/nextjs/chunk-CMV6ZP6E.js +0 -549
  93. package/dist/nextjs/graphql.cjs +0 -1836
  94. package/dist/nextjs/graphql.d.cts +0 -498
  95. package/dist/nextjs/graphql.d.ts +0 -498
  96. package/dist/nextjs/graphql.js +0 -1422
  97. package/dist/nextjs/server-BL-sqZvu.d.cts +0 -156
  98. package/dist/nextjs/server-BL-sqZvu.d.ts +0 -156
  99. package/dist/nuxt/chunk-XWOABVMW.js +0 -417
  100. package/dist/nuxt/graphql.cjs +0 -1085
  101. package/dist/nuxt/graphql.d.cts +0 -297
  102. package/dist/nuxt/graphql.d.ts +0 -297
  103. package/dist/nuxt/graphql.js +0 -985
  104. package/dist/nuxt/server-8v6OHbsw.d.cts +0 -158
  105. package/dist/nuxt/server-8v6OHbsw.d.ts +0 -158
  106. package/dist/pixel-DwW7cXJm.d.cts +0 -49
  107. package/dist/pixel-DwW7cXJm.d.ts +0 -49
  108. package/dist/server-Brr1UgtW.d.ts +0 -59
  109. package/dist/server-DJuS3YU0.d.cts +0 -59
  110. package/dist/sveltekit/chunk-3S5RA6G5.js +0 -413
  111. package/dist/sveltekit/graphql.cjs +0 -1091
  112. package/dist/sveltekit/graphql.d.cts +0 -302
  113. package/dist/sveltekit/graphql.d.ts +0 -302
  114. package/dist/sveltekit/graphql.js +0 -991
  115. package/dist/sveltekit/server-CO847mEV.d.cts +0 -98
  116. package/dist/sveltekit/server-CO847mEV.d.ts +0 -98
@@ -0,0 +1,1255 @@
1
+ import {
2
+ createScopedLogger
3
+ } from "./chunk-V7MCHPE7.js";
4
+
5
+ // src/core/live-preview/guards.ts
6
+ function isScalar(value) {
7
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
8
+ }
9
+ function isObject(value) {
10
+ return value !== null && typeof value === "object" && !Array.isArray(value);
11
+ }
12
+
13
+ // src/core/live-preview/validate.ts
14
+ var MAX_DEPTH = 3;
15
+ var MAX_ENTRIES = 50;
16
+ var FORBIDDEN_KEYS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
17
+ var SAFE_URL = /^https?:\/\//i;
18
+ var URL_KEY = /^(?:url|href|src|link)$|(?:_url|Url)$/;
19
+ var URL_IGNORED_ANYWHERE = /[\t\n\r]/g;
20
+ var SCRIPT_SCHEME = /^(?:javascript|vbscript|data):/i;
21
+ function isSafeLinkValue(value) {
22
+ const stripped = value.replace(URL_IGNORED_ANYWHERE, "");
23
+ let start = 0;
24
+ while (start < stripped.length && stripped.charCodeAt(start) <= 32) start++;
25
+ return !SCRIPT_SCHEME.test(stripped.slice(start));
26
+ }
27
+ function isUrlKey(key) {
28
+ return URL_KEY.test(key);
29
+ }
30
+ function isSafeKeyValue(key, value) {
31
+ if (typeof value !== "string") return true;
32
+ if (key === "url") return SAFE_URL.test(value);
33
+ return !isUrlKey(key) || isSafeLinkValue(value);
34
+ }
35
+ function isLiveValue(v, depth = 0) {
36
+ if (v === null || isScalar(v)) return true;
37
+ if (depth >= MAX_DEPTH) return false;
38
+ if (Array.isArray(v)) {
39
+ return depth === 0 && v.length <= MAX_ENTRIES && v.every((entry) => isPlainRecord(entry) && isLiveValue(entry, depth + 1));
40
+ }
41
+ if (!isPlainRecord(v)) return false;
42
+ const keys = Object.keys(v);
43
+ if (keys.length > MAX_ENTRIES) return false;
44
+ return keys.every((key) => {
45
+ if (FORBIDDEN_KEYS.has(key)) return false;
46
+ const value = v[key];
47
+ if (!isSafeKeyValue(key, value)) return false;
48
+ return !Array.isArray(value) && isLiveValue(value, depth + 1);
49
+ });
50
+ }
51
+ function isLiveFieldChange(field, value) {
52
+ if (!isLiveValue(value)) return false;
53
+ const name = field.slice(field.lastIndexOf(".") + 1);
54
+ return typeof value !== "string" || !isUrlKey(name) || isSafeLinkValue(value);
55
+ }
56
+ var MAX_LIST_ENTRIES = 200;
57
+ function parseListEntries(value) {
58
+ if (!Array.isArray(value) || value.length > MAX_LIST_ENTRIES) return null;
59
+ const list = [];
60
+ for (const raw of value) {
61
+ if (!isPlainRecord(raw) || typeof raw._id !== "string" || !raw._id) {
62
+ return null;
63
+ }
64
+ const entry = { _id: raw._id };
65
+ if (typeof raw.__typename === "string") entry.__typename = raw.__typename;
66
+ if (typeof raw.body === "string") entry.body = raw.body;
67
+ if (typeof raw.format === "string" || raw.format === null) {
68
+ entry.format = raw.format;
69
+ }
70
+ if (typeof raw.typeName === "string" && raw.typeName.length <= 200) {
71
+ entry.typeName = raw.typeName;
72
+ }
73
+ if (raw.fields !== void 0) {
74
+ if (!isPlainRecord(raw.fields) || !isFieldValue(raw.fields, 0)) {
75
+ return null;
76
+ }
77
+ entry.fields = raw.fields;
78
+ }
79
+ list.push(entry);
80
+ }
81
+ return list;
82
+ }
83
+ function isPlainRecord(v) {
84
+ return v !== null && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype;
85
+ }
86
+ var MAX_FIELD_DEPTH = 6;
87
+ var MAX_FIELD_KEYS = 100;
88
+ function isFieldValue(v, depth) {
89
+ if (v === null || isScalar(v)) return true;
90
+ if (depth >= MAX_FIELD_DEPTH) return false;
91
+ if (Array.isArray(v)) {
92
+ return v.length <= MAX_ENTRIES && v.every(
93
+ (entry) => isScalar(entry) || isPlainRecord(entry) && isFieldValue(entry, depth + 1)
94
+ );
95
+ }
96
+ if (!isPlainRecord(v)) return false;
97
+ const keys = Object.keys(v);
98
+ if (keys.length > MAX_FIELD_KEYS) return false;
99
+ return keys.every((key) => {
100
+ if (FORBIDDEN_KEYS.has(key)) return false;
101
+ const value = v[key];
102
+ if (!isSafeKeyValue(key, value)) return false;
103
+ return isFieldValue(value, depth + 1);
104
+ });
105
+ }
106
+ var MAX_EDIT_LENGTH = 1e3;
107
+ function parseEditTarget(raw) {
108
+ if (!isPlainRecord(raw)) return void 0;
109
+ const { item, field } = raw;
110
+ if (typeof item !== "string" || !item || item.length > MAX_EDIT_LENGTH) {
111
+ return void 0;
112
+ }
113
+ if (typeof field !== "string" || !field || field.length > MAX_EDIT_LENGTH) {
114
+ return void 0;
115
+ }
116
+ return { item, field };
117
+ }
118
+
119
+ // src/core/live-preview/patch-log.ts
120
+ var MAX_LOG_ENTRIES = 500;
121
+ var MAX_LOG_SOURCE_LENGTH = 1e6;
122
+ function parsePatchLog(raw) {
123
+ let value = raw;
124
+ if (typeof value === "string") {
125
+ if (!value || value.length > MAX_LOG_SOURCE_LENGTH) return [];
126
+ try {
127
+ value = JSON.parse(value);
128
+ } catch {
129
+ return [];
130
+ }
131
+ }
132
+ if (!Array.isArray(value)) return [];
133
+ const log = [];
134
+ for (const entry of value.slice(-MAX_LOG_ENTRIES)) {
135
+ if (!isPlainRecord(entry)) continue;
136
+ const { type, itemId, field } = entry;
137
+ if (typeof itemId !== "string" || !itemId) continue;
138
+ if (typeof field !== "string" || !field) continue;
139
+ if (type === "field" && isLiveFieldChange(field, entry.value)) {
140
+ const edit = parseEditTarget(entry.edit);
141
+ log.push(
142
+ edit ? { type, itemId, field, value: entry.value, edit } : { type, itemId, field, value: entry.value }
143
+ );
144
+ } else if (type === "list") {
145
+ const entries = parseListEntries(entry.entries);
146
+ if (entries) log.push({ type, itemId, field, entries });
147
+ }
148
+ }
149
+ return log;
150
+ }
151
+
152
+ // src/core/live-preview/entry-edit-links.ts
153
+ import {
154
+ vercelStegaCombine,
155
+ vercelStegaDecode,
156
+ vercelStegaSplit
157
+ } from "@vercel/stega";
158
+ var EDIT_PATH = /\/content\/edit\/[^/?#]+/;
159
+ function editLinks(result, entry) {
160
+ const edit = entry.fields?.__edit;
161
+ if (!isPlainRecord(edit) || typeof edit.item !== "string") return null;
162
+ return editLinksFor(result, edit.item);
163
+ }
164
+ var ITEM_ID = /^[A-Za-z0-9_-]+$/;
165
+ function editLinksFor(result, item) {
166
+ if (!ITEM_ID.test(item)) return null;
167
+ const template = findEditLink(result);
168
+ if (!template) return null;
169
+ return {
170
+ encode(text, field) {
171
+ if (vercelStegaSplit(text).encoded) return text;
172
+ let href;
173
+ try {
174
+ href = new URL(template.href);
175
+ } catch {
176
+ return text;
177
+ }
178
+ href.pathname = href.pathname.replace(
179
+ EDIT_PATH,
180
+ () => `/content/edit/${item}`
181
+ );
182
+ href.searchParams.set("field", field);
183
+ const link = href.toString().replace(/%2E/gi, ".").replace(/%2F/gi, "/");
184
+ return vercelStegaCombine(text, { origin: template.origin, href: link });
185
+ }
186
+ };
187
+ }
188
+ var linkCache = /* @__PURE__ */ new WeakMap();
189
+ function findEditLink(root) {
190
+ if (root === null || typeof root !== "object") return null;
191
+ if (linkCache.has(root)) return linkCache.get(root) ?? null;
192
+ let found = null;
193
+ const seen = /* @__PURE__ */ new WeakSet();
194
+ const walk = (node) => {
195
+ if (found) return;
196
+ if (typeof node === "string") {
197
+ if (!vercelStegaSplit(node).encoded) return;
198
+ try {
199
+ const decoded = vercelStegaDecode(node);
200
+ if (typeof decoded?.origin === "string" && typeof decoded.href === "string" && EDIT_PATH.test(decoded.href)) {
201
+ found = { origin: decoded.origin, href: decoded.href };
202
+ }
203
+ } catch {
204
+ }
205
+ return;
206
+ }
207
+ if (node === null || typeof node !== "object" || seen.has(node)) return;
208
+ seen.add(node);
209
+ for (const value of Object.values(node)) walk(value);
210
+ };
211
+ walk(root);
212
+ linkCache.set(root, found);
213
+ return found;
214
+ }
215
+
216
+ // src/core/live-preview/normalize-query.ts
217
+ import { vercelStegaSplit as vercelStegaSplit3 } from "@vercel/stega";
218
+
219
+ // src/core/live-preview/field-name.ts
220
+ var UPPERCASE_BOUNDARY = /(.)(?=[A-Z])/g;
221
+ function graphqlFieldName(apiId) {
222
+ return apiId.replace(UPPERCASE_BOUNDARY, "$1_").toLowerCase();
223
+ }
224
+ function fieldKeyIn(record, apiId) {
225
+ if (Object.prototype.hasOwnProperty.call(record, apiId)) return apiId;
226
+ const name = graphqlFieldName(apiId);
227
+ return Object.prototype.hasOwnProperty.call(record, name) ? name : void 0;
228
+ }
229
+ var TEXT_BODY_FIELDS = [
230
+ { name: "body", plain: false },
231
+ { name: "html", plain: false },
232
+ { name: "text", plain: true }
233
+ ];
234
+ var TAG_PATTERN = /<[^>]+>/g;
235
+ function plainTextFromHtml(html) {
236
+ return html.replace(TAG_PATTERN, "");
237
+ }
238
+ function isTextEntry(record) {
239
+ const typename = record.__typename;
240
+ if (typeof typename === "string") return typename === "Text";
241
+ return "html" in record || "text" in record && "format" in record;
242
+ }
243
+
244
+ // src/core/live-preview/index-snapshot.ts
245
+ var debug = createScopedLogger("live-preview");
246
+ function indexSnapshot(data) {
247
+ const index = /* @__PURE__ */ new Map();
248
+ const visited = /* @__PURE__ */ new WeakSet();
249
+ const path = [];
250
+ function walk(node) {
251
+ if (node === null || typeof node !== "object") return;
252
+ if (visited.has(node)) return;
253
+ visited.add(node);
254
+ if (Array.isArray(node)) {
255
+ for (let i = 0; i < node.length; i++) {
256
+ path.push(i);
257
+ walk(node[i]);
258
+ path.pop();
259
+ }
260
+ return;
261
+ }
262
+ const record = node;
263
+ if (typeof record._id === "string") {
264
+ const paths = index.get(record._id);
265
+ if (paths) paths.push([...path]);
266
+ else index.set(record._id, [[...path]]);
267
+ } else if (typeof record.__typename === "string") {
268
+ debug.log("item without _id will not live-update", {
269
+ __typename: record.__typename
270
+ });
271
+ }
272
+ for (const key in record) {
273
+ if (!Object.prototype.hasOwnProperty.call(record, key)) continue;
274
+ path.push(key);
275
+ walk(record[key]);
276
+ path.pop();
277
+ }
278
+ }
279
+ walk(data);
280
+ return index;
281
+ }
282
+
283
+ // src/core/live-preview/patch.ts
284
+ import { vercelStegaSplit as vercelStegaSplit2 } from "@vercel/stega";
285
+ var INDEX_SEGMENT = /^\d+$/;
286
+ var FORBIDDEN_SEGMENTS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
287
+ function mergeObject(current, incoming) {
288
+ let changed = false;
289
+ const next = { ...current };
290
+ for (const key of Object.keys(current)) {
291
+ if (!(key in incoming) || incoming[key] === void 0) continue;
292
+ const value = isObject(current[key]) && isObject(incoming[key]) ? mergeObject(current[key], incoming[key]) : incoming[key];
293
+ if (value !== current[key]) {
294
+ next[key] = value;
295
+ changed = true;
296
+ }
297
+ }
298
+ return changed ? next : current;
299
+ }
300
+ function shapeLike(template, incoming) {
301
+ const out = {};
302
+ for (const key of Object.keys(template)) {
303
+ const value = incoming[key];
304
+ out[key] = value === void 0 ? null : isObject(template[key]) && isObject(value) ? shapeLike(template[key], value) : value;
305
+ }
306
+ return out;
307
+ }
308
+ function isAsset(value) {
309
+ return isObject(value) && (typeof value.url === "string" || value.__typename === "Asset");
310
+ }
311
+ function hasId(list, entry) {
312
+ return entry._id !== void 0 && list.some((c) => isObject(c) && c._id === entry._id);
313
+ }
314
+ function isAssetValue(value) {
315
+ return Array.isArray(value) ? value.length > 0 && value.every(isAsset) : isAsset(value);
316
+ }
317
+ function keepRemovedAssets(current, next) {
318
+ const listed = /* @__PURE__ */ new Set();
319
+ for (const entry of next) {
320
+ if (isObject(entry) && entry._id !== void 0) listed.add(entry._id);
321
+ }
322
+ let out = next;
323
+ current.forEach((entry, position) => {
324
+ if (!isObject(entry) || entry._id === void 0) return;
325
+ if (listed.has(entry._id)) return;
326
+ if (out === next) out = [...next];
327
+ out.splice(Math.min(position, out.length), 0, entry);
328
+ });
329
+ return out;
330
+ }
331
+ function mergeStructured(current, incoming) {
332
+ if (incoming === null || Array.isArray(incoming) && !incoming.length) {
333
+ if (isAssetValue(current)) return current;
334
+ if (Array.isArray(current)) return current.length ? [] : current;
335
+ return null;
336
+ }
337
+ const list = Array.isArray(incoming) ? incoming : [incoming];
338
+ if (current === null || current === void 0) return incoming;
339
+ if (Array.isArray(current)) {
340
+ const template = current.find(isObject);
341
+ const next = list.map((entry) => {
342
+ const match = current.find(
343
+ (c) => isObject(c) && c._id !== void 0 && c._id === entry._id
344
+ );
345
+ if (isObject(match)) return mergeObject(match, entry);
346
+ return isObject(template) ? shapeLike(template, entry) : entry;
347
+ });
348
+ if (!isAssetValue(current) || list.some((entry) => !hasId(current, entry))) {
349
+ return next;
350
+ }
351
+ const kept = keepRemovedAssets(current, next);
352
+ return kept.length === current.length && kept.every((entry, i) => entry === current[i]) ? current : kept;
353
+ }
354
+ if (isObject(current)) return mergeObject(current, list[0]);
355
+ return current;
356
+ }
357
+ function isPatchable(current) {
358
+ return current === null || typeof current === "string" || typeof current === "number" || typeof current === "boolean";
359
+ }
360
+ function cloneNode(node) {
361
+ return Array.isArray(node) ? [...node] : { ...node };
362
+ }
363
+ function patchSnapshot(snapshot, index, itemId, field, value) {
364
+ const paths = index.get(itemId);
365
+ if (!paths?.length) return snapshot;
366
+ let root = snapshot;
367
+ let changed = false;
368
+ const markChanged = () => {
369
+ changed = true;
370
+ };
371
+ for (const path of paths) {
372
+ for (const [target, targetValue] of expandTextBody(
373
+ root,
374
+ path,
375
+ field,
376
+ value
377
+ )) {
378
+ root = patchAtPath(root, path, target, targetValue, markChanged);
379
+ }
380
+ }
381
+ return changed ? root : snapshot;
382
+ }
383
+ function expandTextBody(root, path, field, value) {
384
+ const segments = field.split(".");
385
+ if (segments[segments.length - 1] !== "body" || typeof value !== "string") {
386
+ return [[field, value]];
387
+ }
388
+ let node = root;
389
+ for (const step of path) {
390
+ node = node[step];
391
+ }
392
+ for (const segment of segments.slice(0, -1)) {
393
+ if (node === null || typeof node !== "object") return [[field, value]];
394
+ const record2 = node;
395
+ node = INDEX_SEGMENT.test(segment) ? record2[Number(segment)] : record2[fieldKeyIn(record2, segment) ?? segment];
396
+ }
397
+ if (node === null || typeof node !== "object" || Array.isArray(node)) {
398
+ return [[field, value]];
399
+ }
400
+ const record = node;
401
+ if (!isTextEntry(record)) return [[field, value]];
402
+ const prefix = segments.slice(0, -1);
403
+ const writes = [];
404
+ for (const { name, plain } of TEXT_BODY_FIELDS) {
405
+ if (!(name in record)) continue;
406
+ writes.push([
407
+ [...prefix, name].join("."),
408
+ plain ? plainTextFromHtml(value) : value
409
+ ]);
410
+ }
411
+ return writes.length ? writes : [[field, value]];
412
+ }
413
+ function patchAtPath(root, path, field, value, markChanged) {
414
+ const segments = field.split(".");
415
+ if (segments.some((s) => FORBIDDEN_SEGMENTS.has(s))) return root;
416
+ let node = root;
417
+ for (const step of path) {
418
+ node = node[step];
419
+ }
420
+ const fullPath = [...path];
421
+ for (const segment of segments) {
422
+ let step = segment;
423
+ if (INDEX_SEGMENT.test(segment)) {
424
+ step = Number(segment);
425
+ } else if (node !== null && typeof node === "object") {
426
+ step = fieldKeyIn(node, segment) ?? segment;
427
+ }
428
+ fullPath.push(step);
429
+ node = node !== null && typeof node === "object" ? node[step] : void 0;
430
+ }
431
+ return writeAtPath(root, fullPath, value, markChanged);
432
+ }
433
+ function writeAtPath(root, fullPath, value, markChanged = () => {
434
+ }) {
435
+ if (!fullPath.length) return root;
436
+ if (fullPath.some((s) => FORBIDDEN_SEGMENTS.has(String(s)))) return root;
437
+ const last = fullPath.length - 1;
438
+ let node = root;
439
+ for (let i = 0; i < last; i++) {
440
+ if (node === null || typeof node !== "object") return root;
441
+ node = node[fullPath[i]];
442
+ }
443
+ if (node === null || typeof node !== "object") return root;
444
+ const container = node;
445
+ const key = fullPath[last];
446
+ if (!(key in container)) return root;
447
+ let next;
448
+ if (value === null || typeof value === "object") {
449
+ next = mergeStructured(container[key], value);
450
+ } else if (!isPatchable(container[key])) {
451
+ return root;
452
+ } else {
453
+ next = keepEditLink(container[key], value);
454
+ }
455
+ if (container[key] === next) return root;
456
+ const newRoot = cloneNode(root);
457
+ let cursor = newRoot;
458
+ for (let i = 0; i < last; i++) {
459
+ const child = cloneNode(cursor[fullPath[i]]);
460
+ cursor[fullPath[i]] = child;
461
+ cursor = child;
462
+ }
463
+ cursor[key] = next;
464
+ markChanged();
465
+ return newRoot;
466
+ }
467
+ function listKeysOf(entry) {
468
+ if (!isObject(entry)) return [];
469
+ const keys = [];
470
+ if (typeof entry._id === "string") keys.push(entry._id);
471
+ const first = Array.isArray(entry.items) ? entry.items[0] : null;
472
+ if (isObject(first) && typeof first._id === "string") {
473
+ keys.push(first._id);
474
+ }
475
+ return keys;
476
+ }
477
+ function buildText(entry, template) {
478
+ const body = typeof entry.body === "string" ? entry.body : "";
479
+ const full = {
480
+ __typename: "Text",
481
+ _id: entry._id,
482
+ body,
483
+ html: body,
484
+ text: plainTextFromHtml(body),
485
+ format: entry.format ?? null
486
+ };
487
+ if (!template) return full;
488
+ const out = {};
489
+ for (const key of Object.keys(template)) {
490
+ out[key] = key in full ? full[key] : null;
491
+ }
492
+ return out;
493
+ }
494
+ function syncList(current, entries, build) {
495
+ if (current === null || current === void 0) {
496
+ const built = syncList([], entries, build);
497
+ return built.length ? built : current;
498
+ }
499
+ if (!Array.isArray(current)) return current;
500
+ const byKey = /* @__PURE__ */ new Map();
501
+ const templates = /* @__PURE__ */ new Map();
502
+ for (const c of current) {
503
+ for (const key of listKeysOf(c)) byKey.set(key, c);
504
+ if (isObject(c) && typeof c.__typename === "string") {
505
+ if (!templates.has(c.__typename)) templates.set(c.__typename, c);
506
+ }
507
+ }
508
+ if (!entries.length) return current.length ? [] : current;
509
+ if (current.length && !byKey.size) return current;
510
+ if (current.length && !entries.some((e) => byKey.has(e._id))) return current;
511
+ const next = [];
512
+ for (const entry of entries) {
513
+ const existing = byKey.get(entry._id);
514
+ const built = existing === void 0 && entry.fields ? build?.(entry) : void 0;
515
+ if (existing !== void 0) {
516
+ next.push(existing);
517
+ } else if (built) {
518
+ next.push(built);
519
+ } else if (entry.__typename === "Text") {
520
+ next.push(buildText(entry, templates.get("Text")));
521
+ }
522
+ }
523
+ const same = next.length === current.length && next.every((n, i) => n === current[i]);
524
+ return same ? current : next;
525
+ }
526
+ function syncListSnapshot(snapshot, index, itemId, field, entries) {
527
+ const paths = index.get(itemId);
528
+ if (!paths?.length) return snapshot;
529
+ const fieldPath = field.split(".");
530
+ if (fieldPath.some((s) => FORBIDDEN_SEGMENTS.has(s))) return snapshot;
531
+ let root = snapshot;
532
+ for (const path of paths) {
533
+ root = syncListAtPath(root, [...path, ...fieldPath], entries);
534
+ }
535
+ return root;
536
+ }
537
+ function syncListAtPath(root, fullPath, entries, build) {
538
+ if (!fullPath.length) return root;
539
+ if (fullPath.some((s) => FORBIDDEN_SEGMENTS.has(String(s)))) return root;
540
+ let node = root;
541
+ for (const key of fullPath) {
542
+ node = node !== null && typeof node === "object" ? node[key] : void 0;
543
+ }
544
+ const next = syncList(node, entries, build);
545
+ if (next === node) return root;
546
+ const newRoot = cloneNode(root);
547
+ let cursor = newRoot;
548
+ for (let i = 0; i < fullPath.length - 1; i++) {
549
+ const child = cloneNode(cursor[fullPath[i]]);
550
+ cursor[fullPath[i]] = child;
551
+ cursor = child;
552
+ }
553
+ cursor[fullPath[fullPath.length - 1]] = next;
554
+ return newRoot;
555
+ }
556
+ function keepEditLink(current, value) {
557
+ if (typeof current !== "string" || typeof value !== "string") return value;
558
+ const { encoded } = vercelStegaSplit2(current);
559
+ if (!encoded || vercelStegaSplit2(value).encoded) return value;
560
+ return value + encoded;
561
+ }
562
+
563
+ // src/core/live-preview/query-document.ts
564
+ var NAME_START = /[_A-Za-z]/;
565
+ var NAME_CONTINUE = /[_0-9A-Za-z]/;
566
+ var PUNCT = /* @__PURE__ */ new Set([
567
+ "!",
568
+ "$",
569
+ "&",
570
+ "(",
571
+ ")",
572
+ ":",
573
+ "=",
574
+ "@",
575
+ "[",
576
+ "]",
577
+ "{",
578
+ "|",
579
+ "}"
580
+ ]);
581
+ function tokenize(source) {
582
+ const tokens = [];
583
+ let i = 0;
584
+ const n = source.length;
585
+ while (i < n) {
586
+ const ch = source[i];
587
+ if (ch === " " || ch === " " || ch === "\n" || ch === "\r" || ch === "," || ch === "\uFEFF") {
588
+ i++;
589
+ } else if (ch === "#") {
590
+ while (i < n && source[i] !== "\n" && source[i] !== "\r") i++;
591
+ } else if (ch === "." && source.startsWith("...", i)) {
592
+ tokens.push({ type: "punct", value: "..." });
593
+ i += 3;
594
+ } else if (PUNCT.has(ch)) {
595
+ tokens.push({ type: "punct", value: ch });
596
+ i++;
597
+ } else if (NAME_START.test(ch)) {
598
+ const start = i;
599
+ while (i < n && NAME_CONTINUE.test(source[i])) i++;
600
+ tokens.push({ type: "name", value: source.slice(start, i) });
601
+ } else if (ch === '"') {
602
+ if (source.startsWith('"""', i)) {
603
+ i += 3;
604
+ while (i < n && !source.startsWith('"""', i)) {
605
+ i += source.startsWith('\\"""', i) ? 4 : 1;
606
+ }
607
+ if (i >= n) throw new SyntaxError("Unterminated block string");
608
+ i += 3;
609
+ } else {
610
+ i++;
611
+ while (i < n && source[i] !== '"') {
612
+ if (source[i] === "\n" || source[i] === "\r") {
613
+ throw new SyntaxError("Unterminated string");
614
+ }
615
+ i += source[i] === "\\" ? 2 : 1;
616
+ }
617
+ if (i >= n) throw new SyntaxError("Unterminated string");
618
+ i++;
619
+ }
620
+ tokens.push({ type: "value" });
621
+ } else if (ch === "-" || ch >= "0" && ch <= "9") {
622
+ i++;
623
+ while (i < n && /[0-9.eE+-]/.test(source[i])) i++;
624
+ tokens.push({ type: "value" });
625
+ } else {
626
+ throw new SyntaxError(`Unexpected character "${ch}"`);
627
+ }
628
+ }
629
+ return tokens;
630
+ }
631
+ function parseSource(source, operationName) {
632
+ const tokens = tokenize(source);
633
+ let pos = 0;
634
+ const peek = () => tokens[pos];
635
+ const isPunct = (value) => {
636
+ const t = tokens[pos];
637
+ return t?.type === "punct" && t.value === value;
638
+ };
639
+ const expectPunct = (value) => {
640
+ if (!isPunct(value)) throw new SyntaxError(`Expected "${value}"`);
641
+ pos++;
642
+ };
643
+ const expectName = () => {
644
+ const t = tokens[pos];
645
+ if (t?.type !== "name") throw new SyntaxError("Expected a name");
646
+ pos++;
647
+ return t.value;
648
+ };
649
+ const skipParens = () => {
650
+ expectPunct("(");
651
+ let depth = 1;
652
+ while (depth > 0) {
653
+ const t = tokens[pos++];
654
+ if (!t) throw new SyntaxError("Unbalanced parentheses");
655
+ if (t.type === "punct" && t.value === "(") depth++;
656
+ else if (t.type === "punct" && t.value === ")") depth--;
657
+ }
658
+ };
659
+ const skipDirectives = () => {
660
+ while (isPunct("@")) {
661
+ pos++;
662
+ expectName();
663
+ if (isPunct("(")) skipParens();
664
+ }
665
+ };
666
+ const parseSelectionSet = () => {
667
+ expectPunct("{");
668
+ const selections = [];
669
+ while (!isPunct("}")) {
670
+ if (!peek()) throw new SyntaxError("Unterminated selection set");
671
+ selections.push(parseSelection());
672
+ }
673
+ pos++;
674
+ return selections;
675
+ };
676
+ const parseSelection = () => {
677
+ if (isPunct("...")) {
678
+ pos++;
679
+ const t = peek();
680
+ if (t?.type === "name" && t.value !== "on") {
681
+ pos++;
682
+ skipDirectives();
683
+ return { kind: "spread", name: t.value };
684
+ }
685
+ let on = null;
686
+ if (t?.type === "name") {
687
+ pos++;
688
+ on = expectName();
689
+ }
690
+ skipDirectives();
691
+ return { kind: "inline", on, selections: parseSelectionSet() };
692
+ }
693
+ let name = expectName();
694
+ const key = name;
695
+ if (isPunct(":")) {
696
+ pos++;
697
+ name = expectName();
698
+ }
699
+ let hasArgs = false;
700
+ if (isPunct("(")) {
701
+ hasArgs = true;
702
+ skipParens();
703
+ }
704
+ skipDirectives();
705
+ const selections = isPunct("{") ? parseSelectionSet() : null;
706
+ return { kind: "field", name, key, hasArgs, selections };
707
+ };
708
+ const fragments = /* @__PURE__ */ new Map();
709
+ const operations = [];
710
+ while (pos < tokens.length) {
711
+ if (isPunct("{")) {
712
+ operations.push({ name: null, selections: parseSelectionSet() });
713
+ continue;
714
+ }
715
+ const keyword = expectName();
716
+ if (keyword === "fragment") {
717
+ const name = expectName();
718
+ if (expectName() !== "on") throw new SyntaxError('Expected "on"');
719
+ const on = expectName();
720
+ skipDirectives();
721
+ fragments.set(name, { on, selections: parseSelectionSet() });
722
+ } else if (keyword === "query" || keyword === "mutation" || keyword === "subscription") {
723
+ const t = peek();
724
+ let name = null;
725
+ if (t?.type === "name") name = expectName();
726
+ if (isPunct("(")) skipParens();
727
+ skipDirectives();
728
+ operations.push({ name, selections: parseSelectionSet() });
729
+ } else {
730
+ throw new SyntaxError(`Unexpected "${keyword}"`);
731
+ }
732
+ }
733
+ return { operation: pickOperation(operations, operationName), fragments };
734
+ }
735
+ function pickOperation(operations, operationName) {
736
+ const op = operationName ? operations.find((o) => o.name === operationName) : operations[0];
737
+ if (!op) throw new SyntaxError("The document has no operation");
738
+ return op.selections;
739
+ }
740
+ function fromAstSelections(set) {
741
+ return set.selections.map((s) => {
742
+ if (s.kind === "FragmentSpread")
743
+ return { kind: "spread", name: s.name.value };
744
+ if (s.kind === "InlineFragment") {
745
+ return {
746
+ kind: "inline",
747
+ on: s.typeCondition?.name.value ?? null,
748
+ selections: fromAstSelections(s.selectionSet)
749
+ };
750
+ }
751
+ const name = s.name.value;
752
+ return {
753
+ kind: "field",
754
+ name,
755
+ key: s.alias?.value ?? name,
756
+ hasArgs: Boolean(s.arguments?.length),
757
+ selections: s.selectionSet ? fromAstSelections(s.selectionSet) : null
758
+ };
759
+ });
760
+ }
761
+ function fromAst(doc, operationName) {
762
+ const fragments = /* @__PURE__ */ new Map();
763
+ const operations = [];
764
+ for (const def of doc.definitions ?? []) {
765
+ if (def.kind === "FragmentDefinition" && def.name && def.typeCondition && def.selectionSet) {
766
+ fragments.set(def.name.value, {
767
+ on: def.typeCondition.name.value,
768
+ selections: fromAstSelections(def.selectionSet)
769
+ });
770
+ } else if (def.kind === "OperationDefinition" && def.selectionSet) {
771
+ operations.push({
772
+ name: def.name?.value ?? null,
773
+ selections: fromAstSelections(def.selectionSet)
774
+ });
775
+ }
776
+ }
777
+ return { operation: pickOperation(operations, operationName), fragments };
778
+ }
779
+ var astCache = /* @__PURE__ */ new WeakMap();
780
+ var sourceCache = /* @__PURE__ */ new Map();
781
+ var SOURCE_CACHE_LIMIT = 200;
782
+ function readQueryDocument(query, operationName) {
783
+ const cacheKey = operationName ?? "";
784
+ if (typeof query === "object" && query !== null && query.kind === "Document") {
785
+ let byName = astCache.get(query);
786
+ if (!byName) astCache.set(query, byName = /* @__PURE__ */ new Map());
787
+ let parsed2 = byName.get(cacheKey);
788
+ if (!parsed2) {
789
+ parsed2 = fromAst(
790
+ query,
791
+ operationName
792
+ );
793
+ byName.set(cacheKey, parsed2);
794
+ }
795
+ return parsed2;
796
+ }
797
+ const source = String(query);
798
+ const sourceKey = `${cacheKey}
799
+ ${source}`;
800
+ let parsed = sourceCache.get(sourceKey);
801
+ if (!parsed) {
802
+ parsed = parseSource(source, operationName);
803
+ if (sourceCache.size >= SOURCE_CACHE_LIMIT) {
804
+ sourceCache.delete(sourceCache.keys().next().value);
805
+ }
806
+ sourceCache.set(sourceKey, parsed);
807
+ }
808
+ return parsed;
809
+ }
810
+ var fieldsCache = /* @__PURE__ */ new WeakMap();
811
+ function collectFields(selections, typename, doc, options = {}) {
812
+ const cacheKey = `${options.strict ? "s" : "l"}:${typename ?? ""}`;
813
+ let cached = fieldsCache.get(selections);
814
+ if (!cached) {
815
+ cached = /* @__PURE__ */ new Map();
816
+ fieldsCache.set(selections, cached);
817
+ }
818
+ const hit = cached.get(cacheKey);
819
+ if (hit) return hit;
820
+ const fields = resolveFields(selections, typename, doc, options);
821
+ cached.set(cacheKey, fields);
822
+ return fields;
823
+ }
824
+ function resolveFields(selections, typename, doc, options) {
825
+ const exact = /* @__PURE__ */ new Map();
826
+ const loose = /* @__PURE__ */ new Map();
827
+ const merged = /* @__PURE__ */ new Map();
828
+ const walkedMatched = /* @__PURE__ */ new Set();
829
+ const walkedLoose = /* @__PURE__ */ new Set();
830
+ const add = (target, s) => {
831
+ let field = target.get(s.key);
832
+ if (!field) {
833
+ field = { name: s.name, key: s.key, hasArgs: s.hasArgs, selections: [] };
834
+ target.set(s.key, field);
835
+ merged.set(field, /* @__PURE__ */ new Set());
836
+ }
837
+ const done = merged.get(field);
838
+ if (s.selections && !done.has(s.selections)) {
839
+ done.add(s.selections);
840
+ field.selections = [...field.selections, ...s.selections];
841
+ }
842
+ };
843
+ const applies = (on, list) => conditionMatches(on, typename) || typename !== void 0 && typeConditions(list, doc).includes(typename);
844
+ const walk = (list, matched) => {
845
+ for (const s of list) {
846
+ if (s.kind === "field") {
847
+ add(matched ? exact : loose, s);
848
+ } else if (s.kind === "inline") {
849
+ walk(s.selections, matched && applies(s.on, s.selections));
850
+ } else {
851
+ const fragment = doc.fragments.get(s.name);
852
+ if (!fragment) continue;
853
+ const asMatched = matched && applies(fragment.on, fragment.selections);
854
+ if (walkedMatched.has(fragment)) continue;
855
+ if (!asMatched && walkedLoose.has(fragment)) continue;
856
+ (asMatched ? walkedMatched : walkedLoose).add(fragment);
857
+ walk(fragment.selections, asMatched);
858
+ }
859
+ }
860
+ };
861
+ walk(selections, true);
862
+ if (!options.strict) {
863
+ for (const [key, field] of loose) {
864
+ if (!exact.has(key)) exact.set(key, field);
865
+ }
866
+ }
867
+ return exact;
868
+ }
869
+ function conditionMatches(on, typename) {
870
+ return on === null || typename === void 0 || on === typename;
871
+ }
872
+ var conditionsCache = /* @__PURE__ */ new WeakMap();
873
+ function typeConditions(selections, doc) {
874
+ const hit = conditionsCache.get(selections);
875
+ if (hit) return hit;
876
+ const names = /* @__PURE__ */ new Set();
877
+ const seen = /* @__PURE__ */ new Set();
878
+ const walk = (list) => {
879
+ for (const s of list) {
880
+ if (s.kind === "inline") {
881
+ if (s.on) names.add(s.on);
882
+ walk(s.selections);
883
+ } else if (s.kind === "spread") {
884
+ const fragment = doc.fragments.get(s.name);
885
+ if (!fragment || seen.has(fragment)) continue;
886
+ seen.add(fragment);
887
+ names.add(fragment.on);
888
+ walk(fragment.selections);
889
+ }
890
+ }
891
+ };
892
+ walk(selections);
893
+ const conditions = [...names];
894
+ conditionsCache.set(selections, conditions);
895
+ return conditions;
896
+ }
897
+
898
+ // src/core/live-preview/normalize-query.ts
899
+ var debug2 = createScopedLogger("live-preview:normalize");
900
+ var INDEX_SEGMENT2 = /^\d+$/;
901
+ var FORBIDDEN_SEGMENTS2 = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
902
+ var ENVELOPE_KEYS = /* @__PURE__ */ new Set(["data", "errors", "extensions"]);
903
+ function normalizeQuery(query, result, options = {}) {
904
+ return applyPatchLog(
905
+ query,
906
+ result,
907
+ parsePatchLog(options.log),
908
+ options.operationName
909
+ );
910
+ }
911
+ function applyPatchLog(query, result, log, operationName) {
912
+ if (!log.length || result === null || typeof result !== "object") {
913
+ return result;
914
+ }
915
+ if (isEnvelope(result)) {
916
+ const data = applyPatchLog(query, result.data, log, operationName);
917
+ return data === result.data ? result : { ...result, data };
918
+ }
919
+ let doc = null;
920
+ try {
921
+ doc = readQueryDocument(query, operationName);
922
+ } catch (error) {
923
+ debug2.log("could not read the query; applying fields by literal path", {
924
+ error: String(error)
925
+ });
926
+ }
927
+ let root = result;
928
+ let index = null;
929
+ for (const patch of log) {
930
+ try {
931
+ index ?? (index = indexSnapshot(root));
932
+ const next = applyPatch(root, index, patch, doc, result);
933
+ if (next !== root) {
934
+ root = next;
935
+ if (patch.type === "list" || !isScalarValue(patch.value)) {
936
+ index = null;
937
+ }
938
+ }
939
+ } catch (error) {
940
+ debug2.log("could not apply a change", {
941
+ itemId: patch.itemId,
942
+ field: patch.field,
943
+ error: String(error)
944
+ });
945
+ }
946
+ }
947
+ return root;
948
+ }
949
+ function isScalarValue(value) {
950
+ return value === null || typeof value !== "object";
951
+ }
952
+ function applyPatch(root, index, patch, doc, result) {
953
+ const ownerPaths = index.get(patch.itemId);
954
+ if (!ownerPaths?.length) return root;
955
+ const segments = patch.field.split(".");
956
+ if (segments.some((s) => !s || FORBIDDEN_SEGMENTS2.has(s))) return root;
957
+ const targets = [];
958
+ const plain = /* @__PURE__ */ new Set();
959
+ for (const ownerPath of ownerPaths) {
960
+ if (doc) {
961
+ const resolved = resolveTargets(root, doc, ownerPath, segments);
962
+ root = resolved.root;
963
+ targets.push(...resolved.targets);
964
+ resolved.plain.forEach((target) => plain.add(target));
965
+ } else {
966
+ targets.push([...ownerPath, ...segments.map(toPathSegment)]);
967
+ }
968
+ }
969
+ if (!targets.length) {
970
+ debug2.log("no field in the query matches", {
971
+ itemId: patch.itemId,
972
+ field: patch.field
973
+ });
974
+ return root;
975
+ }
976
+ if (patch.type === "field") {
977
+ for (const target of targets) {
978
+ const pushed = plain.has(target) && typeof patch.value === "string" ? plainTextFromHtml(patch.value) : patch.value;
979
+ let value = keepEditLink(readAtPath(root, target), pushed);
980
+ if (patch.edit && typeof value === "string" && !vercelStegaSplit3(value).encoded) {
981
+ value = editLinksFor(result, patch.edit.item)?.encode(
982
+ value,
983
+ patch.edit.field
984
+ ) ?? value;
985
+ }
986
+ root = writeAtPath(root, target, value);
987
+ }
988
+ } else {
989
+ for (const target of targets) {
990
+ const selections = doc ? selectionsAt(root, doc, target) : null;
991
+ const build = doc && selections ? (entry) => buildEntry(doc, selections, entry, {
992
+ links: editLinks(result, entry),
993
+ lists: listKeysIn(result)
994
+ }) : void 0;
995
+ root = syncListAtPath(root, target, patch.entries, build);
996
+ }
997
+ }
998
+ return root;
999
+ }
1000
+ function readAtPath(root, path) {
1001
+ let node = root;
1002
+ for (const step of path) {
1003
+ if (node === null || typeof node !== "object") return void 0;
1004
+ node = node[step];
1005
+ }
1006
+ return node;
1007
+ }
1008
+ function isEnvelope(value) {
1009
+ if (Array.isArray(value) || !("data" in value)) return false;
1010
+ return Object.keys(value).every((key) => ENVELOPE_KEYS.has(key));
1011
+ }
1012
+ function toPathSegment(segment) {
1013
+ return INDEX_SEGMENT2.test(segment) ? Number(segment) : segment;
1014
+ }
1015
+ function typenameOf(node) {
1016
+ const typename = node.__typename;
1017
+ return typeof typename === "string" ? typename : void 0;
1018
+ }
1019
+ function selectionsAt(root, doc, path) {
1020
+ let node = root;
1021
+ let selections = doc.operation;
1022
+ for (const step of path) {
1023
+ if (Array.isArray(node)) {
1024
+ node = node[step];
1025
+ continue;
1026
+ }
1027
+ if (node === null || typeof node !== "object") return null;
1028
+ const field = collectFields(selections, typenameOf(node), doc).get(
1029
+ String(step)
1030
+ );
1031
+ if (!field) return null;
1032
+ selections = field.selections;
1033
+ node = node[String(step)];
1034
+ }
1035
+ return selections;
1036
+ }
1037
+ function resolveTargets(root, doc, ownerPath, segments) {
1038
+ let owner = root;
1039
+ for (const step of ownerPath) {
1040
+ owner = owner[step];
1041
+ }
1042
+ const selections = selectionsAt(root, doc, ownerPath);
1043
+ if (!selections) return { root, targets: [], plain: /* @__PURE__ */ new Set() };
1044
+ let current = root;
1045
+ const out = [];
1046
+ const plain = /* @__PURE__ */ new Set();
1047
+ const walk = (node, sel, i, path) => {
1048
+ if (i === segments.length) {
1049
+ out.push(path);
1050
+ return;
1051
+ }
1052
+ const segment = segments[i];
1053
+ if (Array.isArray(node)) {
1054
+ if (INDEX_SEGMENT2.test(segment)) {
1055
+ const position = Number(segment);
1056
+ if (position < node.length) {
1057
+ walk(node[position], sel, i + 1, [...path, position]);
1058
+ }
1059
+ } else if (segment === "items") {
1060
+ walk(node, sel, i + 1, path);
1061
+ }
1062
+ return;
1063
+ }
1064
+ if (node === null || typeof node !== "object") return;
1065
+ const record = node;
1066
+ const wanted = graphqlFieldName(segment);
1067
+ const textBody = i === segments.length - 1 && segment === "body" && isTextEntry(record) ? TEXT_BODY_FIELDS : null;
1068
+ let matched = false;
1069
+ for (const field of collectFields(sel, typenameOf(node), doc).values()) {
1070
+ const alias = textBody?.find((f) => f.name === field.name);
1071
+ if (field.name !== segment && field.name !== wanted && !alias) continue;
1072
+ if (!Object.prototype.hasOwnProperty.call(record, field.key)) continue;
1073
+ matched = true;
1074
+ const fieldPath = [...path, field.key];
1075
+ if (alias?.plain) plain.add(fieldPath);
1076
+ let value = record[field.key];
1077
+ const next = segments[i + 1];
1078
+ if (value === null && field.selections.length && next !== void 0 && next !== "items" && !INDEX_SEGMENT2.test(next)) {
1079
+ const typename = resolveTypename(
1080
+ doc,
1081
+ field.selections,
1082
+ void 0,
1083
+ void 0
1084
+ );
1085
+ if (typename !== void 0) {
1086
+ value = fillObject(doc, field.selections, typename, {}, void 0, {
1087
+ links: null,
1088
+ lists: listKeysIn(root)
1089
+ });
1090
+ current = writeAtPath(current, fieldPath, value);
1091
+ }
1092
+ }
1093
+ walk(value, field.selections, i + 1, fieldPath);
1094
+ }
1095
+ if (!matched && segment === "items") walk(node, sel, i + 1, path);
1096
+ };
1097
+ walk(owner, selections, 0, ownerPath);
1098
+ return { root: current, targets: out, plain };
1099
+ }
1100
+ var NON_ALPHANUMERIC = /[^a-z0-9]/gi;
1101
+ var typeKey = (name) => name.replace(NON_ALPHANUMERIC, "").toLowerCase();
1102
+ function resolveTypename(doc, selections, typename, typeName) {
1103
+ const known = typeConditions(selections, doc);
1104
+ const explicit = typeof typename === "string" ? typename : void 0;
1105
+ if (!known.length) return explicit ?? null;
1106
+ if (explicit && known.includes(explicit)) return explicit;
1107
+ for (const candidate of [explicit, typeName]) {
1108
+ if (typeof candidate !== "string" || !candidate) continue;
1109
+ const match = known.find((name) => typeKey(name) === typeKey(candidate));
1110
+ if (match) return match;
1111
+ }
1112
+ const named = explicit !== void 0 || typeof typeName === "string";
1113
+ return known.length === 1 && !named ? known[0] : void 0;
1114
+ }
1115
+ function buildEntry(doc, selections, entry, ctx) {
1116
+ const typename = resolveTypename(
1117
+ doc,
1118
+ selections,
1119
+ entry.__typename,
1120
+ entry.typeName
1121
+ );
1122
+ if (typename === void 0) return void 0;
1123
+ return fillObject(
1124
+ doc,
1125
+ selections,
1126
+ typename,
1127
+ entry.fields ?? {},
1128
+ entry._id,
1129
+ ctx
1130
+ );
1131
+ }
1132
+ function fillObject(doc, selections, typename, values, id, ctx) {
1133
+ const out = {};
1134
+ const { links } = ctx;
1135
+ const lists = ctx.lists(typename);
1136
+ const edit = isPlainRecord(values.__edit) ? values.__edit : null;
1137
+ const apiIdOf = /* @__PURE__ */ new Map();
1138
+ for (const key of Object.keys(values)) {
1139
+ apiIdOf.set(key, key);
1140
+ const name = graphqlFieldName(key);
1141
+ if (!apiIdOf.has(name)) apiIdOf.set(name, key);
1142
+ }
1143
+ if (edit && isPlainRecord(edit.apiIds)) {
1144
+ for (const [name, apiId] of Object.entries(edit.apiIds)) {
1145
+ if (typeof apiId === "string") apiIdOf.set(name, apiId);
1146
+ }
1147
+ }
1148
+ const valueOf = (name) => {
1149
+ if (Object.prototype.hasOwnProperty.call(values, name)) return values[name];
1150
+ const key = apiIdOf.get(name);
1151
+ return key !== void 0 && key in values ? values[key] : void 0;
1152
+ };
1153
+ const editField = (name) => {
1154
+ if (!edit) return null;
1155
+ if (typeof edit.field === "string")
1156
+ return name === "body" ? edit.field : null;
1157
+ if (typeof edit.path !== "string") return null;
1158
+ const apiId = apiIdOf.get(name) ?? name;
1159
+ const text = Array.isArray(edit.text) ? edit.text : [];
1160
+ if (!text.includes(apiId) && !text.includes(name)) return null;
1161
+ return `${edit.path}.items.${apiId}`;
1162
+ };
1163
+ const fields = collectFields(selections, typename ?? void 0, doc, {
1164
+ strict: true
1165
+ });
1166
+ for (const field of fields.values()) {
1167
+ if (field.name === "__typename") {
1168
+ out[field.key] = typename;
1169
+ } else if (field.name === "_id") {
1170
+ out[field.key] = typeof id === "string" ? id : values._id ?? null;
1171
+ } else if (field.selections.length) {
1172
+ const value = valueOf(field.name);
1173
+ out[field.key] = value == null && lists.has(field.key) ? [] : fillNested(doc, field.selections, value, ctx);
1174
+ } else {
1175
+ const value = valueOf(field.name);
1176
+ if (Array.isArray(value) && value.every(isScalar)) {
1177
+ out[field.key] = value;
1178
+ continue;
1179
+ }
1180
+ if (value == null && lists.has(field.key)) {
1181
+ out[field.key] = [];
1182
+ continue;
1183
+ }
1184
+ const scalar = value === void 0 || value !== null && typeof value === "object" ? null : value;
1185
+ const target = typeof scalar === "string" ? editField(field.name) : null;
1186
+ out[field.key] = target && links ? links.encode(scalar, target) : scalar;
1187
+ }
1188
+ }
1189
+ return out;
1190
+ }
1191
+ function fillNested(doc, selections, value, ctx) {
1192
+ const one = (item) => {
1193
+ if (!isPlainRecord(item)) return null;
1194
+ const typename = resolveTypename(
1195
+ doc,
1196
+ selections,
1197
+ item.__typename,
1198
+ item.typeName
1199
+ );
1200
+ if (typename === void 0) return null;
1201
+ return fillObject(doc, selections, typename, item, item._id, ctx);
1202
+ };
1203
+ if (Array.isArray(value)) return value.map(one).filter((v) => v !== null);
1204
+ return value === void 0 ? null : one(value);
1205
+ }
1206
+ var NO_KEYS = /* @__PURE__ */ new Set();
1207
+ var listKeysCache = /* @__PURE__ */ new WeakMap();
1208
+ function listKeysIn(result) {
1209
+ return (typename) => {
1210
+ if (!typename || result === null || typeof result !== "object") {
1211
+ return NO_KEYS;
1212
+ }
1213
+ let byType = listKeysCache.get(result);
1214
+ if (!byType) {
1215
+ byType = /* @__PURE__ */ new Map();
1216
+ const seen = /* @__PURE__ */ new WeakSet();
1217
+ const walk = (node) => {
1218
+ if (node === null || typeof node !== "object" || seen.has(node)) return;
1219
+ seen.add(node);
1220
+ if (Array.isArray(node)) {
1221
+ node.forEach(walk);
1222
+ return;
1223
+ }
1224
+ const record = node;
1225
+ const type = typeof record.__typename === "string" ? record.__typename : null;
1226
+ for (const [key, value] of Object.entries(record)) {
1227
+ if (type && Array.isArray(value)) {
1228
+ let keys = byType.get(type);
1229
+ if (!keys) byType.set(type, keys = /* @__PURE__ */ new Set());
1230
+ keys.add(key);
1231
+ }
1232
+ walk(value);
1233
+ }
1234
+ };
1235
+ walk(result);
1236
+ listKeysCache.set(result, byType);
1237
+ }
1238
+ return byType.get(typename) ?? NO_KEYS;
1239
+ };
1240
+ }
1241
+
1242
+ export {
1243
+ isObject,
1244
+ isLiveFieldChange,
1245
+ parseListEntries,
1246
+ parseEditTarget,
1247
+ parsePatchLog,
1248
+ indexSnapshot,
1249
+ patchSnapshot,
1250
+ syncListSnapshot,
1251
+ readQueryDocument,
1252
+ collectFields,
1253
+ normalizeQuery,
1254
+ applyPatchLog
1255
+ };