@vectoriox/iox-ui 5.111.0 → 5.112.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.
- package/assist-core/index.d.ts +650 -0
- package/assist-core/package.json +3 -0
- package/fesm2022/vectoriox-iox-ui-assist-core.mjs +1144 -0
- package/fesm2022/vectoriox-iox-ui-assist-core.mjs.map +1 -0
- package/fesm2022/vectoriox-iox-ui-generation-core.mjs +45 -4
- package/fesm2022/vectoriox-iox-ui-generation-core.mjs.map +1 -1
- package/generation-core/index.d.ts +18 -3
- package/package.json +5 -1
- package/src/assist-core/assist-locale.ts +73 -0
- package/src/assist-core/assist-turn.ts +240 -0
- package/src/assist-core/brief.ts +98 -0
- package/src/assist-core/budget.ts +34 -0
- package/src/assist-core/content-fields.ts +256 -0
- package/src/assist-core/field-edits.ts +178 -0
- package/src/assist-core/field-values.ts +42 -0
- package/src/assist-core/fields-schema.ts +117 -0
- package/src/assist-core/public-api.ts +24 -0
- package/src/assist-core/rich-text.ts +32 -0
- package/src/assist-core/route-schema.ts +49 -0
- package/src/assist-core/summarize-item.ts +219 -0
- package/src/assist-core/surfaces.ts +235 -0
- package/src/generation-core/ai-run.ts +34 -0
- package/src/generation-core/plan-words.ts +12 -3
|
@@ -0,0 +1,1144 @@
|
|
|
1
|
+
import { AiStep, STRICT_SCHEMA_BUDGET, strictSchemaComplexity, jsonText, jsonListOf, jsonOneOf, jsonClosedObject, jsonAnyOf } from '@vectoriox/iox-ui/generation-core';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The surfaces AI Assist runs on (ai-assist-plan §2, §4): each screen that offers a prompt registers ONE spec — what it
|
|
5
|
+
* may change (families), how an accepted change is committed, which model steps a turn uses, the role actions the
|
|
6
|
+
* server re-checks, whether it reads photos and the focus ladder its chip widens along.
|
|
7
|
+
*/
|
|
8
|
+
var AssistSurface;
|
|
9
|
+
(function (AssistSurface) {
|
|
10
|
+
AssistSurface["BuilderPage"] = "builderPage";
|
|
11
|
+
AssistSurface["ContentItem"] = "contentItem";
|
|
12
|
+
AssistSurface["ContentFromPhotos"] = "contentFromPhotos";
|
|
13
|
+
AssistSurface["ContentList"] = "contentList";
|
|
14
|
+
AssistSurface["SchemaType"] = "schemaType";
|
|
15
|
+
AssistSurface["ShopProduct"] = "shopProduct";
|
|
16
|
+
AssistSurface["Media"] = "media";
|
|
17
|
+
AssistSurface["BuilderSite"] = "builderSite";
|
|
18
|
+
AssistSurface["FormInbox"] = "formInbox";
|
|
19
|
+
})(AssistSurface || (AssistSurface = {}));
|
|
20
|
+
/** How an accepted turn reaches the studio (plan §3e). */
|
|
21
|
+
var CommitKind;
|
|
22
|
+
(function (CommitKind) {
|
|
23
|
+
/** One builder history step. */
|
|
24
|
+
CommitKind["BuilderStep"] = "builderStep";
|
|
25
|
+
/** Written into the screen's form; Save stays the owner's. */
|
|
26
|
+
CommitKind["FormFill"] = "formFill";
|
|
27
|
+
/** A server run that writes drafts, with its own Undo. */
|
|
28
|
+
CommitKind["Run"] = "run";
|
|
29
|
+
/** Nothing is written: filters, a copied reply. */
|
|
30
|
+
CommitKind["View"] = "view";
|
|
31
|
+
})(CommitKind || (CommitKind = {}));
|
|
32
|
+
/** The closed edit families a sentence may be answered in — one strict request each. */
|
|
33
|
+
var EditFamily;
|
|
34
|
+
(function (EditFamily) {
|
|
35
|
+
EditFamily["Words"] = "words";
|
|
36
|
+
EditFamily["Sections"] = "sections";
|
|
37
|
+
EditFamily["Style"] = "style";
|
|
38
|
+
EditFamily["Look"] = "look";
|
|
39
|
+
EditFamily["Fields"] = "fields";
|
|
40
|
+
EditFamily["Items"] = "items";
|
|
41
|
+
EditFamily["View"] = "view";
|
|
42
|
+
EditFamily["Schema"] = "schema";
|
|
43
|
+
EditFamily["Media"] = "media";
|
|
44
|
+
EditFamily["Plan"] = "plan";
|
|
45
|
+
})(EditFamily || (EditFamily = {}));
|
|
46
|
+
/** The model steps of a turn — generation-core's `AiStep` rows (Settings ▸ AI ▸ Models), never a second spelling. */
|
|
47
|
+
const AssistStep = {
|
|
48
|
+
AssistRoute: AiStep.AssistRoute,
|
|
49
|
+
AssistEdit: AiStep.AssistEdit,
|
|
50
|
+
AssistRead: AiStep.AssistRead,
|
|
51
|
+
};
|
|
52
|
+
/** One rung of a surface's focus ladder — the chip's ✕ widens to the next rung. */
|
|
53
|
+
var AssistScope;
|
|
54
|
+
(function (AssistScope) {
|
|
55
|
+
AssistScope["Field"] = "field";
|
|
56
|
+
AssistScope["Item"] = "item";
|
|
57
|
+
AssistScope["Type"] = "type";
|
|
58
|
+
AssistScope["Types"] = "types";
|
|
59
|
+
AssistScope["Node"] = "node";
|
|
60
|
+
AssistScope["Section"] = "section";
|
|
61
|
+
AssistScope["Page"] = "page";
|
|
62
|
+
AssistScope["Site"] = "site";
|
|
63
|
+
AssistScope["Photo"] = "photo";
|
|
64
|
+
AssistScope["Photos"] = "photos";
|
|
65
|
+
AssistScope["Rows"] = "rows";
|
|
66
|
+
AssistScope["Slot"] = "slot";
|
|
67
|
+
AssistScope["Library"] = "library";
|
|
68
|
+
AssistScope["Submission"] = "submission";
|
|
69
|
+
})(AssistScope || (AssistScope = {}));
|
|
70
|
+
/** iox-cms role actions (`roles/enums.ts` `Permissions`) a surface needs — the server re-checks them, never only the client. */
|
|
71
|
+
var AssistPermission;
|
|
72
|
+
(function (AssistPermission) {
|
|
73
|
+
AssistPermission["SchemaAll"] = "schema_all";
|
|
74
|
+
AssistPermission["ContentRead"] = "content_read";
|
|
75
|
+
AssistPermission["ContentCreate"] = "content_create";
|
|
76
|
+
AssistPermission["ContentUpdate"] = "content_update";
|
|
77
|
+
AssistPermission["PageRead"] = "page_read";
|
|
78
|
+
AssistPermission["PageCreate"] = "page_create";
|
|
79
|
+
AssistPermission["PageUpdate"] = "page_update";
|
|
80
|
+
AssistPermission["PageDelete"] = "page_delete";
|
|
81
|
+
AssistPermission["StorageAll"] = "storage_all";
|
|
82
|
+
AssistPermission["ProductsAll"] = "products_all";
|
|
83
|
+
})(AssistPermission || (AssistPermission = {}));
|
|
84
|
+
var SurfaceStatus;
|
|
85
|
+
(function (SurfaceStatus) {
|
|
86
|
+
SurfaceStatus["Built"] = "built";
|
|
87
|
+
SurfaceStatus["Planned"] = "planned";
|
|
88
|
+
})(SurfaceStatus || (SurfaceStatus = {}));
|
|
89
|
+
const spec = (s) => ({
|
|
90
|
+
perContentType: false,
|
|
91
|
+
readsPhotos: false,
|
|
92
|
+
...s,
|
|
93
|
+
});
|
|
94
|
+
const SURFACES = {
|
|
95
|
+
[AssistSurface.BuilderPage]: spec({
|
|
96
|
+
surface: AssistSurface.BuilderPage,
|
|
97
|
+
families: [EditFamily.Words, EditFamily.Sections, EditFamily.Style, EditFamily.Look],
|
|
98
|
+
commit: CommitKind.BuilderStep,
|
|
99
|
+
steps: [AssistStep.AssistRoute, AssistStep.AssistEdit],
|
|
100
|
+
permissions: [AssistPermission.PageUpdate],
|
|
101
|
+
scopes: [AssistScope.Node, AssistScope.Section, AssistScope.Page],
|
|
102
|
+
status: SurfaceStatus.Planned,
|
|
103
|
+
}),
|
|
104
|
+
[AssistSurface.ContentItem]: spec({
|
|
105
|
+
surface: AssistSurface.ContentItem,
|
|
106
|
+
families: [EditFamily.Fields],
|
|
107
|
+
commit: CommitKind.FormFill,
|
|
108
|
+
steps: [AssistStep.AssistRoute, AssistStep.AssistEdit],
|
|
109
|
+
permissions: [AssistPermission.ContentUpdate],
|
|
110
|
+
perContentType: true,
|
|
111
|
+
scopes: [AssistScope.Field, AssistScope.Item, AssistScope.Type],
|
|
112
|
+
status: SurfaceStatus.Built,
|
|
113
|
+
}),
|
|
114
|
+
[AssistSurface.ContentFromPhotos]: spec({
|
|
115
|
+
surface: AssistSurface.ContentFromPhotos,
|
|
116
|
+
families: [EditFamily.Fields, EditFamily.Media],
|
|
117
|
+
commit: CommitKind.Run,
|
|
118
|
+
steps: [AssistStep.AssistRoute, AssistStep.AssistRead, AssistStep.AssistEdit],
|
|
119
|
+
permissions: [AssistPermission.ContentCreate, AssistPermission.StorageAll],
|
|
120
|
+
perContentType: true,
|
|
121
|
+
readsPhotos: true,
|
|
122
|
+
scopes: [AssistScope.Photo, AssistScope.Photos, AssistScope.Type],
|
|
123
|
+
status: SurfaceStatus.Planned,
|
|
124
|
+
}),
|
|
125
|
+
[AssistSurface.ContentList]: spec({
|
|
126
|
+
surface: AssistSurface.ContentList,
|
|
127
|
+
families: [EditFamily.View, EditFamily.Items],
|
|
128
|
+
commit: CommitKind.View,
|
|
129
|
+
familyCommits: { [EditFamily.Items]: CommitKind.Run },
|
|
130
|
+
steps: [AssistStep.AssistRoute, AssistStep.AssistEdit],
|
|
131
|
+
permissions: [AssistPermission.ContentRead],
|
|
132
|
+
familyPermissions: { [EditFamily.Items]: [AssistPermission.ContentCreate, AssistPermission.ContentUpdate] },
|
|
133
|
+
perContentType: true,
|
|
134
|
+
scopes: [AssistScope.Rows, AssistScope.Type],
|
|
135
|
+
status: SurfaceStatus.Planned,
|
|
136
|
+
}),
|
|
137
|
+
[AssistSurface.SchemaType]: spec({
|
|
138
|
+
surface: AssistSurface.SchemaType,
|
|
139
|
+
families: [EditFamily.Schema],
|
|
140
|
+
commit: CommitKind.FormFill,
|
|
141
|
+
steps: [AssistStep.AssistRoute, AssistStep.AssistEdit],
|
|
142
|
+
permissions: [AssistPermission.SchemaAll],
|
|
143
|
+
scopes: [AssistScope.Field, AssistScope.Type, AssistScope.Types],
|
|
144
|
+
status: SurfaceStatus.Planned,
|
|
145
|
+
}),
|
|
146
|
+
[AssistSurface.ShopProduct]: spec({
|
|
147
|
+
surface: AssistSurface.ShopProduct,
|
|
148
|
+
families: [EditFamily.Fields],
|
|
149
|
+
commit: CommitKind.FormFill,
|
|
150
|
+
steps: [AssistStep.AssistRoute, AssistStep.AssistRead, AssistStep.AssistEdit],
|
|
151
|
+
permissions: [AssistPermission.ProductsAll],
|
|
152
|
+
readsPhotos: true,
|
|
153
|
+
scopes: [AssistScope.Field, AssistScope.Item],
|
|
154
|
+
status: SurfaceStatus.Planned,
|
|
155
|
+
}),
|
|
156
|
+
[AssistSurface.Media]: spec({
|
|
157
|
+
surface: AssistSurface.Media,
|
|
158
|
+
families: [EditFamily.Media],
|
|
159
|
+
commit: CommitKind.Run,
|
|
160
|
+
steps: [],
|
|
161
|
+
permissions: [AssistPermission.StorageAll],
|
|
162
|
+
readsPhotos: true,
|
|
163
|
+
scopes: [AssistScope.Slot, AssistScope.Library],
|
|
164
|
+
status: SurfaceStatus.Planned,
|
|
165
|
+
}),
|
|
166
|
+
[AssistSurface.BuilderSite]: spec({
|
|
167
|
+
surface: AssistSurface.BuilderSite,
|
|
168
|
+
families: [EditFamily.Plan, EditFamily.Sections],
|
|
169
|
+
commit: CommitKind.Run,
|
|
170
|
+
steps: [AssistStep.AssistRoute, AssistStep.AssistEdit],
|
|
171
|
+
permissions: [AssistPermission.PageCreate, AssistPermission.PageUpdate, AssistPermission.PageDelete],
|
|
172
|
+
familyPermissions: { [EditFamily.Plan]: [AssistPermission.SchemaAll] },
|
|
173
|
+
scopes: [AssistScope.Page, AssistScope.Site],
|
|
174
|
+
status: SurfaceStatus.Planned,
|
|
175
|
+
}),
|
|
176
|
+
[AssistSurface.FormInbox]: spec({
|
|
177
|
+
surface: AssistSurface.FormInbox,
|
|
178
|
+
families: [EditFamily.Words],
|
|
179
|
+
commit: CommitKind.View,
|
|
180
|
+
steps: [AssistStep.AssistRoute, AssistStep.AssistEdit],
|
|
181
|
+
permissions: [AssistPermission.PageRead],
|
|
182
|
+
scopes: [AssistScope.Submission],
|
|
183
|
+
status: SurfaceStatus.Planned,
|
|
184
|
+
}),
|
|
185
|
+
};
|
|
186
|
+
const surfaceSpec = (surface) => SURFACES[surface];
|
|
187
|
+
const builtSurfaces = () => Object.values(SURFACES).filter(s => s.status === SurfaceStatus.Built).map(s => s.surface);
|
|
188
|
+
const commitOf = (surface, family) => SURFACES[surface].familyCommits?.[family] ?? SURFACES[surface].commit;
|
|
189
|
+
const CONTENT_PERMISSION_PREFIX = 'content_';
|
|
190
|
+
const ALL_SUFFIX = '_all';
|
|
191
|
+
/**
|
|
192
|
+
* The permission strings the server checks for a turn on this surface (and these families): `content_<action>` becomes
|
|
193
|
+
* `content_<type>_<action>` on a per-type surface — the same specialisation iox-cms's AuthorizationGuard applies to a
|
|
194
|
+
* `:resource` route, so a user granted only `content_posts_update` may assist on posts and nowhere else.
|
|
195
|
+
*/
|
|
196
|
+
function surfacePermissions(surface, contentType, families = []) {
|
|
197
|
+
const s = SURFACES[surface];
|
|
198
|
+
const all = [...s.permissions, ...families.flatMap(f => s.familyPermissions?.[f] ?? [])];
|
|
199
|
+
const named = all.map(p => {
|
|
200
|
+
if (!s.perContentType || !contentType || !p.startsWith(CONTENT_PERMISSION_PREFIX) || p.endsWith(ALL_SUFFIX))
|
|
201
|
+
return p;
|
|
202
|
+
return `${CONTENT_PERMISSION_PREFIX}${contentType}_${p.slice(CONTENT_PERMISSION_PREFIX.length)}`;
|
|
203
|
+
});
|
|
204
|
+
return [...new Set(named)];
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** The house budget every Assist request is held to (plan F6, trap T7) — generation-core's, never a copy and never raised. */
|
|
208
|
+
const MAX_ASSIST_PROPERTIES = STRICT_SCHEMA_BUDGET.properties;
|
|
209
|
+
/** The route request is small and fast (plan §3a). */
|
|
210
|
+
const MAX_ROUTE_PROPERTIES = 12;
|
|
211
|
+
/** Around-layer text is a summary: at most this many characters per value (plan §3c). */
|
|
212
|
+
const AROUND_TEXT_CHARS = 160;
|
|
213
|
+
/** Sibling items sent as examples of voice (plan §3c: 3–5). */
|
|
214
|
+
const AROUND_ITEMS_MAX = 5;
|
|
215
|
+
/** The session memory sent with a turn: the last turns, one line each (plan §3c). */
|
|
216
|
+
const MEMORY_TURNS = 6;
|
|
217
|
+
class AssistBudgetError extends Error {
|
|
218
|
+
}
|
|
219
|
+
/** What a request's strict schemas break of the house budget — empty when it fits. */
|
|
220
|
+
function assistBudgetIssues(schemas, maxProperties = MAX_ASSIST_PROPERTIES) {
|
|
221
|
+
const c = strictSchemaComplexity(schemas);
|
|
222
|
+
return [
|
|
223
|
+
...c.unsupported,
|
|
224
|
+
...(c.properties > maxProperties ? [`${c.properties} properties (budget ${maxProperties})`] : []),
|
|
225
|
+
...(c.optional > STRICT_SCHEMA_BUDGET.optional ? [`${c.optional} optional (budget ${STRICT_SCHEMA_BUDGET.optional})`] : []),
|
|
226
|
+
...(c.unions > STRICT_SCHEMA_BUDGET.unions ? [`${c.unions} unions (budget ${STRICT_SCHEMA_BUDGET.unions})`] : []),
|
|
227
|
+
];
|
|
228
|
+
}
|
|
229
|
+
function assertAssistBudget(name, schemas, maxProperties) {
|
|
230
|
+
const issues = assistBudgetIssues(schemas, maxProperties);
|
|
231
|
+
if (issues.length)
|
|
232
|
+
throw new AssistBudgetError(`${name}: ${issues.join('; ')}`);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
var AssistIssueCode;
|
|
236
|
+
(function (AssistIssueCode) {
|
|
237
|
+
AssistIssueCode["UnknownHandle"] = "unknownHandle";
|
|
238
|
+
AssistIssueCode["NeverWrite"] = "neverWrite";
|
|
239
|
+
AssistIssueCode["WrongType"] = "wrongType";
|
|
240
|
+
AssistIssueCode["NotAnOption"] = "notAnOption";
|
|
241
|
+
AssistIssueCode["Duplicate"] = "duplicate";
|
|
242
|
+
AssistIssueCode["WrongLocale"] = "wrongLocale";
|
|
243
|
+
AssistIssueCode["HtmlNotAllowed"] = "htmlNotAllowed";
|
|
244
|
+
AssistIssueCode["UnknownFamily"] = "unknownFamily";
|
|
245
|
+
AssistIssueCode["BadRequest"] = "badRequest";
|
|
246
|
+
AssistIssueCode["UnknownSurface"] = "unknownSurface";
|
|
247
|
+
AssistIssueCode["SurfaceNotBuilt"] = "surfaceNotBuilt";
|
|
248
|
+
AssistIssueCode["EmptySentence"] = "emptySentence";
|
|
249
|
+
AssistIssueCode["SentenceTooLong"] = "sentenceTooLong";
|
|
250
|
+
AssistIssueCode["MissingHandles"] = "missingHandles";
|
|
251
|
+
AssistIssueCode["MissingValues"] = "missingValues";
|
|
252
|
+
})(AssistIssueCode || (AssistIssueCode = {}));
|
|
253
|
+
/** A caller's mistake building a brief (a focus that is not on the screen) — never a model answer. */
|
|
254
|
+
class AssistBriefError extends Error {
|
|
255
|
+
constructor(code, message) {
|
|
256
|
+
super(message);
|
|
257
|
+
this.code = code;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
/** The one way a handle becomes a key: an unknown handle is refused, never guessed (trap T1). */
|
|
261
|
+
function resolveHandle(handles, handle) {
|
|
262
|
+
const target = Object.prototype.hasOwnProperty.call(handles, handle) ? handles[handle] : undefined;
|
|
263
|
+
if (target)
|
|
264
|
+
return { ok: true, target };
|
|
265
|
+
return { ok: false, issue: { code: AssistIssueCode.UnknownHandle, handle, message: `"${handle}" is not a handle of this brief` } };
|
|
266
|
+
}
|
|
267
|
+
/** Every handle of the list that the brief does not know. */
|
|
268
|
+
function unknownHandles(handles, list) {
|
|
269
|
+
return list.flatMap(h => {
|
|
270
|
+
const r = resolveHandle(handles, h);
|
|
271
|
+
return 'issue' in r ? [r.issue] : [];
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
const FIELD_HANDLE_PREFIX = 'f.';
|
|
275
|
+
const SIBLING_HANDLE_PREFIX = 's';
|
|
276
|
+
const fieldHandle = (key) => `${FIELD_HANDLE_PREFIX}${key}`;
|
|
277
|
+
|
|
278
|
+
var AssistFieldKind;
|
|
279
|
+
(function (AssistFieldKind) {
|
|
280
|
+
AssistFieldKind["Text"] = "text";
|
|
281
|
+
AssistFieldKind["Textarea"] = "textarea";
|
|
282
|
+
/** Written as plain paragraphs, never HTML (trap T6). */
|
|
283
|
+
AssistFieldKind["RichText"] = "richText";
|
|
284
|
+
AssistFieldKind["Number"] = "number";
|
|
285
|
+
AssistFieldKind["Boolean"] = "boolean";
|
|
286
|
+
/** One of the field's options. */
|
|
287
|
+
AssistFieldKind["Choice"] = "choice";
|
|
288
|
+
/** Some of the field's options. */
|
|
289
|
+
AssistFieldKind["Choices"] = "choices";
|
|
290
|
+
/** A list of words. */
|
|
291
|
+
AssistFieldKind["Tags"] = "tags";
|
|
292
|
+
/** Not writable — `never` says why. */
|
|
293
|
+
AssistFieldKind["Other"] = "other";
|
|
294
|
+
})(AssistFieldKind || (AssistFieldKind = {}));
|
|
295
|
+
var NeverWriteReason;
|
|
296
|
+
(function (NeverWriteReason) {
|
|
297
|
+
NeverWriteReason["Money"] = "money";
|
|
298
|
+
NeverWriteReason["Stock"] = "stock";
|
|
299
|
+
NeverWriteReason["ProductCode"] = "productCode";
|
|
300
|
+
NeverWriteReason["Contact"] = "contact";
|
|
301
|
+
NeverWriteReason["Date"] = "date";
|
|
302
|
+
NeverWriteReason["WebAddress"] = "webAddress";
|
|
303
|
+
NeverWriteReason["Relation"] = "relation";
|
|
304
|
+
NeverWriteReason["Media"] = "media";
|
|
305
|
+
NeverWriteReason["Secret"] = "secret";
|
|
306
|
+
NeverWriteReason["Structure"] = "structure";
|
|
307
|
+
})(NeverWriteReason || (NeverWriteReason = {}));
|
|
308
|
+
/** iox-cms `RESERVED_SCHEMA_PROPERTIES` + read-time bookkeeping + shop catalog bookkeeping — never a field. */
|
|
309
|
+
const NOT_FIELDS = new Set([
|
|
310
|
+
'isPublished', 'organization', 'info', 'addedBy', 'created', 'lastUpdate', '_id', 'isSample', 'pricingUnit',
|
|
311
|
+
]);
|
|
312
|
+
var Control;
|
|
313
|
+
(function (Control) {
|
|
314
|
+
Control["Text"] = "text";
|
|
315
|
+
Control["Tag"] = "tag";
|
|
316
|
+
Control["Textarea"] = "textarea";
|
|
317
|
+
Control["RichText"] = "richText";
|
|
318
|
+
Control["Number"] = "number";
|
|
319
|
+
Control["Range"] = "range";
|
|
320
|
+
Control["Switch"] = "switch";
|
|
321
|
+
Control["Checkbox"] = "checkbox";
|
|
322
|
+
Control["Select"] = "select";
|
|
323
|
+
Control["MultiSelect"] = "multiSelect";
|
|
324
|
+
Control["CheckboxGroup"] = "checkboxGroup";
|
|
325
|
+
Control["Tags"] = "tags";
|
|
326
|
+
Control["List"] = "list";
|
|
327
|
+
Control["MultiLang"] = "multiLang";
|
|
328
|
+
Control["Email"] = "email";
|
|
329
|
+
Control["Password"] = "password";
|
|
330
|
+
Control["Encrypt"] = "encrypt";
|
|
331
|
+
Control["Date"] = "date";
|
|
332
|
+
Control["Time"] = "time";
|
|
333
|
+
Control["Image"] = "image";
|
|
334
|
+
Control["Media"] = "media";
|
|
335
|
+
Control["Gallery"] = "gallery";
|
|
336
|
+
Control["RelationCombobox"] = "relationCombobox";
|
|
337
|
+
Control["Money"] = "money";
|
|
338
|
+
Control["Price"] = "price";
|
|
339
|
+
Control["Currency"] = "currency";
|
|
340
|
+
})(Control || (Control = {}));
|
|
341
|
+
var DataType;
|
|
342
|
+
(function (DataType) {
|
|
343
|
+
DataType["String"] = "string";
|
|
344
|
+
DataType["Array"] = "array";
|
|
345
|
+
DataType["Object"] = "object";
|
|
346
|
+
DataType["Rel"] = "rel";
|
|
347
|
+
DataType["Encrypt"] = "encrypt";
|
|
348
|
+
DataType["Date"] = "date";
|
|
349
|
+
DataType["Money"] = "money";
|
|
350
|
+
})(DataType || (DataType = {}));
|
|
351
|
+
const KIND_OF_CONTROL = {
|
|
352
|
+
[Control.Text]: AssistFieldKind.Text,
|
|
353
|
+
[Control.Tag]: AssistFieldKind.Text,
|
|
354
|
+
[Control.Textarea]: AssistFieldKind.Textarea,
|
|
355
|
+
[Control.RichText]: AssistFieldKind.RichText,
|
|
356
|
+
[Control.Number]: AssistFieldKind.Number,
|
|
357
|
+
[Control.Range]: AssistFieldKind.Number,
|
|
358
|
+
[Control.Switch]: AssistFieldKind.Boolean,
|
|
359
|
+
[Control.Checkbox]: AssistFieldKind.Boolean,
|
|
360
|
+
[Control.Select]: AssistFieldKind.Choice,
|
|
361
|
+
[Control.MultiSelect]: AssistFieldKind.Choices,
|
|
362
|
+
[Control.CheckboxGroup]: AssistFieldKind.Choices,
|
|
363
|
+
[Control.Tags]: AssistFieldKind.Tags,
|
|
364
|
+
[Control.List]: AssistFieldKind.Tags,
|
|
365
|
+
};
|
|
366
|
+
const LIST_KINDS$1 = new Set([AssistFieldKind.Choices, AssistFieldKind.Tags]);
|
|
367
|
+
const CHOICE_KINDS = new Set([AssistFieldKind.Choice, AssistFieldKind.Choices]);
|
|
368
|
+
const NEVER_OF_CONTROL = {
|
|
369
|
+
[Control.Email]: NeverWriteReason.Contact,
|
|
370
|
+
[Control.Password]: NeverWriteReason.Secret,
|
|
371
|
+
[Control.Encrypt]: NeverWriteReason.Secret,
|
|
372
|
+
[Control.Date]: NeverWriteReason.Date,
|
|
373
|
+
[Control.Time]: NeverWriteReason.Date,
|
|
374
|
+
[Control.Image]: NeverWriteReason.Media,
|
|
375
|
+
[Control.Media]: NeverWriteReason.Media,
|
|
376
|
+
[Control.Gallery]: NeverWriteReason.Media,
|
|
377
|
+
[Control.RelationCombobox]: NeverWriteReason.Relation,
|
|
378
|
+
[Control.Money]: NeverWriteReason.Money,
|
|
379
|
+
[Control.Price]: NeverWriteReason.Money,
|
|
380
|
+
[Control.Currency]: NeverWriteReason.Money,
|
|
381
|
+
};
|
|
382
|
+
const NEVER_OF_TYPE = {
|
|
383
|
+
[DataType.Rel]: NeverWriteReason.Relation,
|
|
384
|
+
[DataType.Encrypt]: NeverWriteReason.Secret,
|
|
385
|
+
[DataType.Date]: NeverWriteReason.Date,
|
|
386
|
+
[DataType.Money]: NeverWriteReason.Money,
|
|
387
|
+
};
|
|
388
|
+
/** The closed word list: a key or label word that makes a field a fact the owner gives. */
|
|
389
|
+
const NEVER_WORDS = [
|
|
390
|
+
[NeverWriteReason.Money,
|
|
391
|
+
['price', 'prices', 'pricing', 'cost', 'costs', 'amount', 'fee', 'fees', 'currency', 'discount', 'compareat', 'vat', 'tax', 'total', 'salary', 'budget', 'payment'],
|
|
392
|
+
['מחיר', 'עלות', 'תשלום', 'מע"מ', 'הנחה']],
|
|
393
|
+
[NeverWriteReason.Stock, ['stock', 'quantity', 'qty', 'inventory'], ['מלאי', 'כמות']],
|
|
394
|
+
[NeverWriteReason.ProductCode, ['sku', 'barcode', 'ean', 'upc', 'gtin', 'isbn', 'mpn'], ['מק"ט', 'ברקוד']],
|
|
395
|
+
[NeverWriteReason.Contact,
|
|
396
|
+
['phone', 'tel', 'telephone', 'mobile', 'whatsapp', 'email', 'mail', 'fax', 'address', 'street', 'city', 'zip', 'postcode', 'location', 'hours'],
|
|
397
|
+
['טלפון', 'נייד', 'וואטסאפ', 'דוא"ל', 'אימייל', 'מייל', 'כתובת', 'שעות', 'פקס', 'מיקום']],
|
|
398
|
+
[NeverWriteReason.Date, ['date', 'dates', 'time', 'datetime', 'deadline'], ['תאריך']],
|
|
399
|
+
[NeverWriteReason.WebAddress, ['slug', 'url', 'uri', 'href', 'link', 'website', 'route', 'permalink'], ['קישור', 'לינק']],
|
|
400
|
+
];
|
|
401
|
+
/** `startDate` → start, date · `ticket_link` → ticket, link · `Price (₪)` → price. */
|
|
402
|
+
function words(text) {
|
|
403
|
+
return text.replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
|
|
404
|
+
}
|
|
405
|
+
function neverByWords(key, label) {
|
|
406
|
+
const english = new Set([...words(key), ...words(label)]);
|
|
407
|
+
const raw = `${key} ${label}`;
|
|
408
|
+
return NEVER_WORDS.find(([, en, he]) => en.some(w => english.has(w)) || he.some(w => raw.includes(w)))?.[0];
|
|
409
|
+
}
|
|
410
|
+
function optionValues(options) {
|
|
411
|
+
if (!Array.isArray(options))
|
|
412
|
+
return undefined;
|
|
413
|
+
const values = options.map(o => (o && typeof o === 'object' ? o.value : o))
|
|
414
|
+
.filter(v => v !== undefined && v !== null && v !== '')
|
|
415
|
+
.map(String);
|
|
416
|
+
return values.length ? [...new Set(values)] : undefined;
|
|
417
|
+
}
|
|
418
|
+
const other = (never) => ({ kind: AssistFieldKind.Other, never });
|
|
419
|
+
/** What one leaf property is, by its type and control alone. */
|
|
420
|
+
function leafShape(def) {
|
|
421
|
+
const control = def.controller?.type ?? '';
|
|
422
|
+
const never = NEVER_OF_TYPE[def.type] ?? NEVER_OF_CONTROL[control] ?? (def.items ? NEVER_OF_CONTROL[def.items.controller?.type ?? ''] : undefined);
|
|
423
|
+
if (never)
|
|
424
|
+
return other(never);
|
|
425
|
+
const kind = KIND_OF_CONTROL[control];
|
|
426
|
+
const isList = def.type === DataType.Array;
|
|
427
|
+
if (!kind || isList !== LIST_KINDS$1.has(kind))
|
|
428
|
+
return other(NeverWriteReason.Structure);
|
|
429
|
+
if (isList && def.items && def.items.type !== DataType.String)
|
|
430
|
+
return other(NeverWriteReason.Structure);
|
|
431
|
+
if (!CHOICE_KINDS.has(kind))
|
|
432
|
+
return { kind };
|
|
433
|
+
const options = optionValues(def.controller?.options);
|
|
434
|
+
return options ? { kind, options } : other(NeverWriteReason.Structure);
|
|
435
|
+
}
|
|
436
|
+
const isMultiLang = (def) => def.controller?.type === Control.MultiLang && !!def.properties;
|
|
437
|
+
function fieldOf(key, def) {
|
|
438
|
+
const label = def.label || key;
|
|
439
|
+
const base = { key, handle: fieldHandle(key), label, required: !!def.required };
|
|
440
|
+
if (isMultiLang(def)) {
|
|
441
|
+
const locales = Object.keys(def.properties ?? {});
|
|
442
|
+
const inner = locales.length ? leafShape(def.properties[locales[0]]) : other(NeverWriteReason.Structure);
|
|
443
|
+
const never = inner.never ?? neverByWords(key, label);
|
|
444
|
+
return never ? { ...base, kind: AssistFieldKind.Other, locales, never } : { ...base, ...inner, locales };
|
|
445
|
+
}
|
|
446
|
+
if (def.type === DataType.Object)
|
|
447
|
+
return { ...base, ...other(NeverWriteReason.Structure) };
|
|
448
|
+
const shape = leafShape(def);
|
|
449
|
+
const never = shape.never ?? neverByWords(key, label);
|
|
450
|
+
return never ? { ...base, kind: AssistFieldKind.Other, never } : { ...base, ...shape };
|
|
451
|
+
}
|
|
452
|
+
/** A property the item form renders: not bookkeeping, and (a leaf) carrying a control. */
|
|
453
|
+
const isFormField = (key, def) => !NOT_FIELDS.has(key) && !!def && (def.type === DataType.Object || !!def.controller);
|
|
454
|
+
/** Every form field of the type, in schema order, writable or with the reason it is never written. */
|
|
455
|
+
function assistFields(schema) {
|
|
456
|
+
return Object.entries(schema.schemaObject?.properties ?? {})
|
|
457
|
+
.filter(([key, def]) => isFormField(key, def))
|
|
458
|
+
.map(([key, def]) => fieldOf(key, def));
|
|
459
|
+
}
|
|
460
|
+
const isWritable = (field) => !field.never;
|
|
461
|
+
/** The type's title field: its `@title` role (`metaData.previewTextField`), else its first text field. */
|
|
462
|
+
function titleField(schema, fields = assistFields(schema)) {
|
|
463
|
+
const role = schema.metaData?.previewTextField;
|
|
464
|
+
return fields.find(f => f.key === role) ?? fields.find(f => f.kind === AssistFieldKind.Text);
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/**
|
|
468
|
+
* Rich text crosses the model boundary as PLAIN PARAGRAPHS in both directions (trap T6): the brief reads the stored
|
|
469
|
+
* value (the item editor's Quill writes HTML) as paragraphs, and an answer's paragraphs become HTML only here, every
|
|
470
|
+
* character escaped — the model never writes markup that reaches a page.
|
|
471
|
+
*/
|
|
472
|
+
const BLOCK_END = /<\/(p|div|h[1-6]|li|blockquote|pre)>|<br\s*\/?>/gi;
|
|
473
|
+
const TAG = /<[^>]*>/g;
|
|
474
|
+
const HTML_TAG = /<\/?[a-z][a-z0-9-]*(\s[^<>]*)?\/?>/i;
|
|
475
|
+
const ENTITIES = { '&': '&', '<': '<', '>': '>', '"': '"', ''': "'", ' ': ' ' };
|
|
476
|
+
const ESCAPES = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
|
|
477
|
+
const decode = (text) => text.replace(/&(amp|lt|gt|quot|#39|nbsp);/g, e => ENTITIES[e] ?? e);
|
|
478
|
+
const escape = (text) => text.replace(/[&<>"']/g, c => ESCAPES[c]);
|
|
479
|
+
/** A stored rich-text value (HTML, or plain text) as its non-empty paragraphs. */
|
|
480
|
+
function richTextParagraphs(value) {
|
|
481
|
+
if (typeof value !== 'string')
|
|
482
|
+
return [];
|
|
483
|
+
return decode(value.replace(BLOCK_END, '\n').replace(TAG, ''))
|
|
484
|
+
.split(/\n+/)
|
|
485
|
+
.map(p => p.replace(/\s+/g, ' ').trim())
|
|
486
|
+
.filter(Boolean);
|
|
487
|
+
}
|
|
488
|
+
/** Paragraphs as the editor's HTML: one `<p>` each, escaped. */
|
|
489
|
+
function paragraphsToRichText(paragraphs) {
|
|
490
|
+
return paragraphs.map(p => `<p>${escape(p.trim())}</p>`).join('');
|
|
491
|
+
}
|
|
492
|
+
/** True when a text written by the model carries markup — refused, never stripped. */
|
|
493
|
+
const containsHtml = (text) => HTML_TAG.test(text);
|
|
494
|
+
|
|
495
|
+
const LIST_KINDS = new Set([AssistFieldKind.Choices, AssistFieldKind.Tags]);
|
|
496
|
+
const isPlainRecord = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
|
|
497
|
+
const asStrings = (v) => (Array.isArray(v) ? v.filter(x => x !== null && x !== undefined && x !== '').map(String) : []);
|
|
498
|
+
function readNumber(raw) {
|
|
499
|
+
if (typeof raw === 'number')
|
|
500
|
+
return Number.isFinite(raw) ? raw : null;
|
|
501
|
+
if (typeof raw !== 'string' || raw.trim() === '')
|
|
502
|
+
return null;
|
|
503
|
+
const n = Number(raw);
|
|
504
|
+
return Number.isFinite(n) ? n : null;
|
|
505
|
+
}
|
|
506
|
+
/** One stored value (a plain field, or one locale of a multiLang field) in its kind's readable form. */
|
|
507
|
+
function readFieldValue(kind, raw) {
|
|
508
|
+
if (raw === undefined || raw === null)
|
|
509
|
+
return null;
|
|
510
|
+
if (kind === AssistFieldKind.RichText)
|
|
511
|
+
return richTextParagraphs(raw);
|
|
512
|
+
if (LIST_KINDS.has(kind))
|
|
513
|
+
return asStrings(raw);
|
|
514
|
+
if (kind === AssistFieldKind.Number)
|
|
515
|
+
return readNumber(raw);
|
|
516
|
+
if (kind === AssistFieldKind.Boolean)
|
|
517
|
+
return !!raw;
|
|
518
|
+
return typeof raw === 'string' ? raw : String(raw);
|
|
519
|
+
}
|
|
520
|
+
function isEmptyFieldValue(v) {
|
|
521
|
+
if (v === null || v === undefined)
|
|
522
|
+
return true;
|
|
523
|
+
if (typeof v === 'string')
|
|
524
|
+
return v.trim() === '';
|
|
525
|
+
if (Array.isArray(v))
|
|
526
|
+
return v.length === 0;
|
|
527
|
+
if (isPlainRecord(v))
|
|
528
|
+
return Object.values(v).every(isEmptyFieldValue);
|
|
529
|
+
return false;
|
|
530
|
+
}
|
|
531
|
+
/** A multiLang value's locales, each read in the field's kind. */
|
|
532
|
+
function readLocaleValues(kind, locales, raw) {
|
|
533
|
+
const values = isPlainRecord(raw) ? raw : {};
|
|
534
|
+
return Object.fromEntries(locales.map(l => [l, readFieldValue(kind, values[l])]));
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
const ID_KEY = '_id';
|
|
538
|
+
const ELLIPSIS = '…';
|
|
539
|
+
const LIST_JOIN = ', ';
|
|
540
|
+
const PARAGRAPH_JOIN = '\n\n';
|
|
541
|
+
const TEXT_KINDS = new Set([AssistFieldKind.Text, AssistFieldKind.Textarea, AssistFieldKind.RichText]);
|
|
542
|
+
const clipText = (text, max = AROUND_TEXT_CHARS) => text.length <= max ? text : `${text.slice(0, max - ELLIPSIS.length).trimEnd()}${ELLIPSIS}`;
|
|
543
|
+
function briefField(field, raw, locale) {
|
|
544
|
+
const base = { handle: field.handle, label: field.label, kind: field.kind, required: field.required };
|
|
545
|
+
if (field.never)
|
|
546
|
+
return { ...base, empty: isEmptyFieldValue(raw), never: field.never };
|
|
547
|
+
const options = field.options ? { options: field.options } : {};
|
|
548
|
+
if (field.locales) {
|
|
549
|
+
const values = readLocaleValues(field.kind, field.locales, raw);
|
|
550
|
+
const filled = field.locales.filter(l => !isEmptyFieldValue(values[l]));
|
|
551
|
+
return {
|
|
552
|
+
...base, ...options,
|
|
553
|
+
empty: isEmptyFieldValue(values[locale]),
|
|
554
|
+
value: values,
|
|
555
|
+
locales: { filled, empty: field.locales.filter(l => !filled.includes(l)) },
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
const value = readFieldValue(field.kind, raw);
|
|
559
|
+
return { ...base, ...options, empty: isEmptyFieldValue(value), value };
|
|
560
|
+
}
|
|
561
|
+
const localeOrFirst = (values, locale) => !isEmptyFieldValue(values[locale]) ? values[locale] : Object.values(values).find(v => !isEmptyFieldValue(v)) ?? null;
|
|
562
|
+
/** A value as one clipped line: the write locale first (else the first filled one), paragraphs and lists joined. */
|
|
563
|
+
function summaryText(field, raw, locale) {
|
|
564
|
+
const value = field.locales ? localeOrFirst(readLocaleValues(field.kind, field.locales, raw), locale) : readFieldValue(field.kind, raw);
|
|
565
|
+
if (value === null)
|
|
566
|
+
return '';
|
|
567
|
+
const text = Array.isArray(value) ? value.join(field.kind === AssistFieldKind.RichText ? PARAGRAPH_JOIN : LIST_JOIN) : String(value);
|
|
568
|
+
return clipText(text.replace(/\s+/g, ' ').trim());
|
|
569
|
+
}
|
|
570
|
+
function summaries(fields, record, locale) {
|
|
571
|
+
return Object.fromEntries(fields
|
|
572
|
+
.map(f => [f.handle, summaryText(f, record[f.key], locale)])
|
|
573
|
+
.filter(([, text]) => text !== ''));
|
|
574
|
+
}
|
|
575
|
+
function findFocusField(fields, focus) {
|
|
576
|
+
const found = fields.find(f => f.key === focus || f.handle === focus || f.handle === `${FIELD_HANDLE_PREFIX}${focus}`);
|
|
577
|
+
if (!found)
|
|
578
|
+
throw new AssistBriefError(AssistIssueCode.UnknownHandle, `"${focus}" is not a field of this type`);
|
|
579
|
+
return found;
|
|
580
|
+
}
|
|
581
|
+
const neverList = (fields) => fields.filter(f => f.never).map(f => ({ handle: f.handle, label: f.label, reason: f.never }));
|
|
582
|
+
function siblingsOf(record, siblings) {
|
|
583
|
+
const own = record[ID_KEY];
|
|
584
|
+
return siblings.filter(s => own === undefined || s[ID_KEY] !== own).slice(0, AROUND_ITEMS_MAX);
|
|
585
|
+
}
|
|
586
|
+
/** S2's brief and its handle map: `f.<key>` per field, `s<n>` per sibling (its id stays in the map, never sent). */
|
|
587
|
+
function summarizeItem(schema, item, ctx) {
|
|
588
|
+
const fields = assistFields(schema);
|
|
589
|
+
const focused = ctx.focusField ? findFocusField(fields, ctx.focusField) : null;
|
|
590
|
+
const title = titleField(schema, fields);
|
|
591
|
+
const voiceFields = fields.filter(f => isWritable(f) && TEXT_KINDS.has(f.kind));
|
|
592
|
+
const siblings = siblingsOf(item, ctx.siblings ?? []);
|
|
593
|
+
const siblingHandle = (i) => `${SIBLING_HANDLE_PREFIX}${i + 1}`;
|
|
594
|
+
const surface = SURFACES[AssistSurface.ContentItem];
|
|
595
|
+
const scope = focused ? AssistScope.Field : AssistScope.Item;
|
|
596
|
+
const handles = Object.fromEntries([
|
|
597
|
+
...fields.map(f => [f.handle, { key: f.key, path: [f.key] }]),
|
|
598
|
+
...siblings.map((s, i) => [siblingHandle(i), { key: siblingHandle(i), path: [], ...(s[ID_KEY] !== undefined ? { id: String(s[ID_KEY]) } : {}) }]),
|
|
599
|
+
]);
|
|
600
|
+
const brief = {
|
|
601
|
+
surface: AssistSurface.ContentItem,
|
|
602
|
+
focus: {
|
|
603
|
+
scope,
|
|
604
|
+
type: { name: schema.name, label: schema.metaData?.label || schema.name },
|
|
605
|
+
title: title ? summaryText(title, item[title.key], ctx.locale) : '',
|
|
606
|
+
titleHandle: title?.handle ?? null,
|
|
607
|
+
fields: (focused ? [focused] : fields).map(f => briefField(f, item[f.key], ctx.locale)),
|
|
608
|
+
},
|
|
609
|
+
around: {
|
|
610
|
+
item: focused ? summaries(fields.filter(f => f !== focused && isWritable(f)), item, ctx.locale) : null,
|
|
611
|
+
siblings: siblings.map((s, i) => ({
|
|
612
|
+
handle: siblingHandle(i),
|
|
613
|
+
title: title ? summaryText(title, s[title.key], ctx.locale) : '',
|
|
614
|
+
fields: summaries(voiceFields, s, ctx.locale),
|
|
615
|
+
})),
|
|
616
|
+
},
|
|
617
|
+
owner: ctx.owner ?? null,
|
|
618
|
+
rules: {
|
|
619
|
+
families: surface.families,
|
|
620
|
+
locale: ctx.locale,
|
|
621
|
+
never: neverList(fields),
|
|
622
|
+
scope,
|
|
623
|
+
widensTo: surface.scopes.slice(surface.scopes.indexOf(scope) + 1),
|
|
624
|
+
},
|
|
625
|
+
memory: (ctx.memory ?? []).slice(-MEMORY_TURNS),
|
|
626
|
+
};
|
|
627
|
+
return { brief, handles };
|
|
628
|
+
}
|
|
629
|
+
var ItemSuggestionKind;
|
|
630
|
+
(function (ItemSuggestionKind) {
|
|
631
|
+
ItemSuggestionKind["FillEmpty"] = "fillEmpty";
|
|
632
|
+
ItemSuggestionKind["Translate"] = "translate";
|
|
633
|
+
ItemSuggestionKind["Shorten"] = "shorten";
|
|
634
|
+
ItemSuggestionKind["WriteSeo"] = "writeSeo";
|
|
635
|
+
})(ItemSuggestionKind || (ItemSuggestionKind = {}));
|
|
636
|
+
/** A text this long is worth a "Shorten". */
|
|
637
|
+
const SHORTEN_FROM_CHARS = 280;
|
|
638
|
+
const SEO_WORDS = ['seo', 'meta'];
|
|
639
|
+
const textLength = (v) => typeof v === 'string' ? v.length : Array.isArray(v) ? v.join(' ').length : 0;
|
|
640
|
+
function translations(writable) {
|
|
641
|
+
const byLocale = new Map();
|
|
642
|
+
for (const f of writable) {
|
|
643
|
+
if (!f.locales || !f.locales.filled.length)
|
|
644
|
+
continue;
|
|
645
|
+
for (const l of f.locales.empty)
|
|
646
|
+
byLocale.set(l, [...(byLocale.get(l) ?? []), f.handle]);
|
|
647
|
+
}
|
|
648
|
+
return [...byLocale].map(([locale, handles]) => ({ kind: ItemSuggestionKind.Translate, locale, handles }));
|
|
649
|
+
}
|
|
650
|
+
/** S2's quick actions: Fill empty fields, Translate to <locale>, Shorten, Write SEO — each only when it applies. */
|
|
651
|
+
function itemSuggestions(brief) {
|
|
652
|
+
const writable = brief.focus.fields.filter(f => !f.never);
|
|
653
|
+
const empty = writable.filter(f => f.empty).map(f => f.handle);
|
|
654
|
+
const long = writable.filter(f => TEXT_KINDS.has(f.kind) && !f.locales && textLength(f.value) >= SHORTEN_FROM_CHARS).map(f => f.handle);
|
|
655
|
+
const seo = writable.filter(f => SEO_WORDS.some(w => f.handle.slice(FIELD_HANDLE_PREFIX.length).toLowerCase().startsWith(w))).map(f => f.handle);
|
|
656
|
+
return [
|
|
657
|
+
...(empty.length ? [{ kind: ItemSuggestionKind.FillEmpty, handles: empty }] : []),
|
|
658
|
+
...translations(writable),
|
|
659
|
+
...(long.length ? [{ kind: ItemSuggestionKind.Shorten, handles: long }] : []),
|
|
660
|
+
...(seo.length ? [{ kind: ItemSuggestionKind.WriteSeo, handles: seo }] : []),
|
|
661
|
+
];
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
/**
|
|
665
|
+
* The strict output format of family `fields` for one content type (plan §3b): one property per WRITABLE field, keyed
|
|
666
|
+
* by its handle, every key required, every object closed. "Leave it as it is" is the kind's NONE value — `''` for a
|
|
667
|
+
* text, a number (written in digits), a yes/no or a choice, `[]` for paragraphs and lists — never `null`: the house
|
|
668
|
+
* budget allows 8 unions a request, so nullable fields would cap a part at 8 fields; the house wire (plan-edits) uses
|
|
669
|
+
* the same "every key required, each with its none". So Assist never EMPTIES a field — clearing one is the owner's.
|
|
670
|
+
* Rich text is a list of plain paragraphs (trap T6); a multiLang field is written in ONE locale (trap T5). A type with
|
|
671
|
+
* more writable fields than one request holds is split into parts, each ≤ 40 properties (trap T7 — never raised).
|
|
672
|
+
*/
|
|
673
|
+
var FieldsAnswerKey;
|
|
674
|
+
(function (FieldsAnswerKey) {
|
|
675
|
+
FieldsAnswerKey["Fields"] = "fields";
|
|
676
|
+
FieldsAnswerKey["Note"] = "note";
|
|
677
|
+
})(FieldsAnswerKey || (FieldsAnswerKey = {}));
|
|
678
|
+
/** The answer object's own keys, beside the fields. */
|
|
679
|
+
const PART_OWN_PROPERTIES = Object.keys(FieldsAnswerKey).length;
|
|
680
|
+
/** How many fields one request carries. */
|
|
681
|
+
const FIELDS_PER_PART = MAX_ASSIST_PROPERTIES - PART_OWN_PROPERTIES;
|
|
682
|
+
const NONE_TEXT = '';
|
|
683
|
+
const BOOLEAN_TRUE = 'true';
|
|
684
|
+
const BOOLEAN_FALSE = 'false';
|
|
685
|
+
const LEAVE_TEXT = `'' leaves it as it is`;
|
|
686
|
+
const LEAVE_LIST = '[] leaves it as it is';
|
|
687
|
+
function kindSchema(field) {
|
|
688
|
+
const options = [...(field.options ?? [])];
|
|
689
|
+
switch (field.kind) {
|
|
690
|
+
case AssistFieldKind.RichText: return { schema: jsonListOf(jsonText()), says: `paragraphs of plain text, no markup; ${LEAVE_LIST}` };
|
|
691
|
+
case AssistFieldKind.Number: return { schema: jsonText(), says: `a number in digits; ${LEAVE_TEXT}` };
|
|
692
|
+
case AssistFieldKind.Boolean: return { schema: jsonOneOf([NONE_TEXT, BOOLEAN_TRUE, BOOLEAN_FALSE]), says: `yes or no; ${LEAVE_TEXT}` };
|
|
693
|
+
case AssistFieldKind.Choice: return { schema: jsonOneOf([NONE_TEXT, ...options]), says: `one of its options; ${LEAVE_TEXT}` };
|
|
694
|
+
case AssistFieldKind.Choices: return { schema: jsonListOf(jsonOneOf(options)), says: `some of its options; ${LEAVE_LIST}` };
|
|
695
|
+
case AssistFieldKind.Tags: return { schema: jsonListOf(jsonText()), says: `a list of short words; ${LEAVE_LIST}` };
|
|
696
|
+
case AssistFieldKind.Textarea: return { schema: jsonText(), says: `plain text, may run several sentences; ${LEAVE_TEXT}` };
|
|
697
|
+
default: return { schema: jsonText(), says: `one line of plain text; ${LEAVE_TEXT}` };
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
function fieldSchema(field, locale) {
|
|
701
|
+
const { schema, says } = kindSchema(field);
|
|
702
|
+
const inLocale = field.locales ? ` Written in ${locale} only.` : '';
|
|
703
|
+
return { ...schema, description: `${field.label}${field.required ? ' (required)' : ''} — ${says}.${inLocale}` };
|
|
704
|
+
}
|
|
705
|
+
function chosen(all, wanted) {
|
|
706
|
+
if (!wanted)
|
|
707
|
+
return all.filter(isWritable);
|
|
708
|
+
return wanted.map(w => {
|
|
709
|
+
const f = all.find(x => x.key === w || x.handle === w);
|
|
710
|
+
if (!f)
|
|
711
|
+
throw new AssistBriefError(AssistIssueCode.UnknownHandle, `"${w}" is not a field of this type`);
|
|
712
|
+
return f;
|
|
713
|
+
}).filter(isWritable);
|
|
714
|
+
}
|
|
715
|
+
/** Splits n fields into the fewest parts that fit, as even as they come. */
|
|
716
|
+
function split(list, max) {
|
|
717
|
+
if (!list.length)
|
|
718
|
+
return [];
|
|
719
|
+
const count = Math.ceil(list.length / max);
|
|
720
|
+
const size = Math.ceil(list.length / count);
|
|
721
|
+
return Array.from({ length: count }, (_, i) => list.slice(i * size, (i + 1) * size));
|
|
722
|
+
}
|
|
723
|
+
function partSchema(fields, locale, part, of) {
|
|
724
|
+
const properties = Object.fromEntries(fields.map(f => [f.handle, fieldSchema(f, locale)]));
|
|
725
|
+
const which = of > 1 ? ` (part ${part + 1} of ${of})` : '';
|
|
726
|
+
return jsonClosedObject({
|
|
727
|
+
[FieldsAnswerKey.Fields]: jsonClosedObject(properties, fields.map(f => f.handle), `Per field${which}: its new value, or its leave value.`),
|
|
728
|
+
[FieldsAnswerKey.Note]: { ...jsonText(), description: 'One short line for the owner on what changed, or what needs them.' },
|
|
729
|
+
}, Object.values(FieldsAnswerKey));
|
|
730
|
+
}
|
|
731
|
+
function fieldsJsonSchema(schema, options) {
|
|
732
|
+
const groups = split(chosen(assistFields(schema), options.fields), FIELDS_PER_PART);
|
|
733
|
+
const parts = groups.map((g, i) => partSchema(g, options.locale, i, groups.length));
|
|
734
|
+
parts.forEach((p, i) => assertAssistBudget(`fields ${schema.name} part ${i + 1}`, [p]));
|
|
735
|
+
return { parts, handles: groups.map(g => g.map(f => f.handle)) };
|
|
736
|
+
}
|
|
737
|
+
const isLeave = (v) => v === null || v === undefined || v === NONE_TEXT || (Array.isArray(v) && v.length === 0);
|
|
738
|
+
/** The parts' answers → the edits they make (every leave value dropped). */
|
|
739
|
+
function decodeFieldsAnswers(answers) {
|
|
740
|
+
return answers.flatMap(answer => {
|
|
741
|
+
const fields = answer && typeof answer === 'object' ? answer[FieldsAnswerKey.Fields] : undefined;
|
|
742
|
+
if (!fields || typeof fields !== 'object' || Array.isArray(fields))
|
|
743
|
+
return [];
|
|
744
|
+
return Object.entries(fields).filter(([, v]) => !isLeave(v)).map(([handle, value]) => ({ handle, value }));
|
|
745
|
+
});
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
/**
|
|
749
|
+
* The route request (plan §3c rule 5): the first, small, fast question of every turn — which of THIS surface's
|
|
750
|
+
* families the sentence needs, or `cannot` with one line for the owner. Its family enum is the surface's, so the model
|
|
751
|
+
* cannot route a content-item sentence to the builder's Style.
|
|
752
|
+
*/
|
|
753
|
+
var RouteAnswerKey;
|
|
754
|
+
(function (RouteAnswerKey) {
|
|
755
|
+
RouteAnswerKey["Families"] = "families";
|
|
756
|
+
RouteAnswerKey["Cannot"] = "cannot";
|
|
757
|
+
RouteAnswerKey["Reply"] = "reply";
|
|
758
|
+
})(RouteAnswerKey || (RouteAnswerKey = {}));
|
|
759
|
+
function routeJsonSchema(surface) {
|
|
760
|
+
const schema = jsonClosedObject({
|
|
761
|
+
[RouteAnswerKey.Families]: { ...jsonListOf(jsonOneOf(SURFACES[surface].families)), description: 'The kinds of change the sentence asks for, in the order to make them. [] when it cannot be done here.' },
|
|
762
|
+
[RouteAnswerKey.Cannot]: { ...jsonAnyOf([jsonText(), { type: 'null' }]), description: 'Why it cannot be done here, in one line in the sentence\'s language — or null.' },
|
|
763
|
+
[RouteAnswerKey.Reply]: { ...jsonText(), description: 'One short line to the owner, in the sentence\'s language.' },
|
|
764
|
+
}, Object.values(RouteAnswerKey));
|
|
765
|
+
assertAssistBudget(`route ${surface}`, [schema], MAX_ROUTE_PROPERTIES);
|
|
766
|
+
return schema;
|
|
767
|
+
}
|
|
768
|
+
const text = (v) => (typeof v === 'string' ? v.trim() : '');
|
|
769
|
+
/** A route answer, checked against its surface: a family the surface does not have is refused, repeats dropped. */
|
|
770
|
+
function readRoute(surface, answer) {
|
|
771
|
+
const a = (answer && typeof answer === 'object' ? answer : {});
|
|
772
|
+
const allowed = new Set(SURFACES[surface].families);
|
|
773
|
+
const named = Array.isArray(a[RouteAnswerKey.Families]) ? a[RouteAnswerKey.Families].map(String) : [];
|
|
774
|
+
const issues = named.filter(f => !allowed.has(f))
|
|
775
|
+
.map(f => ({ code: AssistIssueCode.UnknownFamily, message: `"${f}" is not a family of ${surface}` }));
|
|
776
|
+
const families = [...new Set(named.filter(f => allowed.has(f)))];
|
|
777
|
+
const cannot = text(a[RouteAnswerKey.Cannot]) || null;
|
|
778
|
+
return { ok: !issues.length, families: cannot ? [] : families, cannot, reply: text(a[RouteAnswerKey.Reply]), issues };
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
const refuse = (code, message) => ({ ok: false, code, message });
|
|
782
|
+
const wrongType = (what) => refuse(AssistIssueCode.WrongType, `expected ${what}`);
|
|
783
|
+
const fine = (stored, readable = stored) => ({ ok: true, stored, readable });
|
|
784
|
+
function coerceText(value) {
|
|
785
|
+
if (typeof value !== 'string' || !value.trim())
|
|
786
|
+
return wrongType('a non-empty text');
|
|
787
|
+
if (containsHtml(value))
|
|
788
|
+
return refuse(AssistIssueCode.HtmlNotAllowed, 'markup is not written by Assist');
|
|
789
|
+
return fine(value.trim());
|
|
790
|
+
}
|
|
791
|
+
function coerceWords(value) {
|
|
792
|
+
if (!Array.isArray(value) || value.some(v => typeof v !== 'string'))
|
|
793
|
+
return wrongType('a list of texts');
|
|
794
|
+
const words = [...new Set(value.map(v => v.trim()).filter(Boolean))];
|
|
795
|
+
if (!words.length)
|
|
796
|
+
return wrongType('at least one text');
|
|
797
|
+
if (words.some(containsHtml))
|
|
798
|
+
return refuse(AssistIssueCode.HtmlNotAllowed, 'markup is not written by Assist');
|
|
799
|
+
return { words };
|
|
800
|
+
}
|
|
801
|
+
function coerceNumber(value) {
|
|
802
|
+
const n = typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value.trim()) : NaN;
|
|
803
|
+
return Number.isFinite(n) ? fine(n) : wrongType('a number');
|
|
804
|
+
}
|
|
805
|
+
function coerceBoolean(value) {
|
|
806
|
+
if (typeof value === 'boolean')
|
|
807
|
+
return fine(value);
|
|
808
|
+
if (value === BOOLEAN_TRUE || value === BOOLEAN_FALSE)
|
|
809
|
+
return fine(value === BOOLEAN_TRUE);
|
|
810
|
+
return wrongType('yes or no');
|
|
811
|
+
}
|
|
812
|
+
function coerceChoice(field, value) {
|
|
813
|
+
if (typeof value !== 'string')
|
|
814
|
+
return wrongType('one of the options');
|
|
815
|
+
return field.options?.includes(value) ? fine(value) : refuse(AssistIssueCode.NotAnOption, `"${value}" is not an option of ${field.label}`);
|
|
816
|
+
}
|
|
817
|
+
function coerceList(field, value) {
|
|
818
|
+
const read = coerceWords(value);
|
|
819
|
+
if (!('words' in read))
|
|
820
|
+
return read;
|
|
821
|
+
if (field.kind === AssistFieldKind.Choices) {
|
|
822
|
+
const outside = read.words.filter(w => !field.options?.includes(w));
|
|
823
|
+
if (outside.length)
|
|
824
|
+
return refuse(AssistIssueCode.NotAnOption, `${outside.map(w => `"${w}"`).join(', ')} not an option of ${field.label}`);
|
|
825
|
+
}
|
|
826
|
+
return fine(read.words);
|
|
827
|
+
}
|
|
828
|
+
function coerceRichText(value) {
|
|
829
|
+
const read = coerceWords(value);
|
|
830
|
+
if (!('words' in read))
|
|
831
|
+
return read;
|
|
832
|
+
return fine(paragraphsToRichText(read.words), read.words);
|
|
833
|
+
}
|
|
834
|
+
function coerce(field, value) {
|
|
835
|
+
switch (field.kind) {
|
|
836
|
+
case AssistFieldKind.RichText: return coerceRichText(value);
|
|
837
|
+
case AssistFieldKind.Number: return coerceNumber(value);
|
|
838
|
+
case AssistFieldKind.Boolean: return coerceBoolean(value);
|
|
839
|
+
case AssistFieldKind.Choice: return coerceChoice(field, value);
|
|
840
|
+
case AssistFieldKind.Choices:
|
|
841
|
+
case AssistFieldKind.Tags: return coerceList(field, value);
|
|
842
|
+
default: return coerceText(value);
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
const NAME_MIN_CHARS = 3;
|
|
846
|
+
/** The fields a sentence names by label, key or handle (case-insensitive) — rule 9's "unless the sentence names it". */
|
|
847
|
+
function fieldsNamedIn(sentence, fields) {
|
|
848
|
+
const s = sentence.toLowerCase();
|
|
849
|
+
if (!s.trim())
|
|
850
|
+
return [];
|
|
851
|
+
return fields.filter(f => [f.label, f.key, f.handle].some(n => n.length >= NAME_MIN_CHARS && s.includes(n.toLowerCase()))).map(f => f.key);
|
|
852
|
+
}
|
|
853
|
+
const names = (list, fields) => new Set((list ?? []).map(n => fields.find(f => f.key === n || f.handle === n)?.key ?? n));
|
|
854
|
+
function plan(field, handle, values, coerced, locale) {
|
|
855
|
+
const raw = values[field.key];
|
|
856
|
+
const own = field.locales ? (isPlainRecord(raw) ? raw : {}) : null;
|
|
857
|
+
const before = readFieldValue(field.kind, own ? own[locale] : raw);
|
|
858
|
+
if (JSON.stringify(before) === JSON.stringify(coerced.readable))
|
|
859
|
+
return null;
|
|
860
|
+
const stored = own ? { ...own, [locale]: coerced.stored } : coerced.stored;
|
|
861
|
+
const change = {
|
|
862
|
+
handle, key: field.key, label: field.label, kind: field.kind, before, after: coerced.readable, ...(own ? { locale } : {}),
|
|
863
|
+
};
|
|
864
|
+
return { field, stored, change };
|
|
865
|
+
}
|
|
866
|
+
function applyFieldEdits(values, edits, ctx) {
|
|
867
|
+
const fields = assistFields(ctx.schema);
|
|
868
|
+
const issues = [];
|
|
869
|
+
const planned = [];
|
|
870
|
+
const seen = new Set();
|
|
871
|
+
const issue = (code, handle, message) => issues.push({ code, handle, message });
|
|
872
|
+
for (const edit of edits) {
|
|
873
|
+
const resolved = resolveHandle(ctx.handles, edit.handle);
|
|
874
|
+
if ('issue' in resolved) {
|
|
875
|
+
issues.push(resolved.issue);
|
|
876
|
+
continue;
|
|
877
|
+
}
|
|
878
|
+
const field = fields.find(f => f.key === resolved.target.key);
|
|
879
|
+
if (!field) {
|
|
880
|
+
issue(AssistIssueCode.UnknownHandle, edit.handle, `"${edit.handle}" is not a field of ${ctx.schema.name}`);
|
|
881
|
+
continue;
|
|
882
|
+
}
|
|
883
|
+
if (seen.has(field.key)) {
|
|
884
|
+
issue(AssistIssueCode.Duplicate, edit.handle, `${field.label} is written twice`);
|
|
885
|
+
continue;
|
|
886
|
+
}
|
|
887
|
+
seen.add(field.key);
|
|
888
|
+
if (field.never) {
|
|
889
|
+
issue(AssistIssueCode.NeverWrite, edit.handle, `${field.label} is never written by Assist (${field.never})`);
|
|
890
|
+
continue;
|
|
891
|
+
}
|
|
892
|
+
if (field.locales && !field.locales.includes(ctx.locale)) {
|
|
893
|
+
issue(AssistIssueCode.WrongLocale, edit.handle, `${field.label} has no ${ctx.locale}`);
|
|
894
|
+
continue;
|
|
895
|
+
}
|
|
896
|
+
const coerced = coerce(field, edit.value);
|
|
897
|
+
if ('code' in coerced) {
|
|
898
|
+
issue(coerced.code, edit.handle, `${field.label}: ${coerced.message}`);
|
|
899
|
+
continue;
|
|
900
|
+
}
|
|
901
|
+
const p = plan(field, edit.handle, values, coerced, ctx.locale);
|
|
902
|
+
if (p)
|
|
903
|
+
planned.push(p);
|
|
904
|
+
}
|
|
905
|
+
if (issues.length)
|
|
906
|
+
return { ok: false, result: { ...values }, changes: [], kept: [], issues };
|
|
907
|
+
const edited = names(ctx.ownerEdited, fields);
|
|
908
|
+
const named = names(ctx.named ?? fieldsNamedIn(ctx.sentence ?? '', fields), fields);
|
|
909
|
+
const isKept = (p) => edited.has(p.field.key) && !named.has(p.field.key);
|
|
910
|
+
const applied = planned.filter(p => !isKept(p));
|
|
911
|
+
const result = { ...values };
|
|
912
|
+
for (const p of applied)
|
|
913
|
+
result[p.field.key] = p.stored;
|
|
914
|
+
return { ok: true, result, changes: applied.map(p => p.change), kept: planned.filter(isKept).map(p => p.change), issues: [] };
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
/**
|
|
918
|
+
* The turn wire (plan §3d) — what cms-client posts and polls and iox-cms stores and answers, ONE definition both sides
|
|
919
|
+
* import (generation-core `ai-run.ts` is the precedent for generations). A turn is a document on the jobs runner:
|
|
920
|
+
* POST answers 202 `{ turnId }`, the client polls the turn every 750 ms until it is terminal.
|
|
921
|
+
*/
|
|
922
|
+
var AssistTurnStatus;
|
|
923
|
+
(function (AssistTurnStatus) {
|
|
924
|
+
AssistTurnStatus["Queued"] = "queued";
|
|
925
|
+
AssistTurnStatus["Routing"] = "routing";
|
|
926
|
+
AssistTurnStatus["Editing"] = "editing";
|
|
927
|
+
AssistTurnStatus["Done"] = "done";
|
|
928
|
+
AssistTurnStatus["Refused"] = "refused";
|
|
929
|
+
AssistTurnStatus["Failed"] = "failed";
|
|
930
|
+
})(AssistTurnStatus || (AssistTurnStatus = {}));
|
|
931
|
+
const TERMINAL = new Set([AssistTurnStatus.Done, AssistTurnStatus.Refused, AssistTurnStatus.Failed]);
|
|
932
|
+
const isTerminalTurn = (status) => TERMINAL.has(status);
|
|
933
|
+
/** Auto = the step's model from Settings ▸ AI ▸ Models (A-D14). */
|
|
934
|
+
const ASSIST_MODEL_AUTO = 'auto';
|
|
935
|
+
const ASSIST_POLL_MS = 750;
|
|
936
|
+
const MAX_SENTENCE_CHARS = 2000;
|
|
937
|
+
/** A turn's own refusals and failures, beside generation-core's `AiRefusalCode`s (credits, plan, key), which a turn returns as they are. */
|
|
938
|
+
var AssistRefusalCode;
|
|
939
|
+
(function (AssistRefusalCode) {
|
|
940
|
+
/** The turn machinery runs, no model is connected yet. */
|
|
941
|
+
AssistRefusalCode["NotConnected"] = "ai.assistNotConnected";
|
|
942
|
+
/** The turn spent its own credit cap (trap T8) before a call it still needed. */
|
|
943
|
+
AssistRefusalCode["TurnBudget"] = "ai.assistTurnBudget";
|
|
944
|
+
/** The routed families need a permission the person who asked does not hold. */
|
|
945
|
+
AssistRefusalCode["Permission"] = "ai.assistPermission";
|
|
946
|
+
/** A process died during this turn's call more often than one resume allows. */
|
|
947
|
+
AssistRefusalCode["Interrupted"] = "ai.assistInterrupted";
|
|
948
|
+
/** The provider call threw — the turn ends; the owner may ask again. */
|
|
949
|
+
AssistRefusalCode["CallFailed"] = "ai.assistCallFailed";
|
|
950
|
+
/** The model's answer broke the check twice (the first time it was re-asked with the issues). */
|
|
951
|
+
AssistRefusalCode["InvalidAnswer"] = "ai.assistInvalidAnswer";
|
|
952
|
+
/** The chosen model is not on the vetted list for this step, and the turn runs on IOX credits. */
|
|
953
|
+
AssistRefusalCode["ModelNotOffered"] = "ai.assistModelNotOffered";
|
|
954
|
+
/** The chosen model cannot do the step (on the studio's own key any model may be typed; this one lacks a need). */
|
|
955
|
+
AssistRefusalCode["ModelDeclined"] = "ai.assistModelDeclined";
|
|
956
|
+
})(AssistRefusalCode || (AssistRefusalCode = {}));
|
|
957
|
+
var AssistRouteKey;
|
|
958
|
+
(function (AssistRouteKey) {
|
|
959
|
+
AssistRouteKey["Turns"] = "turns";
|
|
960
|
+
AssistRouteKey["Turn"] = "turn";
|
|
961
|
+
AssistRouteKey["Session"] = "session";
|
|
962
|
+
})(AssistRouteKey || (AssistRouteKey = {}));
|
|
963
|
+
/** The path templates, `:param` filled by `assistPath` — neither side hand-types a URL. */
|
|
964
|
+
const ASSIST_ROUTES = {
|
|
965
|
+
[AssistRouteKey.Turns]: 'admin/api/org/:orgId/ai/assist/turns',
|
|
966
|
+
[AssistRouteKey.Turn]: 'admin/api/org/:orgId/ai/assist/turns/:turnId',
|
|
967
|
+
[AssistRouteKey.Session]: 'admin/api/org/:orgId/ai/assist/sessions/:sessionKey',
|
|
968
|
+
};
|
|
969
|
+
class AssistPathError extends Error {
|
|
970
|
+
}
|
|
971
|
+
/** A route with its params filled, each URL-encoded; a missing param throws. */
|
|
972
|
+
function assistPath(route, params) {
|
|
973
|
+
return ASSIST_ROUTES[route].replace(/:([A-Za-z]+)/g, (_, name) => {
|
|
974
|
+
const value = params[name];
|
|
975
|
+
if (!value)
|
|
976
|
+
throw new AssistPathError(`${route}: no ${name}`);
|
|
977
|
+
return encodeURIComponent(value);
|
|
978
|
+
});
|
|
979
|
+
}
|
|
980
|
+
const SESSION_TARGET_KEYS = {
|
|
981
|
+
[AssistSurface.BuilderPage]: ['pageId'],
|
|
982
|
+
[AssistSurface.ContentItem]: ['contentType', 'itemId'],
|
|
983
|
+
[AssistSurface.ContentFromPhotos]: ['contentType'],
|
|
984
|
+
[AssistSurface.ContentList]: ['contentType'],
|
|
985
|
+
[AssistSurface.SchemaType]: ['contentType'],
|
|
986
|
+
[AssistSurface.ShopProduct]: ['itemId'],
|
|
987
|
+
[AssistSurface.Media]: [],
|
|
988
|
+
[AssistSurface.BuilderSite]: [],
|
|
989
|
+
[AssistSurface.FormInbox]: ['submissionId'],
|
|
990
|
+
};
|
|
991
|
+
/** A target not saved yet. */
|
|
992
|
+
const NEW_TARGET = 'new';
|
|
993
|
+
const SESSION_SEPARATOR = ':';
|
|
994
|
+
/** `contentItem:projects:<itemId|new>` — each part encoded, so a value never carries the separator. */
|
|
995
|
+
function assistSessionKey(surface, target = {}) {
|
|
996
|
+
const parts = SESSION_TARGET_KEYS[surface].map(k => encodeURIComponent(target[k] || NEW_TARGET));
|
|
997
|
+
return [surface, ...parts].join(SESSION_SEPARATOR);
|
|
998
|
+
}
|
|
999
|
+
const SENTENCE_IN_MEMORY_CHARS = 80;
|
|
1000
|
+
function outcome(turn) {
|
|
1001
|
+
const named = (list) => (list ?? []).map(c => (c.locale ? `${c.label} (${c.locale})` : c.label)).join(', ');
|
|
1002
|
+
switch (turn.status) {
|
|
1003
|
+
case AssistTurnStatus.Refused: return `refused: ${turn.refusal?.message ?? ''}`.trim();
|
|
1004
|
+
case AssistTurnStatus.Failed: return 'failed';
|
|
1005
|
+
case AssistTurnStatus.Done: {
|
|
1006
|
+
const changed = named(turn.changes);
|
|
1007
|
+
const kept = named(turn.kept);
|
|
1008
|
+
const head = changed ? `changed ${changed}` : `no change${turn.reply ? `: ${turn.reply}` : ''}`;
|
|
1009
|
+
return kept ? `${head}; kept ${kept} (the owner edited it)` : head;
|
|
1010
|
+
}
|
|
1011
|
+
default: return turn.status;
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
/** One line the next turn reads as memory — never a tree, a record or a value. */
|
|
1015
|
+
function memoryLine(turn) {
|
|
1016
|
+
const asked = clipText(turn.sentence.replace(/\s+/g, ' ').trim(), SENTENCE_IN_MEMORY_CHARS);
|
|
1017
|
+
return { turnId: turn.id, createdAt: turn.createdAt, line: clipText(`"${asked}" → ${outcome(turn)}`, AROUND_TEXT_CHARS) };
|
|
1018
|
+
}
|
|
1019
|
+
/** A session's answer from its stored turns (those of another session are ignored). */
|
|
1020
|
+
function assistSession(sessionKey, turns) {
|
|
1021
|
+
return { sessionKey, lines: sessionMemory(turns.filter(t => t.sessionKey === sessionKey)) };
|
|
1022
|
+
}
|
|
1023
|
+
/** A session's memory: its last `MEMORY_TURNS` finished turns, oldest first. */
|
|
1024
|
+
function sessionMemory(turns) {
|
|
1025
|
+
return turns
|
|
1026
|
+
.filter(t => isTerminalTurn(t.status))
|
|
1027
|
+
.slice()
|
|
1028
|
+
.sort((a, b) => a.createdAt.localeCompare(b.createdAt))
|
|
1029
|
+
.slice(-MEMORY_TURNS)
|
|
1030
|
+
.map(memoryLine);
|
|
1031
|
+
}
|
|
1032
|
+
const isObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
|
|
1033
|
+
const nonEmpty = (v) => typeof v === 'string' && v.trim() !== '';
|
|
1034
|
+
/** Absent, or a list of non-empty field keys. */
|
|
1035
|
+
const isOwnerEdited = (v) => v === undefined || (Array.isArray(v) && v.every(nonEmpty));
|
|
1036
|
+
/** A key `assistSessionKey` made for this surface. */
|
|
1037
|
+
const isSessionOf = (key, surface) => nonEmpty(key) && (key === surface || key.startsWith(`${surface}${SESSION_SEPARATOR}`));
|
|
1038
|
+
/** What the server refuses in a posted turn before anything runs. Empty = accepted. */
|
|
1039
|
+
function validateTurnRequest(req) {
|
|
1040
|
+
const issue = (code, message) => ({ code, message });
|
|
1041
|
+
if (!isObject(req))
|
|
1042
|
+
return [issue(AssistIssueCode.BadRequest, 'a turn is an object')];
|
|
1043
|
+
const surface = req['surface'];
|
|
1044
|
+
const spec = Object.prototype.hasOwnProperty.call(SURFACES, surface) ? SURFACES[surface] : undefined;
|
|
1045
|
+
if (!spec)
|
|
1046
|
+
return [issue(AssistIssueCode.UnknownSurface, `"${String(surface)}" is not a surface`)];
|
|
1047
|
+
const sentence = req['sentence'];
|
|
1048
|
+
const brief = req['brief'];
|
|
1049
|
+
return [
|
|
1050
|
+
...(spec.status !== SurfaceStatus.Built ? [issue(AssistIssueCode.SurfaceNotBuilt, `${surface} is not built yet`)] : []),
|
|
1051
|
+
...(!isSessionOf(req['sessionKey'], surface) ? [issue(AssistIssueCode.BadRequest, `the session key is not a ${surface} session`)] : []),
|
|
1052
|
+
...(!nonEmpty(sentence) ? [issue(AssistIssueCode.EmptySentence, 'the sentence is empty')] : []),
|
|
1053
|
+
...(nonEmpty(sentence) && sentence.length > MAX_SENTENCE_CHARS ? [issue(AssistIssueCode.SentenceTooLong, `the sentence is over ${MAX_SENTENCE_CHARS} characters`)] : []),
|
|
1054
|
+
...(!nonEmpty(req['model']) ? [issue(AssistIssueCode.BadRequest, 'no model choice (auto or a model id)')] : []),
|
|
1055
|
+
...(!isObject(brief) || brief['surface'] !== surface ? [issue(AssistIssueCode.BadRequest, `the brief is not a ${surface} brief`)] : []),
|
|
1056
|
+
...(!isObject(req['handles']) || !Object.keys(req['handles']).length ? [issue(AssistIssueCode.MissingHandles, 'the brief\'s handles are missing')] : []),
|
|
1057
|
+
...(spec.commit === CommitKind.FormFill && !isObject(req['values']) ? [issue(AssistIssueCode.MissingValues, 'a form-fill turn carries the form\'s values')] : []),
|
|
1058
|
+
...(!isOwnerEdited(req['ownerEdited']) ? [issue(AssistIssueCode.BadRequest, 'ownerEdited is a list of field keys')] : []),
|
|
1059
|
+
...(spec.perContentType && !nonEmpty(req['contentType']) ? [issue(AssistIssueCode.BadRequest, `${surface} names its content type`)] : []),
|
|
1060
|
+
];
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
/**
|
|
1064
|
+
* The ONE locale a content-item turn writes in (plan §3c rule 8, trap T5) — decided the same way by the server and the
|
|
1065
|
+
* client: a multiLang field gets this key and no other. The sentence decides when it names a language ("translate the
|
|
1066
|
+
* summary to English", "תרגם לאנגלית") — matched against the runtime's own language names (`Intl.DisplayNames`) in the
|
|
1067
|
+
* languages the admin speaks, never a hand-kept list; the last one named wins. Otherwise the item's own language: the
|
|
1068
|
+
* locale most of its multiLang fields are filled in (schema order breaks a tie); else the admin's; else the first.
|
|
1069
|
+
*/
|
|
1070
|
+
/** The languages whose names a sentence may use — the admin's two UI languages. */
|
|
1071
|
+
const LOCALE_NAME_LANGUAGES = ['en', 'he'];
|
|
1072
|
+
const DISPLAY_TYPE_LANGUAGE = 'language';
|
|
1073
|
+
/** Every locale the type's multiLang fields hold, in schema order. */
|
|
1074
|
+
function itemLocales(fields) {
|
|
1075
|
+
return [...new Set(fields.flatMap(f => f.locales ?? []))];
|
|
1076
|
+
}
|
|
1077
|
+
function displayName(locale, inLanguage) {
|
|
1078
|
+
try {
|
|
1079
|
+
const name = new Intl.DisplayNames([inLanguage], { type: DISPLAY_TYPE_LANGUAGE }).of(locale);
|
|
1080
|
+
return name && name !== locale ? name : null;
|
|
1081
|
+
}
|
|
1082
|
+
catch {
|
|
1083
|
+
return null;
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
function languageNames(locale, languages) {
|
|
1087
|
+
return languages.flatMap(lang => {
|
|
1088
|
+
const name = displayName(locale, lang);
|
|
1089
|
+
return name ? [name.toLowerCase()] : [];
|
|
1090
|
+
});
|
|
1091
|
+
}
|
|
1092
|
+
/** The last position a locale's name appears at in the sentence, or -1. */
|
|
1093
|
+
function lastMention(sentence, locale, languages) {
|
|
1094
|
+
const s = sentence.toLowerCase();
|
|
1095
|
+
return Math.max(-1, ...languageNames(locale, languages).map(n => s.lastIndexOf(n)));
|
|
1096
|
+
}
|
|
1097
|
+
/** The locale the sentence names; the last one named wins ("the Hebrew summary to English" → en). */
|
|
1098
|
+
function namedLocale(sentence, locales, languages = LOCALE_NAME_LANGUAGES) {
|
|
1099
|
+
const named = locales
|
|
1100
|
+
.map(locale => ({ locale, at: lastMention(sentence, locale, languages) }))
|
|
1101
|
+
.filter(m => m.at >= 0)
|
|
1102
|
+
.sort((a, b) => b.at - a.at);
|
|
1103
|
+
return named[0]?.locale ?? null;
|
|
1104
|
+
}
|
|
1105
|
+
/** The locale most of the item's multiLang fields are filled in (schema order breaks a tie); else the UI's; else the first. */
|
|
1106
|
+
function primaryLocale(fields, values, uiLang) {
|
|
1107
|
+
const locales = itemLocales(fields);
|
|
1108
|
+
if (!locales.length)
|
|
1109
|
+
return uiLang;
|
|
1110
|
+
const filled = (locale) => fields.filter(f => {
|
|
1111
|
+
const v = values[f.key];
|
|
1112
|
+
return f.locales?.includes(locale) && isPlainRecord(v) && !isEmptyFieldValue(v[locale]);
|
|
1113
|
+
}).length;
|
|
1114
|
+
const best = locales.reduce((a, b) => (filled(b) > filled(a) ? b : a));
|
|
1115
|
+
if (filled(best) > 0)
|
|
1116
|
+
return best;
|
|
1117
|
+
return locales.includes(uiLang) ? uiLang : locales[0];
|
|
1118
|
+
}
|
|
1119
|
+
/** The write locale of a content-item turn. */
|
|
1120
|
+
function turnLocale(sentence, fields, values, uiLang) {
|
|
1121
|
+
return namedLocale(sentence, itemLocales(fields)) ?? primaryLocale(fields, values, uiLang);
|
|
1122
|
+
}
|
|
1123
|
+
/** The language's own name in the admin's language (`en` → "English" / "אנגלית"). */
|
|
1124
|
+
const languageName = (locale, uiLang) => displayName(locale, uiLang) ?? locale;
|
|
1125
|
+
|
|
1126
|
+
/**
|
|
1127
|
+
* @vectoriox/iox-ui/assist-core — the shared, FRAMEWORK-FREE vocabulary of AI Assist (iox-ai-guidance
|
|
1128
|
+
* `architecture/ai/ai-assist-plan.md` §3b): the surfaces and their specs, the brief and its handle map, the route
|
|
1129
|
+
* request, and family `fields` for surface S2 (one content item) — its brief (`summarizeItem`), its strict output format
|
|
1130
|
+
* (`fieldsJsonSchema`) and the ONE check that applies an answer (`applyFieldEdits`), run by iox-cms on a copy and by
|
|
1131
|
+
* cms-client as the trial. Pure: no transport, no clock, no randomness.
|
|
1132
|
+
* ⚠️ Not re-exported from the main entry. Consumers wire the usual trio — ng-package raw-ts assets, jest
|
|
1133
|
+
* moduleNameMapper, tsconfig paths — or `nest start` dies with ERR_REQUIRE_ESM. It imports generation-core (the strict
|
|
1134
|
+
* schema builders and budget), so a consumer maps both.
|
|
1135
|
+
* TODO(after the 2026-11-19 demo): extract the fact gate `factIssues` out of generation-core's `planWordIssues` into
|
|
1136
|
+
* this entry (plan §3b, R-H2) — `planWordIssues` becomes its caller; deferred because it edits generation-core.
|
|
1137
|
+
*/
|
|
1138
|
+
|
|
1139
|
+
/**
|
|
1140
|
+
* Generated bundle index. Do not edit.
|
|
1141
|
+
*/
|
|
1142
|
+
|
|
1143
|
+
export { AROUND_ITEMS_MAX, AROUND_TEXT_CHARS, ASSIST_MODEL_AUTO, ASSIST_POLL_MS, ASSIST_ROUTES, AssistBriefError, AssistBudgetError, AssistFieldKind, AssistIssueCode, AssistPathError, AssistPermission, AssistRefusalCode, AssistRouteKey, AssistScope, AssistStep, AssistSurface, AssistTurnStatus, BOOLEAN_FALSE, BOOLEAN_TRUE, CommitKind, EditFamily, FIELDS_PER_PART, FIELD_HANDLE_PREFIX, FieldsAnswerKey, ItemSuggestionKind, LOCALE_NAME_LANGUAGES, MAX_ASSIST_PROPERTIES, MAX_ROUTE_PROPERTIES, MAX_SENTENCE_CHARS, MEMORY_TURNS, NEW_TARGET, NONE_TEXT, NeverWriteReason, RouteAnswerKey, SHORTEN_FROM_CHARS, SIBLING_HANDLE_PREFIX, SURFACES, SurfaceStatus, applyFieldEdits, assertAssistBudget, assistBudgetIssues, assistFields, assistPath, assistSession, assistSessionKey, builtSurfaces, clipText, commitOf, containsHtml, decodeFieldsAnswers, fieldHandle, fieldsJsonSchema, fieldsNamedIn, isEmptyFieldValue, isPlainRecord, isSessionOf, isTerminalTurn, isWritable, itemLocales, itemSuggestions, languageName, memoryLine, namedLocale, paragraphsToRichText, primaryLocale, readFieldValue, readLocaleValues, readRoute, resolveHandle, richTextParagraphs, routeJsonSchema, sessionMemory, summarizeItem, surfacePermissions, surfaceSpec, titleField, turnLocale, unknownHandles, validateTurnRequest };
|
|
1144
|
+
//# sourceMappingURL=vectoriox-iox-ui-assist-core.mjs.map
|