@aglyn/plugins-ai 1.27.0 → 1.29.0

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 (48) hide show
  1. package/package.json +17 -17
  2. package/src/lib/components/ai-credits-prompt.component.js +4 -1
  3. package/src/lib/components/ai-credits-prompt.component.js.map +1 -1
  4. package/src/lib/components/ai-site-import-job.component.js +5 -2
  5. package/src/lib/components/ai-site-import-job.component.js.map +1 -1
  6. package/src/lib/components/ai-site-start-card.component.js +6 -3
  7. package/src/lib/components/ai-site-start-card.component.js.map +1 -1
  8. package/src/lib/components/assist-build-card.component.js +4 -1
  9. package/src/lib/components/assist-build-card.component.js.map +1 -1
  10. package/src/lib/components/assist-edit-canvas.d.ts +12 -0
  11. package/src/lib/components/assist-edit-canvas.js +38 -7
  12. package/src/lib/components/assist-edit-canvas.js.map +1 -1
  13. package/src/lib/components/assist-jobs-drawer.component.js +4 -1
  14. package/src/lib/components/assist-jobs-drawer.component.js.map +1 -1
  15. package/src/lib/components/assist-panel.component.js +5 -2
  16. package/src/lib/components/assist-panel.component.js.map +1 -1
  17. package/src/lib/declarations.server.js +17 -0
  18. package/src/lib/declarations.server.js.map +1 -1
  19. package/src/lib/jobs/ai-job-drafts.d.ts +5 -11
  20. package/src/lib/jobs/ai-job-drafts.js +8 -25
  21. package/src/lib/jobs/ai-job-drafts.js.map +1 -1
  22. package/src/lib/jobs/ai-job-edit-step.d.ts +95 -5
  23. package/src/lib/jobs/ai-job-edit-step.js +88 -17
  24. package/src/lib/jobs/ai-job-edit-step.js.map +1 -1
  25. package/src/lib/model/ai-edit-job.d.ts +27 -0
  26. package/src/lib/model/ai-edit-job.js +45 -23
  27. package/src/lib/model/ai-edit-job.js.map +1 -1
  28. package/src/lib/model/ai-layout-menus.d.ts +10 -0
  29. package/src/lib/model/ai-layout-menus.js +23 -2
  30. package/src/lib/model/ai-layout-menus.js.map +1 -1
  31. package/src/lib/model/assist-edit.d.ts +2 -0
  32. package/src/lib/model/assist-edit.js.map +1 -1
  33. package/src/lib/runtime/ai-node-tree.d.ts +25 -1
  34. package/src/lib/runtime/ai-node-tree.js +39 -14
  35. package/src/lib/runtime/ai-node-tree.js.map +1 -1
  36. package/src/lib/runtime/ai-palette.generated.js +84 -2
  37. package/src/lib/runtime/ai-palette.generated.js.map +1 -1
  38. package/src/lib/server/ai-page-content.d.ts +83 -0
  39. package/src/lib/server/ai-page-content.js +765 -0
  40. package/src/lib/server/ai-page-content.js.map +1 -0
  41. package/src/lib/server/ai-usage.js +7 -1
  42. package/src/lib/server/ai-usage.js.map +1 -1
  43. package/src/lib/server/assist-edit.d.ts +136 -1
  44. package/src/lib/server/assist-edit.js +124 -47
  45. package/src/lib/server/assist-edit.js.map +1 -1
  46. package/src/lib/usage/ai-usage-wire.d.ts +15 -0
  47. package/src/lib/usage/ai-usage-wire.js +21 -0
  48. package/src/lib/usage/ai-usage-wire.js.map +1 -1
