@widgetic/editor 4.1.18 → 4.1.19

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 (93) hide show
  1. package/dist/components/WidgetPreview.svelte +77 -14
  2. package/dist/components/editors/CompositionEditorApp.svelte +71 -35
  3. package/dist/components/editors/CompositionEditorApp.svelte.d.ts +3 -1
  4. package/dist/components/editors/ContentTabBulkDrop.svelte +268 -0
  5. package/dist/components/editors/ContentTabBulkDrop.svelte.d.ts +37 -0
  6. package/dist/components/editors/EmbedAssistantPanel.svelte +303 -0
  7. package/dist/components/editors/EmbedAssistantPanel.svelte.d.ts +29 -0
  8. package/dist/components/editors/EmbedEditor.svelte +221 -15
  9. package/dist/components/editors/EmbedEditor.svelte.d.ts +31 -3
  10. package/dist/components/editors/PropsEditor.svelte +223 -30
  11. package/dist/components/editors/PropsEditor.svelte.d.ts +11 -0
  12. package/dist/components/editors/propsEditorContentStateFlatten.d.ts +12 -0
  13. package/dist/components/editors/propsEditorContentStateFlatten.js +40 -0
  14. package/dist/components/ic/BrowserInputController.svelte +184 -21
  15. package/dist/components/ic/BrowserInputController.svelte.d.ts +2 -0
  16. package/dist/components/ic/CheckboxInputController.svelte +11 -0
  17. package/dist/components/ic/ColorPickerInputController.svelte +2 -1
  18. package/dist/components/ic/DatePickerInputController.svelte +5 -3
  19. package/dist/components/ic/FontInputController.svelte +9 -4
  20. package/dist/components/ic/InputControllerHeader.svelte +4 -3
  21. package/dist/components/ic/KnowledgeDocumentsInputController.svelte +13 -0
  22. package/dist/components/ic/NumberControls.svelte +140 -17
  23. package/dist/components/ic/RadioGroupInputController.svelte +11 -0
  24. package/dist/components/ic/RangeCalendarInputController.svelte +38 -13
  25. package/dist/components/ic/TextAreaInputController.svelte +593 -321
  26. package/dist/components/ic/TextAreaPreviewInputController.svelte +46 -58
  27. package/dist/components/ic/VectorInputController.svelte +0 -1
  28. package/dist/components/ic/numberControlsValueArea.d.ts +29 -0
  29. package/dist/components/ic/numberControlsValueArea.js +51 -0
  30. package/dist/components/ic/optionGroupCardPointerDown.d.ts +9 -0
  31. package/dist/components/ic/optionGroupCardPointerDown.js +20 -0
  32. package/dist/components/ic/shared/EditorFileBrowserOverlay.svelte +48 -6
  33. package/dist/components/ic/shared/EditorFileBrowserOverlay.svelte.d.ts +4 -1
  34. package/dist/components/ic/shared/EditorSelectedFilePreviewOverlay.svelte +34 -0
  35. package/dist/components/ic/shared/EditorSelectedFilePreviewOverlay.svelte.d.ts +24 -0
  36. package/dist/components/ic/shared/fileBrowserOverlayEscape.d.ts +29 -0
  37. package/dist/components/ic/shared/fileBrowserOverlayEscape.js +21 -0
  38. package/dist/composition/compositionApi.d.ts +16 -0
  39. package/dist/composition/compositionApi.js +16 -1
  40. package/dist/composition/compositionEditorController.d.ts +46 -0
  41. package/dist/composition/compositionEditorController.js +277 -5
  42. package/dist/composition/compositionEditorSchemaCache.d.ts +35 -0
  43. package/dist/composition/compositionEditorSchemaCache.js +82 -0
  44. package/dist/contentBulkDrop/applyContentPlan.d.ts +18 -0
  45. package/dist/contentBulkDrop/applyContentPlan.js +55 -0
  46. package/dist/contentBulkDrop/bulkDropSummary.d.ts +4 -0
  47. package/dist/contentBulkDrop/bulkDropSummary.js +12 -0
  48. package/dist/contentBulkDrop/dragIntent.d.ts +7 -0
  49. package/dist/contentBulkDrop/dragIntent.js +24 -0
  50. package/dist/contentBulkDrop/filterDropFiles.d.ts +2 -0
  51. package/dist/contentBulkDrop/filterDropFiles.js +21 -0
  52. package/dist/contentBulkDrop/formatFileSize.d.ts +2 -0
  53. package/dist/contentBulkDrop/formatFileSize.js +13 -0
  54. package/dist/contentBulkDrop/types.d.ts +34 -0
  55. package/dist/contentBulkDrop/types.js +1 -0
  56. package/dist/contentBulkDrop/uploadQueue.d.ts +41 -0
  57. package/dist/contentBulkDrop/uploadQueue.js +114 -0
  58. package/dist/drafts/compositionDraft.d.ts +65 -0
  59. package/dist/drafts/compositionDraft.js +136 -0
  60. package/dist/drafts/compositionEditorViewState.d.ts +9 -0
  61. package/dist/drafts/compositionEditorViewState.js +33 -0
  62. package/dist/drafts/draftJournal.d.ts +59 -0
  63. package/dist/drafts/draftJournal.js +261 -0
  64. package/dist/embed/__fixtures__/gatewayGeneratedEmbedCodes.json +25 -0
  65. package/dist/embed/__fixtures__/generatedEmbedCodes.json +320 -0
  66. package/dist/embed/parseCompositionEmbedCode.d.ts +21 -0
  67. package/dist/embed/parseCompositionEmbedCode.js +376 -0
  68. package/dist/embedAssistant/embedAssistantEvents.d.ts +22 -0
  69. package/dist/embedAssistant/embedAssistantEvents.js +39 -0
  70. package/dist/embedAssistant/embedAssistantStream.d.ts +30 -0
  71. package/dist/embedAssistant/embedAssistantStream.js +125 -0
  72. package/dist/embedAssistant/highlightTiming.d.ts +1 -0
  73. package/dist/embedAssistant/highlightTiming.js +6 -0
  74. package/dist/embedAssistant/types.d.ts +27 -0
  75. package/dist/embedAssistant/types.js +1 -0
  76. package/dist/i18n/labels.js +8 -4
  77. package/dist/i18n/language.d.ts +38 -2
  78. package/dist/i18n/messages.d.ts +38 -1
  79. package/dist/i18n/messages.js +40 -1
  80. package/dist/i18n/translate.d.ts +1 -1
  81. package/dist/index.d.ts +3 -1
  82. package/dist/index.js +2 -0
  83. package/dist/utils/FontManager.d.ts +2 -0
  84. package/dist/utils/FontManager.js +16 -1
  85. package/dist/utils/isEditableEventTarget.d.ts +5 -0
  86. package/dist/utils/isEditableEventTarget.js +25 -0
  87. package/dist/utils/linkUrlValidation.d.ts +17 -0
  88. package/dist/utils/linkUrlValidation.js +120 -0
  89. package/dist/utils/mediaFileValue.d.ts +12 -0
  90. package/dist/utils/mediaFileValue.js +24 -0
  91. package/dist/utils/placeRichTextCaretAtDocumentEnd.d.ts +11 -0
  92. package/dist/utils/placeRichTextCaretAtDocumentEnd.js +26 -0
  93. package/package.json +6 -6