@@ -0,0 +1,765 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ /**
3
+ * @license
4
+ * Copyright 2026 Aglyn LLC
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */ import { createHash } from "node:crypto";
18
+ import { NODE_MAP_MAX_BYTES } from "@aglyn/aglyn/app-utils/measure-node-map";
19
+ import { screenClaimsToBeAPage } from "@aglyn/aglyn/app-utils/screen-route";
20
+ import { CANVAS_ROOT_ELEMENT_ID } from "@aglyn/aglyn/foundation/constants/canvas";
21
+ import { aiEditBase, aiEditDatasetScope, clearAiEditMirror, draftRef, writeAiEdit } from "../jobs/ai-job-edit-step.js";
22
+ import { AI_EDIT_GONE_COPY, AI_EDIT_NO_NODES_COPY, AI_EDIT_STALE_COPY, AI_EDIT_TOO_LARGE_COPY, AI_EDIT_VERSION_GONE_COPY, aiDocumentElements } from "../model/ai-edit-job.js";
23
+ import { ASSIST_EDIT_ACTION_ID, summarizeAssistEditOps } from "../model/assist-edit.js";
24
+ import { AI_REPEAT_DATASET_PROP, AI_SX_ALLOWED_KEYS, aiPaletteEntryWithCapabilities, aiPropIsIconPick } from "../runtime/ai-node-tree.js";
25
+ import { AI_PALETTE } from "../runtime/ai-palette.generated.js";
26
+ import { readAiSiteDatasets } from "../runtime/site-inventory.js";
27
+ import { ASSIST_EDIT_MAX_INSERT_NODES, ASSIST_EDIT_MAX_OPS, ASSIST_EDIT_MOTION_SETTINGS, assistEditClosedWorld, assistEditLayerNameRefusal, validatePendingEdit } from "./assist-edit.js";
28
+ /** The id a write made with no person behind it is attributed to, beside its label. */ export const AI_PAGE_CONTENT_API_ACTOR = 'api';
29
+ /** What a write's summary says, in the draft's history. */ const API_EDIT_SUMMARY = 'Edited through the API';
30
+ const isRecord = (value)=>typeof value === 'object' && value !== null && !Array.isArray(value);
31
+ const refusal = (status, code, message, fields)=>_extends({
32
+ ok: false,
33
+ status,
34
+ code,
35
+ message
36
+ }, fields && Object.keys(fields).length ? {
37
+ fields
38
+ } : {});
39
+ // ── The revision ──────────────────────────────────────────────────────────
40
+ /** A stored value as text that does not depend on key order. */ function canonicalJson(value) {
41
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
42
+ if (isRecord(value)) {
43
+ return `{${Object.keys(value).sort().map((key)=>`${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(',')}}`;
44
+ }
45
+ return JSON.stringify(value != null ? value : null);
46
+ }
47
+ /**
48
+ * The base tree's revision (see the module head): which tree, of which
49
+ * version, and a digest of its `nodes` field as stored — the bytes a
50
+ * current document stores, or a legacy map in a key-order-free form.
51
+ */ export function aiPageContentRevision(from, versionId, stored) {
52
+ const hash = createHash('sha256').update(`${from}:${versionId}:`);
53
+ if (stored instanceof Uint8Array) hash.update(stored);
54
+ else hash.update(canonicalJson(stored));
55
+ return `${from === 'draft' ? 'd' : 's'}_${hash.digest('base64url').slice(0, 22)}`;
56
+ }
57
+ // ── What an element shows ────────────────────────────────────────────────
58
+ /** The kind an element is stored as; the document root's wrapper when it names none. */ const kindOf = (node)=>typeof node['componentId'] === 'string' && node['componentId'] ? node['componentId'] : 'div';
59
+ /**
60
+ * The settings an edit can set on an element of this kind, by name: the
61
+ * palette's declarations with the ones every element takes, less an icon the
62
+ * site owner picks, then the motion settings and the repeat's dataset. Empty
63
+ * for a kind the palette does not list, whose settings the validator cannot
64
+ * check.
65
+ */ export function aiPageContentKindProps(kind) {
66
+ const entry = aiPaletteEntryWithCapabilities(kind);
67
+ if (!entry) return {};
68
+ const props = {};
69
+ for (const [name, schema] of Object.entries(entry.propsSchema.properties)){
70
+ var _entry_textLimits_name, _schema_type;
71
+ var _schema_enum;
72
+ if (aiPropIsIconPick(entry, name)) continue;
73
+ const role = entry.propRoles[name];
74
+ const maxLength = role === 'text' ? (_entry_textLimits_name = entry.textLimits[name]) != null ? _entry_textLimits_name : schema.maxLength : schema.maxLength;
75
+ props[name] = _extends({}, role ? {
76
+ role
77
+ } : {}, {
78
+ type: (_schema_type = schema.type) != null ? _schema_type : 'string'
79
+ }, ((_schema_enum = schema.enum) == null ? void 0 : _schema_enum.length) ? {
80
+ values: [
81
+ ...schema.enum
82
+ ]
83
+ } : {}, maxLength !== undefined ? {
84
+ maxLength
85
+ } : {});
86
+ }
87
+ for (const [name, allowed] of Object.entries(ASSIST_EDIT_MOTION_SETTINGS)){
88
+ props[name] = allowed === 'switch' ? {
89
+ role: 'motion',
90
+ type: 'boolean'
91
+ } : typeof allowed === 'number' ? {
92
+ role: 'motion',
93
+ type: 'integer'
94
+ } : {
95
+ role: 'motion',
96
+ type: 'string',
97
+ values: [
98
+ ...allowed
99
+ ]
100
+ };
101
+ }
102
+ props[AI_REPEAT_DATASET_PROP] = {
103
+ role: 'dataset',
104
+ type: 'string'
105
+ };
106
+ return props;
107
+ }
108
+ /** What the palette knows of one kind of element. */ export function aiPageContentKind(kind, options = {}) {
109
+ var _ref;
110
+ const entry = AI_PALETTE[kind];
111
+ return {
112
+ label: options.root ? 'Page' : (_ref = entry == null ? void 0 : entry.displayName) != null ? _ref : kind,
113
+ acceptsChildren: options.root === true || (entry == null ? void 0 : entry.acceptsChildren) === true,
114
+ props: options.root ? {} : aiPageContentKindProps(kind)
115
+ };
116
+ }
117
+ /** Node fields an edit here never writes, which an element shows read-only. */ const READ_ONLY_NODE_FIELDS = [
118
+ 'className',
119
+ 'styleOverrides',
120
+ 'attrOverrides',
121
+ 'presetRef',
122
+ 'layoutStyleOverrides'
123
+ ];
124
+ /** One stored element as a read answers it: what an edit can set, and the rest read-only. */ function elementView(element, settable) {
125
+ const { node } = element;
126
+ const kind = kindOf(node);
127
+ const props = {};
128
+ const readOnlyProps = {};
129
+ for (const [name, value] of Object.entries(isRecord(node['props']) ? node['props'] : {})){
130
+ if (value === undefined) continue;
131
+ if (settable.has(name)) props[name] = value;
132
+ else readOnlyProps[name] = value;
133
+ }
134
+ const style = {};
135
+ const readOnlyStyle = {};
136
+ for (const [key, value] of Object.entries(isRecord(node['sx']) ? node['sx'] : {})){
137
+ if (AI_SX_ALLOWED_KEYS.has(key)) style[key] = value;
138
+ else readOnlyStyle[key] = value;
139
+ }
140
+ const readOnly = {};
141
+ if (Object.keys(readOnlyProps).length) readOnly.props = readOnlyProps;
142
+ if (Object.keys(readOnlyStyle).length) readOnly.style = readOnlyStyle;
143
+ if (Array.isArray(node['interactions']) && node['interactions'].length) readOnly.interactions = node['interactions'].length;
144
+ const fields = READ_ONLY_NODE_FIELDS.filter((field)=>node[field] !== undefined && node[field] !== null);
145
+ if (fields.length) readOnly.fields = fields;
146
+ return _extends({
147
+ id: element.id,
148
+ kind
149
+ }, typeof node['pluginId'] === 'string' && node['pluginId'] ? {
150
+ pluginId: node['pluginId']
151
+ } : {}, typeof node['name'] === 'string' && node['name'] ? {
152
+ name: node['name']
153
+ } : {}, {
154
+ parentId: element.parentId,
155
+ children: [
156
+ ...element.children
157
+ ],
158
+ props
159
+ }, Object.keys(style).length ? {
160
+ style
161
+ } : {}, node['hidden'] === true ? {
162
+ hidden: true
163
+ } : {}, Object.keys(readOnly).length ? {
164
+ readOnly
165
+ } : {});
166
+ }
167
+ /**
168
+ * A page's elements as a read answers them, every one, depth first in the
169
+ * order the page reads, with what each kind takes. With `elementId`, that
170
+ * element and everything inside it; null when it is not on the page.
171
+ */ export function aiPageContentElements(nodes, elementId) {
172
+ const order = aiDocumentElements(nodes);
173
+ if (!order) return null;
174
+ let chosen = order;
175
+ if (elementId !== undefined) {
176
+ const start = order.findIndex((element)=>element.id === elementId);
177
+ if (start < 0) return null;
178
+ // Depth first, so a branch is the run of elements from its root until
179
+ // the walk leaves it.
180
+ const inside = new Set([
181
+ elementId
182
+ ]);
183
+ chosen = [
184
+ order[start]
185
+ ];
186
+ for (const element of order.slice(start + 1)){
187
+ if (element.parentId === null || !inside.has(element.parentId)) break;
188
+ inside.add(element.id);
189
+ chosen.push(element);
190
+ }
191
+ }
192
+ const kinds = {};
193
+ const settable = new Map();
194
+ const elements = chosen.map((element)=>{
195
+ const kind = kindOf(element.node);
196
+ const root = element.id === CANVAS_ROOT_ELEMENT_ID;
197
+ if (!kinds[kind]) kinds[kind] = aiPageContentKind(kind, {
198
+ root
199
+ });
200
+ if (!settable.has(kind)) settable.set(kind, new Set(Object.keys(kinds[kind].props)));
201
+ return elementView(element, settable.get(kind));
202
+ });
203
+ return {
204
+ total: order.length,
205
+ elements,
206
+ kinds
207
+ };
208
+ }
209
+ // ── Reading the page ──────────────────────────────────────────────────────
210
+ const NO_PAGE = ()=>refusal(404, 'page_not_found', 'No such page');
211
+ const EMPTY_PAGE = ()=>refusal(404, 'page_empty', 'That page has no saved content to read or edit yet. Open it in the editor first.');
212
+ /**
213
+ * An ordinary page of the site — not deleted, not an email design, a
214
+ * template, an error page or a folder (`screenClaimsToBeAPage`, the rule
215
+ * every page list holds to), and a layout is not in this collection at all —
216
+ * with its current version and that version's draft.
217
+ */ async function readPage(firestore, input) {
218
+ const hostRef = firestore.collection('hosts').doc(input.hostId);
219
+ const pageRef = hostRef.collection('screens').doc(input.pageId);
220
+ const [host, page] = await Promise.all([
221
+ hostRef.get(),
222
+ pageRef.get()
223
+ ]);
224
+ // A site of another workspace holds no page of this one. The door that
225
+ // calls has admitted the site already, so this only guards the pairing.
226
+ if (!host.exists || host.get('orgId') !== input.orgId) return NO_PAGE();
227
+ if (!page.exists || !screenClaimsToBeAPage(page.data())) return NO_PAGE();
228
+ const versionId = typeof page.get('versionId') === 'string' ? page.get('versionId') : '';
229
+ if (!versionId) return EMPTY_PAGE();
230
+ const versions = pageRef.collection('versions');
231
+ const [version, draft] = await Promise.all([
232
+ versions.doc(versionId).get(),
233
+ draftRef(versions, versionId).get()
234
+ ]);
235
+ if (!version.exists) return EMPTY_PAGE();
236
+ return {
237
+ pageRef,
238
+ versionId,
239
+ version,
240
+ draft
241
+ };
242
+ }
243
+ export async function readAiPageContent(input) {
244
+ const firestore = input.firestore;
245
+ const page = await readPage(firestore, input);
246
+ if ('ok' in page) return page;
247
+ const base = aiEditBase(page.draft, page.version);
248
+ if (!base) return EMPTY_PAGE();
249
+ const content = aiPageContentElements(base.nodes, input.elementId);
250
+ if (!content) {
251
+ return input.elementId !== undefined && aiDocumentElements(base.nodes) ? refusal(404, 'element_not_found', 'No such element on this page', {
252
+ elementId: 'is not an element of this page'
253
+ }) : EMPTY_PAGE();
254
+ }
255
+ return {
256
+ ok: true,
257
+ pageId: input.pageId,
258
+ versionId: page.versionId,
259
+ base: base.from,
260
+ revision: aiPageContentRevision(base.from, page.versionId, base.stored),
261
+ rootId: CANVAS_ROOT_ELEMENT_ID,
262
+ total: content.total,
263
+ elements: content.elements,
264
+ kinds: content.kinds
265
+ };
266
+ }
267
+ // ── Edits, held to the editor's rules ─────────────────────────────────────
268
+ /** Props an edit here never names: markup, styles and handlers, which no field of an element offers. */ const UNSETTABLE_PROP = /^(html|sx|style|className|dangerouslySetInnerHTML|on[A-Z].*)$/;
269
+ /** The words a refused element is named with. */ const ELEMENT_REFUSALS = {
270
+ unknown: 'is not an element of this page',
271
+ root: 'is the page’s root, which cannot be changed, moved or removed',
272
+ removed: 'is inside an element an earlier edit removes'
273
+ };
274
+ const UNSETTABLE_WORDS = 'cannot be set through the API; send text in `children` to replace rich text';
275
+ /** The whole page as the editor's closed world: every element, its kind, its place and its settings. */ function wholeContext(order) {
276
+ const nodes = order.map(({ id, parentId, index, childCount, node })=>_extends({
277
+ id,
278
+ componentId: typeof node['componentId'] === 'string' ? node['componentId'] : '',
279
+ parentId,
280
+ index,
281
+ childCount
282
+ }, isRecord(node['props']) ? {
283
+ props: node['props']
284
+ } : {}));
285
+ return {
286
+ selectedId: null,
287
+ total: nodes.length,
288
+ nodes,
289
+ whole: true
290
+ };
291
+ }
292
+ /** The local id an inserted element is validated under: its path among the request's nested elements. */ const localId = (steps)=>[
293
+ 'el',
294
+ ...steps
295
+ ].join('-');
296
+ /**
297
+ * The API's edits as the editor's pending ops, through the one closed world
298
+ * (`assistEditClosedWorld`), with every problem the request itself carries
299
+ * named by edit and member.
300
+ */ function parseApiEdits(edits, context) {
301
+ const world = assistEditClosedWorld(context);
302
+ const parsed = {
303
+ pending: [],
304
+ edits: [],
305
+ inserts: new Map(),
306
+ fields: {}
307
+ };
308
+ const { fields } = parsed;
309
+ const element = (at, nodeId)=>{
310
+ const found = world.element(nodeId);
311
+ if (typeof found !== 'string') return found;
312
+ fields[at] = ELEMENT_REFUSALS[found];
313
+ return null;
314
+ };
315
+ const parent = (at, parentId)=>{
316
+ const found = world.parent(parentId);
317
+ if (!found) fields[at] = typeof parentId === 'string' && world.byId.has(parentId) ? ELEMENT_REFUSALS.removed : ELEMENT_REFUSALS.unknown;
318
+ return found;
319
+ };
320
+ const unsettable = (at, props)=>{
321
+ let found = false;
322
+ for (const name of Object.keys(props)){
323
+ if (!UNSETTABLE_PROP.test(name)) continue;
324
+ fields[`${at}.${name}`] = UNSETTABLE_WORDS;
325
+ found = true;
326
+ }
327
+ return found;
328
+ };
329
+ const push = (index, op)=>{
330
+ parsed.pending.push(op);
331
+ parsed.edits.push(index);
332
+ };
333
+ edits.forEach((edit, index)=>{
334
+ const at = `edits[${index}]`;
335
+ switch(edit.op){
336
+ case 'updateProps':
337
+ {
338
+ const node = element(`${at}.elementId`, edit.elementId);
339
+ const props = isRecord(edit.props) ? edit.props : {};
340
+ if (!Object.keys(props).length) fields[`${at}.props`] = 'sets no property';
341
+ if (unsettable(`${at}.props`, props) || !node || !Object.keys(props).length) return;
342
+ push(index, {
343
+ op: 'updateProps',
344
+ nodeId: node.id,
345
+ componentId: node.componentId,
346
+ props
347
+ });
348
+ return;
349
+ }
350
+ case 'updateStyle':
351
+ {
352
+ const node = element(`${at}.elementId`, edit.elementId);
353
+ const style = isRecord(edit.style) ? edit.style : {};
354
+ if (!Object.keys(style).length) fields[`${at}.style`] = 'sets no style';
355
+ if (!node || !Object.keys(style).length) return;
356
+ push(index, {
357
+ op: 'updateSx',
358
+ nodeId: node.id,
359
+ componentId: node.componentId,
360
+ sx: style
361
+ });
362
+ return;
363
+ }
364
+ case 'rename':
365
+ {
366
+ const node = element(`${at}.elementId`, edit.elementId);
367
+ const named = typeof edit.name === 'string' ? assistEditLayerNameRefusal(edit.name) : 'is not text';
368
+ if (named) fields[`${at}.name`] = named;
369
+ if (!node || named) return;
370
+ push(index, {
371
+ op: 'rename',
372
+ nodeId: node.id,
373
+ componentId: node.componentId,
374
+ name: edit.name
375
+ });
376
+ return;
377
+ }
378
+ case 'remove':
379
+ {
380
+ const node = element(`${at}.elementId`, edit.elementId);
381
+ if (!node) return;
382
+ world.remove(node.id);
383
+ push(index, {
384
+ op: 'remove',
385
+ nodeId: node.id,
386
+ componentId: node.componentId
387
+ });
388
+ return;
389
+ }
390
+ case 'move':
391
+ {
392
+ const node = element(`${at}.elementId`, edit.elementId);
393
+ const into = parent(`${at}.parentId`, edit.parentId);
394
+ if (!node || !into) return;
395
+ if (world.movesInsideItself(node.id, into.id)) {
396
+ fields[`${at}.parentId`] = 'is inside the element being moved';
397
+ return;
398
+ }
399
+ world.move(node.id, into.id);
400
+ push(index, {
401
+ op: 'move',
402
+ nodeId: node.id,
403
+ componentId: node.componentId,
404
+ parentId: into.id,
405
+ parentComponentId: into.componentId,
406
+ index: edit.index
407
+ });
408
+ return;
409
+ }
410
+ case 'insert':
411
+ {
412
+ const into = parent(`${at}.parentId`, edit.parentId);
413
+ const paths = new Map();
414
+ const nodes = {};
415
+ let refused = false;
416
+ const visit = (raw, steps, path)=>{
417
+ const id = localId(steps);
418
+ paths.set(id, {
419
+ path,
420
+ kind: raw.kind
421
+ });
422
+ const props = isRecord(raw.props) ? raw.props : {};
423
+ if (unsettable(`${path}.props`, props)) refused = true;
424
+ if (raw.name !== undefined) {
425
+ const named = assistEditLayerNameRefusal(raw.name);
426
+ if (named) {
427
+ fields[`${path}.name`] = named;
428
+ refused = true;
429
+ }
430
+ }
431
+ const children = Array.isArray(raw.children) ? raw.children : [];
432
+ nodes[id] = _extends({
433
+ $id: id,
434
+ componentId: raw.kind,
435
+ nodes: children.map((_, child)=>localId([
436
+ ...steps,
437
+ child
438
+ ])),
439
+ props
440
+ }, raw.style !== undefined ? {
441
+ sx: raw.style
442
+ } : {}, raw.name !== undefined ? {
443
+ name: raw.name
444
+ } : {});
445
+ children.forEach((child, position)=>visit(child, [
446
+ ...steps,
447
+ position
448
+ ], `${path}.children[${position}]`));
449
+ };
450
+ visit(edit.element, [], `${at}.element`);
451
+ if (paths.size > ASSIST_EDIT_MAX_INSERT_NODES) {
452
+ fields[`${at}.element`] = `adds ${paths.size} elements; one insert adds at most ${ASSIST_EDIT_MAX_INSERT_NODES}`;
453
+ return;
454
+ }
455
+ if (!into || refused) return;
456
+ parsed.inserts.set(index, paths);
457
+ push(index, {
458
+ op: 'insertSubtree',
459
+ parentId: into.id,
460
+ parentComponentId: into.componentId,
461
+ index: typeof edit.index === 'number' ? edit.index : null,
462
+ tree: {
463
+ rootId: localId([]),
464
+ nodes
465
+ }
466
+ });
467
+ return;
468
+ }
469
+ default:
470
+ fields[`${at}.op`] = 'is not an edit this API makes: updateProps, updateStyle, rename, insert, move or remove';
471
+ }
472
+ });
473
+ return parsed;
474
+ }
475
+ /** The validator's line, in the words a field is named with. */ function reasonOf(text) {
476
+ return text.replace(/; (dropped|truncated|recomputed)$/, '').replace(/^was over (\d+) characters$/, 'is longer than $1 characters').replace(/^is not a prop of /, 'is not a property of ').replace(/; normalized to "([^"]*)"$/, '; write "$1"').trim();
477
+ }
478
+ const escapeRegExp = (text)=>text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
479
+ /**
480
+ * One violation, named by the edit and the member it is in. A repair line
481
+ * names the element the validator was given — the kind, for a patch; the
482
+ * local id, for an inserted element — and the setting, which is read back
483
+ * off it.
484
+ */ function placeViolation(violation, edit, at, paths, kindOfElement) {
485
+ const { message } = violation;
486
+ if (edit.op === 'updateProps') {
487
+ var _edit_props;
488
+ const subject = `${escapeRegExp(kindOfElement(edit.elementId))}\\.`;
489
+ const names = Object.keys((_edit_props = edit.props) != null ? _edit_props : {}).sort((a, b)=>b.length - a.length);
490
+ for (const name of names){
491
+ const repaired = new RegExp(`^${subject}${escapeRegExp(name)}:? (.*)$`).exec(message);
492
+ if (repaired) return [
493
+ `${at}.props.${name}`,
494
+ reasonOf(repaired[1])
495
+ ];
496
+ if (message.startsWith(`${name} `)) return [
497
+ `${at}.props.${name}`,
498
+ reasonOf(message.slice(name.length + 1))
499
+ ];
500
+ }
501
+ return [
502
+ `${at}.props`,
503
+ reasonOf(message)
504
+ ];
505
+ }
506
+ if (edit.op === 'updateStyle') {
507
+ const repaired = /: sx\.([A-Za-z]+)((?:\.[A-Za-z]+)?) (.*)$/.exec(message);
508
+ if (repaired) return [
509
+ `${at}.style.${repaired[1]}${repaired[2]}`,
510
+ reasonOf(repaired[3])
511
+ ];
512
+ return [
513
+ `${at}.style`,
514
+ reasonOf(message)
515
+ ];
516
+ }
517
+ if (edit.op === 'move') return [
518
+ `${at}.parentId`,
519
+ reasonOf(message)
520
+ ];
521
+ if (edit.op === 'insert' && paths) {
522
+ const ids = [
523
+ ...paths.keys()
524
+ ].sort((a, b)=>b.length - a.length);
525
+ const named = (text)=>ids.reduce((out, id)=>{
526
+ var _ref;
527
+ var _paths_get;
528
+ return out.replace(new RegExp(`\\b${escapeRegExp(id)}\\b(?!-)`, 'g'), (_ref = (_paths_get = paths.get(id)) == null ? void 0 : _paths_get.path) != null ? _ref : id);
529
+ }, text).replace(/\bchain-\d+\b/g, 'the element it is added into').replace(new RegExp(escapeRegExp(CANVAS_ROOT_ELEMENT_ID), 'g'), 'the page’s root');
530
+ for (const id of ids){
531
+ var _paths_get;
532
+ const path = (_paths_get = paths.get(id)) == null ? void 0 : _paths_get.path;
533
+ const prop = new RegExp(`^${escapeRegExp(id)}\\.([A-Za-z_][A-Za-z0-9_]*)(?:\\.[A-Za-z0-9_]+)?:? (.*)$`).exec(message);
534
+ if (prop) return [
535
+ `${path}.${prop[1] === 'hidden' ? 'hidden' : `props.${prop[1]}`}`,
536
+ reasonOf(named(prop[2]))
537
+ ];
538
+ const style = new RegExp(`^${escapeRegExp(id)}: sx\\.([A-Za-z]+)((?:\\.[A-Za-z]+)?) (.*)$`).exec(message);
539
+ if (style) return [
540
+ `${path}.style.${style[1]}${style[2]}`,
541
+ reasonOf(named(style[3]))
542
+ ];
543
+ if (new RegExp(`\\(${escapeRegExp(id)}\\)|^${escapeRegExp(id)}\\b(?!-)`).test(message)) return [
544
+ path,
545
+ reasonOf(named(message))
546
+ ];
547
+ }
548
+ // An element the page's palette does not offer, as the palette or the
549
+ // sanitizer under it words it.
550
+ const component = /^Component "([^"]+)" (?:is not in the palette|cannot be published)/.exec(message);
551
+ if (component) {
552
+ const found = [
553
+ ...paths.values()
554
+ ].find((entry)=>entry.kind === component[1]);
555
+ if (found) return [
556
+ `${found.path}.kind`,
557
+ 'is not a kind of element a page takes'
558
+ ];
559
+ }
560
+ return [
561
+ `${at}.element`,
562
+ reasonOf(named(message))
563
+ ];
564
+ }
565
+ return [
566
+ at,
567
+ reasonOf(message)
568
+ ];
569
+ }
570
+ /**
571
+ * The edits validated against one tree and built into the editor's proposal,
572
+ * or refused with every problem named. Pure: the write calls it with the tree
573
+ * its transaction read, so what is checked is what is written.
574
+ */ export function buildAiPageContentEdit(input) {
575
+ if (input.ifRevision !== undefined) {
576
+ const current = aiPageContentRevision(input.base.from, input.versionId, input.base.stored);
577
+ if (current !== input.ifRevision) {
578
+ return {
579
+ refused: refusal(409, 'stale', 'The page changed since that revision was read, so nothing was saved. Read it again.', {
580
+ ifRevision: `is not the page’s current revision, ${current}`
581
+ })
582
+ };
583
+ }
584
+ }
585
+ if (!input.edits.length || input.edits.length > ASSIST_EDIT_MAX_OPS) {
586
+ return {
587
+ refused: refusal(422, 'edit_refused', 'The edits could not be saved, so none were.', {
588
+ edits: `holds ${input.edits.length}; send 1 to ${ASSIST_EDIT_MAX_OPS} edits`
589
+ })
590
+ };
591
+ }
592
+ const order = aiDocumentElements(input.base.nodes);
593
+ if (!order) return {
594
+ refused: EMPTY_PAGE()
595
+ };
596
+ const context = wholeContext(order);
597
+ // The kind each element was validated as, which a patch's repair lines name.
598
+ const kinds = new Map(context.nodes.map((node)=>[
599
+ node.id,
600
+ node.componentId
601
+ ]));
602
+ const parsed = parseApiEdits(input.edits, context);
603
+ const validated = validatePendingEdit(_extends({
604
+ surface: 'screen',
605
+ context,
606
+ pending: parsed.pending,
607
+ strict: true,
608
+ references: {
609
+ screenIds: input.screenIds,
610
+ mediaScopes: input.mediaScopes
611
+ }
612
+ }, input.datasets ? {
613
+ datasets: input.datasets
614
+ } : {}));
615
+ const fields = _extends({}, parsed.fields);
616
+ for (const violation of validated.violations){
617
+ const index = parsed.edits[violation.position];
618
+ const [member, reason] = placeViolation(violation, input.edits[index], `edits[${index}]`, parsed.inserts.get(index), (id)=>{
619
+ var _kinds_get;
620
+ return (_kinds_get = kinds.get(id)) != null ? _kinds_get : '';
621
+ });
622
+ fields[member] = fields[member] ? `${fields[member]}; ${reason}` : reason;
623
+ }
624
+ if (Object.keys(fields).length || validated.ops.length !== input.edits.length) {
625
+ return {
626
+ refused: refusal(422, 'edit_refused', 'The edits could not be saved, so none were. `fields` names each problem.', fields)
627
+ };
628
+ }
629
+ return {
630
+ proposal: {
631
+ id: ASSIST_EDIT_ACTION_ID,
632
+ summary: API_EDIT_SUMMARY,
633
+ ops: validated.ops,
634
+ diff: summarizeAssistEditOps(validated.ops),
635
+ dropped: [],
636
+ target: {
637
+ kind: 'screen',
638
+ documentId: input.pageId,
639
+ versionId: input.versionId,
640
+ hostId: input.hostId
641
+ }
642
+ }
643
+ };
644
+ }
645
+ /** The site's pages a link may name: every ordinary page, as a page list holds them. */ async function sitePageIds(firestore, hostId) {
646
+ const pages = await firestore.collection('hosts').doc(hostId).collection('screens').select('deletedAt', 'kind').get();
647
+ return pages.docs.filter((page)=>screenClaimsToBeAPage(page.data())).map((page)=>page.id);
648
+ }
649
+ /** A write's own failures, as the statuses an API answers. */ function writeRefusal(error, tooLarge) {
650
+ if (tooLarge) {
651
+ return refusal(413, 'page_too_large', `${AI_EDIT_TOO_LARGE_COPY} It would be ${tooLarge.bytes} bytes; a page holds at most ${NODE_MAP_MAX_BYTES}.`);
652
+ }
653
+ if (error === AI_EDIT_GONE_COPY) return NO_PAGE();
654
+ if (error === AI_EDIT_NO_NODES_COPY) return EMPTY_PAGE();
655
+ if (error === AI_EDIT_STALE_COPY || error === AI_EDIT_VERSION_GONE_COPY) {
656
+ return refusal(409, 'stale', 'The page changed while the edits were being saved, so nothing was saved. Read it again.');
657
+ }
658
+ return refusal(422, 'edit_refused', 'The editor refused part of these edits, so none were saved.');
659
+ }
660
+ export function createAiPageContentEditor(deps = {}) {
661
+ var _deps_writeEdit, _deps_readDatasets, _deps_clearMirror;
662
+ const writeEdit = (_deps_writeEdit = deps.writeEdit) != null ? _deps_writeEdit : writeAiEdit;
663
+ const readDatasets = (_deps_readDatasets = deps.readDatasets) != null ? _deps_readDatasets : readAiSiteDatasets;
664
+ const clearMirror = (_deps_clearMirror = deps.clearMirror) != null ? _deps_clearMirror : clearAiEditMirror;
665
+ return async function editAiPageContent(input) {
666
+ var _input_actor_uid, _deps_now, _write_refused, _ref;
667
+ var _write_written;
668
+ const firestore = input.firestore;
669
+ if (!Array.isArray(input.edits) || !input.edits.length || input.edits.length > ASSIST_EDIT_MAX_OPS) {
670
+ return refusal(422, 'edit_refused', 'The edits could not be saved, so none were.', {
671
+ edits: `send 1 to ${ASSIST_EDIT_MAX_OPS} edits`
672
+ });
673
+ }
674
+ const page = await readPage(firestore, input);
675
+ if ('ok' in page) return page;
676
+ const [screenIds, datasets] = await Promise.all([
677
+ sitePageIds(firestore, input.hostId),
678
+ readDatasets(input.orgId, input.hostId)
679
+ ]);
680
+ const scope = aiEditDatasetScope(datasets, {
681
+ kind: 'screen',
682
+ id: input.pageId
683
+ });
684
+ const write = await writeEdit(firestore, {
685
+ hostId: input.hostId,
686
+ kind: 'screen',
687
+ id: input.pageId,
688
+ sourceVersionId: page.versionId,
689
+ jobVersionId: input.editId,
690
+ // Always the version's draft: never a new version, never the search
691
+ // fields, so nothing a visitor sees and nothing on the page moves.
692
+ versioning: false,
693
+ newVersion: false,
694
+ writeSeo: false,
695
+ versionName: API_EDIT_SUMMARY,
696
+ uid: (_input_actor_uid = input.actor.uid) != null ? _input_actor_uid : AI_PAGE_CONTENT_API_ACTOR,
697
+ updatedByLabel: input.actor.label,
698
+ maxNodeBytes: NODE_MAP_MAX_BYTES,
699
+ aiJobId: input.editId,
700
+ now: ((_deps_now = deps.now) != null ? _deps_now : ()=>new Date())(),
701
+ proposal: (base)=>{
702
+ // The version the page points at moved since the read: the draft the
703
+ // edits were asked of is no longer the page's.
704
+ if (base.pointerVersionId !== page.versionId) {
705
+ return {
706
+ refused: refusal(409, 'stale', 'The page changed since it was read, so nothing was saved. Read it again.')
707
+ };
708
+ }
709
+ const built = buildAiPageContentEdit(_extends({
710
+ base,
711
+ pageId: input.pageId,
712
+ hostId: input.hostId,
713
+ versionId: page.versionId,
714
+ edits: input.edits
715
+ }, input.ifRevision !== undefined ? {
716
+ ifRevision: input.ifRevision
717
+ } : {}, {
718
+ screenIds,
719
+ mediaScopes: input.mediaScopes,
720
+ datasets: scope
721
+ }));
722
+ return 'proposal' in built ? built.proposal : built;
723
+ }
724
+ });
725
+ if (write.ok === false) return (_write_refused = write.refused) != null ? _write_refused : writeRefusal(write.error, write.tooLarge);
726
+ if (write.placement === 'draft') {
727
+ await clearMirror({
728
+ orgId: input.orgId,
729
+ hostId: input.hostId,
730
+ kind: 'screen',
731
+ id: input.pageId,
732
+ versionId: write.versionId
733
+ }).catch((error)=>console.warn('[page content] the co-edit mirror could not be cleared', {
734
+ pageId: input.pageId,
735
+ error
736
+ }));
737
+ }
738
+ // A write asked again finds what it wrote and writes nothing; its
739
+ // revision is the draft's as it stands.
740
+ const revision = write.written ? aiPageContentRevision('draft', write.versionId, write.written.stored) : await readAiPageContent({
741
+ firestore,
742
+ orgId: input.orgId,
743
+ hostId: input.hostId,
744
+ pageId: input.pageId
745
+ }).then((read)=>read.ok ? read.revision : '');
746
+ return {
747
+ ok: true,
748
+ pageId: input.pageId,
749
+ versionId: write.versionId,
750
+ revision,
751
+ applied: input.edits.length,
752
+ created: ((_ref = (_write_written = write.written) == null ? void 0 : _write_written.inserted) != null ? _ref : []).map(({ op, ids })=>({
753
+ index: op,
754
+ id: ids[0],
755
+ ids
756
+ }))
757
+ };
758
+ };
759
+ }
760
+ /** The contract's implementation, as the plugin registers it. */ export const aiPageContentService = {
761
+ read: readAiPageContent,
762
+ editDraft: createAiPageContentEditor()
763
+ };
764
+
765
+ //# sourceMappingURL=ai-page-content.js.map