@@ -0,0 +1,376 @@
1
+ /**
2
+ * Parses a paste-ready Widgetic composition embed snippet into embed editor settings.
3
+ * Accepts only output from the site `generateCompositionEmbedCode` and the gateway HTML embed generator.
4
+ */
5
+ import embedSchemaFile from '../../../static/embed-schema.json';
6
+ const MAX_INPUT_LENGTH = 20_000;
7
+ const ALLOWED_SDK_HOST = 'cdn.widgetic.com';
8
+ const SDK_PATH_SUFFIX = '/sdks/browser/embed-sdk.js';
9
+ const EMBED_FRAME_PATH_PATTERN = /\/embed\/compositions\/([^/"'?]+)\/frame(?:[/?#]|$)/i;
10
+ const CDN_COMPOSITION_PATH_PATTERN = /\/composition\/([^/"'?]+)(?:[/?#]|$)/i;
11
+ /** Hostnames the HTML and iframe embed emitters use (api.widgetic.com, cdn.widgetic.com, …). */
12
+ function isWidgeticHostname(hostname) {
13
+ const host = hostname.toLowerCase();
14
+ if (!host || host.includes('@'))
15
+ return false;
16
+ if (host === 'widgetic.com')
17
+ return true;
18
+ if (!host.endsWith('.widgetic.com'))
19
+ return false;
20
+ // Reject lookalikes such as widgetic.com.evil.test (they do not end with .widgetic.com).
21
+ return !host.slice(0, -'.widgetic.com'.length).includes('.');
22
+ }
23
+ function isAllowedEmbedFrameUrl(source) {
24
+ try {
25
+ const url = new URL(source);
26
+ if (url.protocol !== 'https:')
27
+ return false;
28
+ if (url.username || url.password)
29
+ return false;
30
+ if (url.port && url.port !== '443')
31
+ return false;
32
+ if (!isWidgeticHostname(url.hostname))
33
+ return false;
34
+ if (EMBED_FRAME_PATH_PATTERN.test(`${url.pathname}${url.search}`))
35
+ return true;
36
+ if (url.hostname === ALLOWED_SDK_HOST && CDN_COMPOSITION_PATH_PATTERN.test(url.pathname))
37
+ return true;
38
+ return false;
39
+ }
40
+ catch {
41
+ return false;
42
+ }
43
+ }
44
+ function compositionIdFromIframeSrc(source) {
45
+ try {
46
+ const url = new URL(source);
47
+ const frameMatch = EMBED_FRAME_PATH_PATTERN.exec(url.pathname);
48
+ if (frameMatch?.[1])
49
+ return decodeURIComponent(frameMatch[1]);
50
+ const cdnMatch = CDN_COMPOSITION_PATH_PATTERN.exec(url.pathname);
51
+ if (cdnMatch?.[1])
52
+ return decodeURIComponent(cdnMatch[1]);
53
+ }
54
+ catch {
55
+ return '';
56
+ }
57
+ return '';
58
+ }
59
+ /** Attributes the editor schema knows how to apply (whitelist). */
60
+ const KNOWN_WIDGETIC_ATTRIBUTES = new Set([
61
+ 'composition-id',
62
+ 'id',
63
+ 'resize',
64
+ 'width',
65
+ 'height',
66
+ 'autoscale',
67
+ 'adaptive',
68
+ 'embed-target',
69
+ 'overlay',
70
+ 'overlay-position',
71
+ 'event-trigger',
72
+ 'overlay-backdrop',
73
+ 'overlay-background-color',
74
+ 'overlay-background-opacity',
75
+ 'keep-dimensions',
76
+ 'overlay-resize-mode',
77
+ 'overlay-width',
78
+ 'overlay-height',
79
+ 'device-mobile-enabled',
80
+ 'device-desktop-enabled',
81
+ 'max-views',
82
+ 'time-period',
83
+ 'render-mode',
84
+ 'display-mode',
85
+ 'style',
86
+ 'class',
87
+ ]);
88
+ const RESIZE_ATTRIBUTE_TO_MODE = {
89
+ 'fill-width': 'fillWidth',
90
+ fixed: 'fixed',
91
+ responsive: 'responsive',
92
+ custom: 'custom',
93
+ };
94
+ const GRID_POSITIONS = [
95
+ 'top-left',
96
+ 'top-center',
97
+ 'top-right',
98
+ 'center-left',
99
+ 'center-center',
100
+ 'center-right',
101
+ 'bottom-left',
102
+ 'bottom-center',
103
+ 'bottom-right',
104
+ ];
105
+ const OVERLAY_RESIZE_MODES = new Set([
106
+ 'fillWidth',
107
+ 'fillHeight',
108
+ 'fixedSize',
109
+ 'fixedHeight',
110
+ 'fixedWidth',
111
+ 'allowScaleDown',
112
+ 'fill',
113
+ ]);
114
+ function listSchemaProperties() {
115
+ const result = [];
116
+ const groups = embedSchemaFile?.componentGroups;
117
+ if (!Array.isArray(groups))
118
+ return result;
119
+ for (const group of groups) {
120
+ for (const component of group?.components ?? []) {
121
+ for (const propertyGroup of component?.propertyGroups ?? []) {
122
+ for (const property of propertyGroup?.properties ?? []) {
123
+ const propertyRecord = property;
124
+ const name = (propertyRecord.name ?? propertyRecord.id);
125
+ if (!name)
126
+ continue;
127
+ const controller = (propertyRecord.inputController ?? {});
128
+ const options = controller.options;
129
+ result.push({
130
+ name,
131
+ type: String(propertyRecord.type ?? 'string'),
132
+ label: String(controller.description ?? name),
133
+ enumValues: Array.isArray(options)
134
+ ? options.map((option) => String(option?.value ?? ''))
135
+ : undefined,
136
+ });
137
+ }
138
+ }
139
+ }
140
+ }
141
+ return result;
142
+ }
143
+ const SCHEMA_PROPERTIES = listSchemaProperties();
144
+ const SCHEMA_BY_NAME = new Map(SCHEMA_PROPERTIES.map((property) => [property.name, property]));
145
+ function gridPosition(value) {
146
+ const key = value.trim();
147
+ if (GRID_POSITIONS.includes(key))
148
+ return key;
149
+ const edgeToGrid = {
150
+ top: 'top-center',
151
+ bottom: 'bottom-center',
152
+ left: 'center-left',
153
+ right: 'center-right',
154
+ center: 'center-center',
155
+ };
156
+ return edgeToGrid[key] ?? 'center-center';
157
+ }
158
+ function readAttributes(tagInner) {
159
+ const attributes = {};
160
+ for (const match of tagInner.matchAll(/([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/gi)) {
161
+ const value = match[2] ?? match[3] ?? '';
162
+ attributes[match[1].toLowerCase()] = value;
163
+ }
164
+ return attributes;
165
+ }
166
+ function readInteger(text) {
167
+ if (text === undefined)
168
+ return undefined;
169
+ const number = Number.parseInt(text, 10);
170
+ return Number.isFinite(number) ? number : undefined;
171
+ }
172
+ function readFlag(text) {
173
+ return text === undefined ? undefined : text === 'true';
174
+ }
175
+ function scriptSrcIsAllowed(source) {
176
+ try {
177
+ const url = new URL(source, 'https://cdn.widgetic.com');
178
+ if (url.hostname !== ALLOWED_SDK_HOST)
179
+ return false;
180
+ return url.pathname.endsWith(SDK_PATH_SUFFIX) || url.pathname === SDK_PATH_SUFFIX;
181
+ }
182
+ catch {
183
+ return false;
184
+ }
185
+ }
186
+ function containsDisallowedMarkup(text) {
187
+ if (/\bon\w+\s*=/i.test(text))
188
+ return true;
189
+ if (/javascript:/i.test(text))
190
+ return true;
191
+ return false;
192
+ }
193
+ function validateWidgeticEmbedShape(text) {
194
+ const trimmed = text.trim();
195
+ if (!trimmed)
196
+ return false;
197
+ const iframeMatch = /<iframe\b/i.test(trimmed);
198
+ const widgetTagCount = (trimmed.match(/<widgetic\b/gi) ?? []).length;
199
+ const widgetMatch = widgetTagCount > 0;
200
+ if (!iframeMatch && !widgetMatch)
201
+ return false;
202
+ if (widgetTagCount > 1)
203
+ return false;
204
+ if (containsDisallowedMarkup(trimmed))
205
+ return false;
206
+ const scriptTags = [...trimmed.matchAll(/<script\b([^>]*)>/gi)];
207
+ if (widgetMatch) {
208
+ if (scriptTags.length !== 1)
209
+ return false;
210
+ const attributes = readAttributes(scriptTags[0]?.[1] ?? '');
211
+ const source = attributes.src;
212
+ if (!source || !scriptSrcIsAllowed(source))
213
+ return false;
214
+ }
215
+ if (iframeMatch && !widgetMatch) {
216
+ const iframeTag = /<iframe\b([^>]*)>/i.exec(trimmed);
217
+ const src = readAttributes(iframeTag?.[1] ?? '')?.src ?? '';
218
+ if (!isAllowedEmbedFrameUrl(src))
219
+ return false;
220
+ return true;
221
+ }
222
+ // Reject lookalike hosts embedded in script src strings (e.g. widgetic.com.evil.test).
223
+ for (const scriptTag of scriptTags) {
224
+ const source = readAttributes(scriptTag[1] ?? '').src ?? '';
225
+ if (/widgetic\.com\.[^/]+/i.test(source) && !source.includes(`://${ALLOWED_SDK_HOST}/`)) {
226
+ return false;
227
+ }
228
+ }
229
+ return true;
230
+ }
231
+ function coerceSettingValue(name, raw) {
232
+ const definition = SCHEMA_BY_NAME.get(name);
233
+ if (!definition)
234
+ return { ok: false };
235
+ if (definition.type === 'boolean') {
236
+ if (typeof raw === 'boolean')
237
+ return { ok: true, value: raw };
238
+ if (raw === 'true' || raw === true)
239
+ return { ok: true, value: true };
240
+ if (raw === 'false' || raw === false)
241
+ return { ok: true, value: false };
242
+ return { ok: false };
243
+ }
244
+ if (definition.type === 'number') {
245
+ const number = typeof raw === 'number' ? raw : Number(raw);
246
+ if (!Number.isFinite(number))
247
+ return { ok: false };
248
+ return { ok: true, value: number };
249
+ }
250
+ const text = String(raw ?? '');
251
+ if (definition.enumValues?.length) {
252
+ if (!definition.enumValues.includes(text))
253
+ return { ok: false };
254
+ }
255
+ return { ok: true, value: text };
256
+ }
257
+ function humanLabelForAttribute(attributeName) {
258
+ const map = {
259
+ 'scroll-trigger': 'Scroll trigger',
260
+ 'delay-trigger': 'Delay trigger',
261
+ };
262
+ if (map[attributeName])
263
+ return map[attributeName];
264
+ return attributeName;
265
+ }
266
+ function parseWidgeticTagAttributes(attributes) {
267
+ const settings = {};
268
+ const ignored = [];
269
+ const set = (name, value) => {
270
+ if (value === undefined)
271
+ return;
272
+ if (name.endsWith('_opacity')) {
273
+ const number = typeof value === 'number' ? value : Number(value);
274
+ if (Number.isFinite(number))
275
+ settings[name] = number;
276
+ return;
277
+ }
278
+ const coerced = coerceSettingValue(name, value);
279
+ if (coerced.ok)
280
+ settings[name] = coerced.value;
281
+ };
282
+ set('useIframe', false);
283
+ set('resizeMode', RESIZE_ATTRIBUTE_TO_MODE[attributes.resize ?? '']);
284
+ set('width', readInteger(attributes.width));
285
+ set('height', readInteger(attributes.height));
286
+ set('responsive', readInteger(attributes.adaptive));
287
+ set('autoscale', attributes.autoscale === undefined ? undefined : attributes.autoscale !== 'off');
288
+ set('embedTarget', attributes['embed-target']);
289
+ if (attributes['overlay-position']) {
290
+ set('overlayPosition', gridPosition(attributes['overlay-position']));
291
+ }
292
+ set('eventTriggers', attributes['event-trigger'] === undefined
293
+ ? undefined
294
+ : attributes['event-trigger'] === 'page-load'
295
+ ? 'pageLoad'
296
+ : 'exitIntent');
297
+ set('addBackgroundColor', readFlag(attributes['overlay-backdrop']));
298
+ set('overlayBackgroundColor', attributes['overlay-background-color']);
299
+ const opacity = Number(attributes['overlay-background-opacity']);
300
+ set('overlayBackgroundColor_opacity', attributes['overlay-background-opacity'] === undefined || !Number.isFinite(opacity) ? undefined : opacity);
301
+ set('keepDimensions', readFlag(attributes['keep-dimensions']));
302
+ if (attributes['overlay-resize-mode'] && OVERLAY_RESIZE_MODES.has(attributes['overlay-resize-mode'])) {
303
+ set('overlayResizeMode', attributes['overlay-resize-mode']);
304
+ }
305
+ set('overlayWidth', readInteger(attributes['overlay-width']));
306
+ set('overlayHeight', readInteger(attributes['overlay-height']));
307
+ const restrictionNames = ['device-mobile-enabled', 'device-desktop-enabled', 'max-views', 'time-period'];
308
+ set('restrictions', restrictionNames.some((name) => attributes[name] !== undefined));
309
+ set('displayOnMobile', readFlag(attributes['device-mobile-enabled']));
310
+ set('displayOnDesktop', readFlag(attributes['device-desktop-enabled']));
311
+ set('maxViews', readInteger(attributes['max-views']));
312
+ set('timePeriod', readInteger(attributes['time-period']));
313
+ if (attributes['render-mode'] === 'iframe')
314
+ set('useIframe', true);
315
+ for (const [attributeName] of Object.entries(attributes)) {
316
+ if (KNOWN_WIDGETIC_ATTRIBUTES.has(attributeName))
317
+ continue;
318
+ ignored.push(humanLabelForAttribute(attributeName));
319
+ }
320
+ return { settings, ignored };
321
+ }
322
+ /**
323
+ * Parse a Widgetic embed snippet pasted from another composition. The returned composition id is informational only and
324
+ * must never replace the composition being edited.
325
+ */
326
+ export function parseCompositionEmbedCode(text) {
327
+ const trimmed = text?.trim() ?? '';
328
+ if (!trimmed)
329
+ return { ok: false, reason: 'empty' };
330
+ if (trimmed.length > MAX_INPUT_LENGTH)
331
+ return { ok: false, reason: 'too_large' };
332
+ if (!validateWidgeticEmbedShape(trimmed))
333
+ return { ok: false, reason: 'not_widgetic' };
334
+ const widgetTag = /<widgetic\b([^>]*)>/i.exec(trimmed);
335
+ const iframeTag = /<iframe\b([^>]*)>/i.exec(trimmed);
336
+ if (iframeTag && !widgetTag) {
337
+ const attributes = readAttributes(iframeTag[1] ?? '');
338
+ const source = attributes.src ?? '';
339
+ if (!isAllowedEmbedFrameUrl(source))
340
+ return { ok: false, reason: 'not_widgetic' };
341
+ const compositionId = compositionIdFromIframeSrc(source);
342
+ if (!compositionId)
343
+ return { ok: false, reason: 'missing_composition' };
344
+ const { settings, ignored } = parseWidgeticTagAttributes({});
345
+ settings.useIframe = true;
346
+ const width = readInteger(attributes.width);
347
+ const height = readInteger(attributes.height);
348
+ if (width !== undefined)
349
+ settings.width = width;
350
+ if (height !== undefined)
351
+ settings.height = height;
352
+ return { ok: true, compositionId, settings, ignored };
353
+ }
354
+ if (!widgetTag)
355
+ return { ok: false, reason: 'not_widgetic' };
356
+ const attributes = readAttributes(widgetTag[1] ?? '');
357
+ const compositionId = attributes['composition-id'] || attributes.id || '';
358
+ if (!compositionId)
359
+ return { ok: false, reason: 'missing_composition' };
360
+ const { settings, ignored } = parseWidgeticTagAttributes(attributes);
361
+ return { ok: true, compositionId, settings, ignored };
362
+ }
363
+ /** Normalise settings for fixture comparison (sorted keys, finite numbers). */
364
+ export function normalizeParsedEmbedSettings(settings) {
365
+ const normalized = {};
366
+ for (const key of Object.keys(settings).sort()) {
367
+ const value = settings[key];
368
+ if (typeof value === 'number' && Number.isFinite(value)) {
369
+ normalized[key] = value;
370
+ }
371
+ else {
372
+ normalized[key] = value;
373
+ }
374
+ }
375
+ return normalized;
376
+ }
@@ -0,0 +1,22 @@
1
+ import type { EmbedAssistantQuestionCard, EmbedAssistantTranscriptTurn } from './types.js';
2
+ import type { EmbedAssistantUiEvent } from './embedAssistantStream.js';
3
+ export interface EmbedAssistantUiState {
4
+ readonly messages: EmbedAssistantTranscriptTurn[];
5
+ readonly isStreaming: boolean;
6
+ readonly pendingQuestion: EmbedAssistantQuestionCard | null;
7
+ readonly showCopyPrimary: boolean;
8
+ readonly lastError: string | null;
9
+ }
10
+ export declare const emptyEmbedAssistantUiState: EmbedAssistantUiState;
11
+ export type EmbedAssistantUiAction = EmbedAssistantUiEvent | {
12
+ type: 'user_message';
13
+ id: string;
14
+ text: string;
15
+ } | {
16
+ type: 'reset';
17
+ };
18
+ export declare function reduceEmbedAssistantUiState(state: EmbedAssistantUiState, action: EmbedAssistantUiAction): EmbedAssistantUiState;
19
+ export declare function buildAssistantHistory(messages: readonly EmbedAssistantTranscriptTurn[]): Array<{
20
+ role: 'user' | 'assistant';
21
+ text: string;
22
+ }>;
@@ -0,0 +1,39 @@
1
+ export const emptyEmbedAssistantUiState = {
2
+ messages: [],
3
+ isStreaming: false,
4
+ pendingQuestion: null,
5
+ showCopyPrimary: false,
6
+ lastError: null,
7
+ };
8
+ export function reduceEmbedAssistantUiState(state, action) {
9
+ switch (action.type) {
10
+ case 'user_message':
11
+ return {
12
+ ...state,
13
+ lastError: null,
14
+ messages: [...state.messages, { id: action.id, role: 'user', text: action.text }],
15
+ };
16
+ case 'assistant_text':
17
+ return {
18
+ ...state,
19
+ messages: [...state.messages, { id: action.id, role: 'assistant', text: action.text }],
20
+ };
21
+ case 'question_card':
22
+ return { ...state, pendingQuestion: action.card };
23
+ case 'options_set':
24
+ return state;
25
+ case 'streaming':
26
+ return { ...state, isStreaming: action.value };
27
+ case 'error':
28
+ return { ...state, lastError: action.message };
29
+ case 'done':
30
+ return { ...state, isStreaming: false, pendingQuestion: null, showCopyPrimary: true };
31
+ case 'reset':
32
+ return { ...emptyEmbedAssistantUiState };
33
+ default:
34
+ return state;
35
+ }
36
+ }
37
+ export function buildAssistantHistory(messages) {
38
+ return messages.map((message) => ({ role: message.role, text: message.text }));
39
+ }
@@ -0,0 +1,30 @@
1
+ import type { EmbedAssistantOptionsSetPayload, EmbedAssistantQuestionCard } from './types.js';
2
+ export type EmbedAssistantUiEvent = {
3
+ type: 'assistant_text';
4
+ id: string;
5
+ text: string;
6
+ } | {
7
+ type: 'question_card';
8
+ card: EmbedAssistantQuestionCard;
9
+ } | {
10
+ type: 'options_set';
11
+ payload: EmbedAssistantOptionsSetPayload;
12
+ } | {
13
+ type: 'streaming';
14
+ value: boolean;
15
+ } | {
16
+ type: 'done';
17
+ } | {
18
+ type: 'error';
19
+ message: string;
20
+ };
21
+ export declare const EMBED_ASSISTANT_STREAM_MESSAGES: {
22
+ readonly rateLimit: "Too many messages. Try again shortly.";
23
+ readonly generic: "The assistant could not respond. Try again.";
24
+ };
25
+ /** Parses SSE blocks already in the buffer; leaves an incomplete trailing block in `remainder`. */
26
+ export declare function extractSseJsonPayloadsFromBuffer(buffer: string): {
27
+ payloads: Array<Record<string, unknown>>;
28
+ remainder: string;
29
+ };
30
+ export declare function parseEmbedAssistantSseStream(response: Response, signal?: AbortSignal): AsyncGenerator<EmbedAssistantUiEvent>;
@@ -0,0 +1,125 @@
1
+ import { EDITOR_MESSAGES } from '../i18n/messages.js';
2
+ export const EMBED_ASSISTANT_STREAM_MESSAGES = {
3
+ rateLimit: EDITOR_MESSAGES['editor.embedAssistant.errorRateLimit'],
4
+ generic: EDITOR_MESSAGES['editor.embedAssistant.errorGeneric'],
5
+ };
6
+ /** Parses SSE blocks already in the buffer; leaves an incomplete trailing block in `remainder`. */
7
+ export function extractSseJsonPayloadsFromBuffer(buffer) {
8
+ const normalized = buffer.replace(/\r\n/g, '\n');
9
+ const payloads = [];
10
+ let remainder = normalized;
11
+ while (true) {
12
+ const delimiter = remainder.indexOf('\n\n');
13
+ if (delimiter === -1)
14
+ break;
15
+ const block = remainder.slice(0, delimiter);
16
+ remainder = remainder.slice(delimiter + 2);
17
+ const payload = parseSseBlockToJson(block);
18
+ if (payload)
19
+ payloads.push(payload);
20
+ }
21
+ return { payloads, remainder };
22
+ }
23
+ function parseSseBlockToJson(block) {
24
+ const dataLines = [];
25
+ for (const line of block.split('\n')) {
26
+ if (line.startsWith(':'))
27
+ continue;
28
+ if (line.startsWith('data:')) {
29
+ dataLines.push(line.startsWith('data: ') ? line.slice(6) : line.slice(5).trimStart());
30
+ }
31
+ }
32
+ if (dataLines.length === 0)
33
+ return null;
34
+ try {
35
+ return JSON.parse(dataLines.join('\n'));
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ }
41
+ function* mapEmbedAssistantPayload(payload) {
42
+ switch (payload.type) {
43
+ case 'assistant_message':
44
+ yield {
45
+ type: 'assistant_text',
46
+ id: crypto.randomUUID(),
47
+ text: String(payload.text ?? ''),
48
+ };
49
+ break;
50
+ case 'question_card':
51
+ yield {
52
+ type: 'question_card',
53
+ card: payload.card,
54
+ };
55
+ break;
56
+ case 'options_set':
57
+ yield {
58
+ type: 'options_set',
59
+ payload: {
60
+ options: (payload.options ?? {}),
61
+ changedIds: Array.isArray(payload.changedIds) ? payload.changedIds.map(String) : [],
62
+ summary: String(payload.summary ?? ''),
63
+ },
64
+ };
65
+ break;
66
+ case 'error':
67
+ yield {
68
+ type: 'error',
69
+ message: String(payload.message ?? EMBED_ASSISTANT_STREAM_MESSAGES.generic),
70
+ };
71
+ break;
72
+ case 'done':
73
+ yield { type: 'done' };
74
+ break;
75
+ default:
76
+ break;
77
+ }
78
+ }
79
+ export async function* parseEmbedAssistantSseStream(response, signal) {
80
+ if (response.status === 429) {
81
+ yield { type: 'error', message: EMBED_ASSISTANT_STREAM_MESSAGES.rateLimit };
82
+ yield { type: 'done' };
83
+ return;
84
+ }
85
+ if (!response.ok) {
86
+ yield { type: 'error', message: EMBED_ASSISTANT_STREAM_MESSAGES.generic };
87
+ yield { type: 'done' };
88
+ return;
89
+ }
90
+ const reader = response.body?.getReader();
91
+ if (!reader) {
92
+ yield { type: 'error', message: EMBED_ASSISTANT_STREAM_MESSAGES.generic };
93
+ yield { type: 'done' };
94
+ return;
95
+ }
96
+ const decoder = new TextDecoder();
97
+ let buffer = '';
98
+ try {
99
+ while (true) {
100
+ if (signal?.aborted)
101
+ return;
102
+ const { done, value } = await reader.read();
103
+ if (done)
104
+ break;
105
+ buffer += decoder.decode(value, { stream: true });
106
+ const parsed = extractSseJsonPayloadsFromBuffer(buffer);
107
+ buffer = parsed.remainder;
108
+ for (const payload of parsed.payloads) {
109
+ yield* mapEmbedAssistantPayload(payload);
110
+ }
111
+ }
112
+ const trailing = extractSseJsonPayloadsFromBuffer(`${buffer}\n\n`);
113
+ for (const payload of trailing.payloads) {
114
+ yield* mapEmbedAssistantPayload(payload);
115
+ }
116
+ }
117
+ finally {
118
+ try {
119
+ reader.releaseLock();
120
+ }
121
+ catch {
122
+ /* ignore */
123
+ }
124
+ }
125
+ }
@@ -0,0 +1 @@
1
+ export declare function schedulePropertyHighlights(propertyIds: readonly string[], onFlash: (ids: string[]) => void, onClear: () => void, durationMs?: number): () => void;
@@ -0,0 +1,6 @@
1
+ const DEFAULT_FLASH_MS = 3000;
2
+ export function schedulePropertyHighlights(propertyIds, onFlash, onClear, durationMs = DEFAULT_FLASH_MS) {
3
+ onFlash([...propertyIds]);
4
+ const timer = setTimeout(() => onClear(), durationMs);
5
+ return () => clearTimeout(timer);
6
+ }
@@ -0,0 +1,27 @@
1
+ export interface EmbedAssistantTranscriptTurn {
2
+ readonly role: 'user' | 'assistant';
3
+ readonly text: string;
4
+ readonly id: string;
5
+ }
6
+ export interface EmbedAssistantQuestionOption {
7
+ readonly id: string;
8
+ readonly label: string;
9
+ }
10
+ export interface EmbedAssistantQuestionCard {
11
+ readonly cardId: string;
12
+ readonly question: string;
13
+ readonly options: EmbedAssistantQuestionOption[];
14
+ readonly allowMultiple?: boolean;
15
+ }
16
+ export interface EmbedAssistantWireConfig {
17
+ readonly enabled: boolean;
18
+ readonly streamUrl: string;
19
+ readonly getAuthHeaders: () => Promise<Record<string, string>> | Record<string, string>;
20
+ readonly initialTranscript?: readonly EmbedAssistantTranscriptTurn[];
21
+ readonly onTranscriptChange?: (transcript: EmbedAssistantTranscriptTurn[]) => void;
22
+ }
23
+ export interface EmbedAssistantOptionsSetPayload {
24
+ readonly options: Record<string, unknown>;
25
+ readonly changedIds: string[];
26
+ readonly summary: string;
27
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -1,3 +1,4 @@
1
+ import { normalizeFontWeightName } from '../utils/FontManager.js';
1
2
  /** `own[name]`, only when `name` is the table's own entry (a weight called "constructor" is not a method of the table). */
2
3
  function ownEntry(table, name) {
3
4
  return Object.prototype.hasOwnProperty.call(table, name) ? table[name] : undefined;
@@ -31,12 +32,15 @@ const WEIGHT_KEYS = {
31
32
  };
32
33
  /** A weight of a font, by the name that is saved ("Bold", "Medium Italic", "Italic"). A name the editor does not know is shown as it is. */
33
34
  export function fontWeightLabel(weight, t) {
34
- if (weight === 'Italic')
35
+ if (!weight)
36
+ return weight;
37
+ const named = normalizeFontWeightName(weight);
38
+ if (named === 'Italic')
35
39
  return t('editor.fontWeight.italic');
36
- const italic = /^(\S+) Italic$/.exec(weight);
37
- const baseKey = ownEntry(WEIGHT_KEYS, italic ? italic[1] : weight);
40
+ const italic = /^(\S+) Italic$/.exec(named);
41
+ const baseKey = ownEntry(WEIGHT_KEYS, italic ? italic[1] : named);
38
42
  if (!baseKey)
39
- return weight;
43
+ return named;
40
44
  return italic ? t('editor.fontWeight.withItalic', { weight: t(baseKey) }) : t(baseKey);
41
45
  }
42
46
  const POSITION_KEYS = {