@widgetic/ui-sdk 0.1.2 → 0.1.5

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.
@@ -0,0 +1,1488 @@
1
+ # @widgetic/ui-sdk-modules
2
+
3
+ The heavy UI modules a partner mounts into its own page: the **File Browser**, the **composition editor** and the AI
4
+ **widget creator**. Each module is **one self-contained ES module file** (`dist/<name>/index.js`) that brings its own Svelte,
5
+ design system and CSS, and draws inside a **shadow root**, so the partner's CSS cannot restyle it and its CSS cannot
6
+ touch the partner's page. The only other files are a few **lazy files** next to it (`dist/<name>/chunks/`): pdf.js and
7
+ its worker, which only a visitor who previews a PDF needs (see "One file, and the parts that are not in it").
8
+
9
+ It is a separate workspace so `@widgetic/ui-sdk` (the small loader partners install) stays free of Svelte. The SDK
10
+ loads a module from the CDN; the module talks to the Widgetic API with an **editor session token** that the partner's
11
+ server mints (`POST /v1/managed-users/{id}/editor-sessions`), so the partner's API key never reaches the browser.
12
+
13
+ ## Using the File Browser module
14
+
15
+ Partners load it through `@widgetic/ui-sdk`, which reads `https://cdn.widgetic.com/modules/file-browser/manifest.json`,
16
+ imports the file it names and mounts it (the SDK's README is the reference):
17
+
18
+ ```js
19
+ import { mountModule } from '@widgetic/ui-sdk';
20
+
21
+ const fileBrowser = await mountModule('file-browser', {
22
+ container: '#media',
23
+ // Called when the module starts and again ~60 s before the token expires. Your server mints the session.
24
+ getToken: async ({ reason }) => (await fetch('/my-server/widgetic-editor-session')).json(), // { token, expiresAt }
25
+ theme: 'light',
26
+ maxSelections: 1,
27
+ on: { select: ({ files }) => useFiles(files) }, // [{ id, name, url, mimeType?, size?, thumbnail? }]
28
+ });
29
+ // later: await fileBrowser.unmount();
30
+ ```
31
+
32
+ What the SDK imports is a plain ES module whose default export is the class. This is the same thing without the SDK
33
+ (the version is part of the address; see "Publishing"):
34
+
35
+ ```js
36
+ const { default: FileBrowserModule } = await import('https://cdn.widgetic.com/modules/file-browser/0.1.0/index.js');
37
+ const fileBrowser = new FileBrowserModule(document.querySelector('#media'), {
38
+ apiUrl: 'https://api.widgetic.com',
39
+ getToken: async ({ reason }) => (await fetch('/my-server/widgetic-editor-session')).json(),
40
+ theme: 'light',
41
+ maxSelections: 1,
42
+ });
43
+
44
+ fileBrowser.on('ready', () => console.log('on screen'));
45
+ fileBrowser.on('select', ({ files }) => useFiles(files));
46
+ fileBrowser.on('error', ({ message, code, fatal }) => report(message));
47
+
48
+ await fileBrowser.mount();
49
+ // later: fileBrowser.setTheme('dark'); fileBrowser.unmount();
50
+ ```
51
+
52
+ `getToken` may resolve with the bare token or with `{ token, expiresAt }`; give `expiresAt` and the module replaces the
53
+ token in time, so the visitor is never interrupted. If the API still refuses the token (a session ended early), the
54
+ module asks `getToken({ reason: 'expired' })` once and repeats the request; when that is refused too, the File Browser
55
+ shows the API's message with "Try again" and the module emits a non-fatal `error` with `MEDIA_LIBRARY_UNAUTHORIZED`.
56
+ Only **one File Browser can be mounted per page** for now (see "Known gaps"). Its words can be your visitors' own: pass
57
+ `locale` and `messages` (see "Speaking your visitors' language").
58
+
59
+ ## Showing your own media library
60
+
61
+ A platform that keeps its files itself (a CMS, an S3 bucket, a DAM) passes `mediaLibrary` instead of `getToken`: an object
62
+ with a `list` function and, if visitors may change things, `upload`, `rename` and `delete`. The module never talks to
63
+ Widgetic then, so no session is minted and `getToken` is never called (the SDK does not ask for it either).
64
+
65
+ ```js
66
+ const fileBrowser = await mountModule('file-browser', {
67
+ container: '#media',
68
+ mediaLibrary: {
69
+ id: 'acme-assets',
70
+ label: 'Acme assets',
71
+ list: async ({ cursor, limit, signal }) => {
72
+ const response = await fetch(`/api/assets?cursor=${cursor ?? ''}&limit=${limit}`, { signal });
73
+ if (!response.ok) throw Object.assign(new Error('Could not load your files'), { status: response.status });
74
+ const page = await response.json();
75
+ return { items: page.assets.map((a) => ({ id: a.id, name: a.fileName, url: a.publicUrl, mimeType: a.contentType })), nextCursor: page.next ?? null };
76
+ },
77
+ upload: async ({ file, onProgress, signal }) => uploadToAcme(file, onProgress, signal), // optional
78
+ rename: async ({ id, name, signal }) => renameInAcme(id, name, signal), // optional
79
+ delete: async ({ id, signal }) => deleteInAcme(id, signal), // optional
80
+ // Optional: turn listed urls into stable addresses saved with compositions (see urlResolver below).
81
+ urlResolver: async (file) => `https://cdn.acme.com/assets/${file.id}`,
82
+ },
83
+ on: {
84
+ select: ({ files }) => useFiles(files), // your files, as your library described them
85
+ error: ({ message, code, action, file }) => report(code, action, message),
86
+ },
87
+ });
88
+ ```
89
+
90
+ What the module adds to the File Browser's own contract (the File Browser's README, "Using your own media library",
91
+ has all of it: file fields, paging, limits, what is validated, CORS for previews):
92
+
93
+ - **A flat list.** No folders, breadcrumb, Move or Recent files. The buttons shown are the ones the library can honour:
94
+ Upload needs `upload`, Rename needs `rename`, Delete needs `delete`, and `capabilities: { delete: false }` switches
95
+ one off. Download is always offered.
96
+ - **Failures arrive as `error` events** with `fatal: false` (the File Browser stays up), a code
97
+ of `MEDIA_LIBRARY_` plus `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, `NETWORK`, `INVALID_RESPONSE`, `NOT_SUPPORTED` or
98
+ `FAILED`, `action` (`setup`, `load`, `upload`, `rename`, `delete`) and, for an upload, the `file` name. Throw an error
99
+ with a `status` (a failed `fetch` response works) and it is sorted for you. A cancelled call is not an error. The
100
+ visitor is shown a list that cannot be read ("Try again"), an upload that fails (in the upload panel) and a refused
101
+ `rename` or `delete` (in a pop-up, "Rename failed"), each with your library's own sentence under it. Your page gets the
102
+ event as well, for its own log; the visitor already has the message, so a second one from your page would say it twice.
103
+ - **Nothing is kept on the visitor's device**: no file tree, no cache and no remembered selection, so the next person
104
+ on a shared computer never sees the previous one's picks.
105
+ - **The constructor refuses a `mediaLibrary` without a `list` function**, and `getToken` stays required without one.
106
+ - Without a `mediaLibrary` the module builds the same kind of library over `GET|POST /uploads` with the session token
107
+ (see "Known gaps" for what that API cannot do yet).
108
+ - **`urlResolver`** (optional, on the same object): `(file) => string | Promise<string>`. When a file from your library
109
+ is picked (in the File Browser module's `select` event, or when a composition field stores it), the module calls this
110
+ and saves the address it returns. Use it when `list` returns short-lived signed urls but embeds need a stable or
111
+ redirecting address. Time limit 10 seconds; on failure or a result that is not `http:` or `https:`, the file's own
112
+ `url` is kept and one `console.warn` is written. **Memoreco pattern:** addresses should work without a sign-in (no
113
+ cookies), or redirect to one that does. Measured in Chromium 153 (local servers on three different origins, no
114
+ cookies): a redirect to another origin works for images, video and audio loaded the plain way (`<img>`, `<video>`,
115
+ `<audio>`) with no CORS headers at all. Anything loaded in CORS mode needs `Access-Control-Allow-Origin` on the
116
+ redirect answer **and** on the final file: fonts (`@font-face` and `FontFace` always load that way), pictures, video
117
+ or audio with `crossorigin="anonymous"` (read through a canvas, WebGL or Web Audio), and `fetch`. After a redirect to
118
+ another site the browser sends `Origin: null` to the final host, so a rule that names the page's origin fails there:
119
+ answer `*`, or echo the `Origin` you receive. Firefox and Safari were not run (the Fetch standard says the same), and
120
+ a Content-Security-Policy on the widget's page applies on top.
121
+ - **`upload` with `purpose`** (widget creator and composition editor file fields): when `upload` is given on
122
+ `mediaLibrary`, the **widget creator** calls it once per file for chat attachments (`purpose: 'chat'`) and for
123
+ prompt or canvas reference images (`purpose: 'canvas'`). File pickers in the creator and composition editor pass
124
+ `purpose: 'field'`. The request shape is `upload({ file, purpose, onProgress?, signal? })`. The transfer has no time
125
+ limit of ours: it ends when your promise settles or when `signal` aborts (only `urlResolver` keeps a 10 second
126
+ lookup limit). A valid result is `{ id, name, url, mimeType?, size? }` with an `http:` or `https:` url (after optional
127
+ `urlResolver` / `storeFileUrl`). A file the visitor attaches to the chat and then sends is uploaded once: sending the
128
+ message reuses the stored copy instead of calling `upload` again (a failed upload leaves nothing to reuse, so the
129
+ next attempt calls it again). When the partner gave `upload`, a rejection or invalid result is shown to the visitor
130
+ as the message of your error ("The upload failed." when it has none, so reject with words a visitor can read) and
131
+ Widgetic's `POST /uploads` is **not** used; one `console.warn` per mount explains that. Without `upload`, canvas
132
+ and chat behaviour is unchanged (Widgetic storage for chat; embedded base64 for prompt images).
133
+
134
+ ```js
135
+ upload: async ({ file, purpose, signal }) => {
136
+ const folder = purpose === 'chat' ? 'chat' : purpose === 'canvas' ? 'canvas' : 'fields';
137
+ const stored = await myStore.put(file, { folder, signal });
138
+ return { id: stored.id, name: file.name, url: stored.publicUrl, mimeType: file.type, size: file.size };
139
+ },
140
+ ```
141
+
142
+ ## Partner file picker (`pickFile`)
143
+
144
+ When the **composition editor** or **widget creator** opens a file field, it uses the built-in File Browser by default.
145
+ Pass **`pickFile`** to call your own picker instead:
146
+
147
+ ```js
148
+ pickFile: async ({ accept, multiple, signal }) => {
149
+ const chosen = await myPicker.open({ types: accept, many: multiple, cancel: signal });
150
+ return chosen.map((f) => ({ id: f.id, name: f.name, url: f.publicUrl, mimeType: f.type }));
151
+ },
152
+ ```
153
+
154
+ `accept` is the list of file types the field allows, as the field gives it (for example `['image/*']`), and `['*/*']` when
155
+ the field names none. `multiple` is `false` for file fields, and a field takes the first file of the list you return.
156
+ `signal` aborts when the visitor closes the editor or starts another pick. Resolving `[]` or rejecting with an
157
+ `AbortError` means cancelled; any other rejection is written to the console once and also counts as nothing picked (the
158
+ field is unchanged, and the visitor sees nothing). A result that is not an array is ignored with one `console.warn`, and
159
+ so is an entry of it that has no `id` or no `url`. When `pickFile` is not given, behaviour is unchanged. It serves file
160
+ fields only: chat attachments and pictures dropped on the creator's canvas use `mediaLibrary.upload` (with `purpose`).
161
+
162
+ ## Using the composition editor module
163
+
164
+ The settings of one composition beside a live preview of its widget, saved through the API: what a managed user needs to
165
+ change the texts, pictures, colours and fonts of their own widget without leaving your page. It is Widgetic's own editor
166
+ (`@widgetic/editor`'s `CompositionEditorApp`, the one the Widgetic site uses), drawn in a shadow root.
167
+
168
+ The session you mint needs the `editor` surface, and `files` for the file pickers: `surfaces: ['editor', 'files']`. It
169
+ opens and changes the compositions of the managed user it was minted for, and nothing else: another user's composition
170
+ is answered with 404 (create the composition for that user with `managedUserId`).
171
+
172
+ ```js
173
+ import { mountModule } from '@widgetic/ui-sdk';
174
+
175
+ const editor = await mountModule('composition-editor', {
176
+ container: '#editor', // give it a height: it fills its container
177
+ compositionId: 'cmp_123', // one editor edits one composition
178
+ getToken: async ({ reason }) => (await fetch('/my-server/widgetic-editor-session')).json(), // { token, expiresAt }
179
+ theme: 'light',
180
+ on: {
181
+ ready: ({ name, widgetId }) => showTitle(name),
182
+ dirty: ({ dirty }) => markUnsaved(dirty),
183
+ saved: ({ savedAt }) => markSaved(savedAt),
184
+ error: ({ message, code, fatal, sessionEnded }) => report(code, message),
185
+ },
186
+ });
187
+ // later: await editor.unmount(); // saves what is unsaved first
188
+ ```
189
+
190
+ Without the SDK it is the same class as the File Browser's (`new CompositionEditorModule(container, config)`, `on`,
191
+ `await mount()`, `await unmount()`), imported from `https://cdn.widgetic.com/modules/composition-editor/<version>/index.js`.
192
+
193
+ | Option | |
194
+ | --- | --- |
195
+ | `compositionId` | **Required.** The composition to edit. To edit another one, mount another editor. |
196
+ | `getToken` | **Required**, and the same as for the File Browser. It is called once before the editor appears (a `getToken` that fails fails the mount), and again when the token is about to run out or the API refuses it (`reason: 'expired'`, once per refusal). |
197
+ | `mediaLibrary` | Your own media library for the file pickers (see "Showing your own media library"). Without it they show the managed user's Widgetic uploads. |
198
+ | `pickFile` | Your own file picker for file fields (see "Partner file picker (`pickFile`)"). Without it the built-in File Browser is used. |
199
+ | `googleFontsApiKey` | A Google Fonts Web Fonts API key for the font picker's list. Without one the picker lists a short set of popular families. |
200
+ | `autosaveDelayMs` | Save this many milliseconds after the last change. Default 2500; `0` saves only when you call `save()`. |
201
+ | `lockPreviewSize` | When `true`, resizing the preview changes how it looks in the editor but does not update `embedSettings.width` and `embedSettings.height` on save (you control embed size elsewhere). Default: `false`. |
202
+ | `theme` | As for every module: a mode, or a look of your own (see "Looking like your product"). |
203
+ | `locale` | A BCP 47 language tag (`de`, `pt-BR`): plural rules and how numbers and dates are written (including month and weekday names in calendars). When a translation pack exists for the tag, the module loads it as a lazy file; otherwise words stay English while formatting and direction still follow `locale`. See "Speaking your visitors' language". |
204
+ | `messages` | The editor's words in your language, `{ 'editor.props.save': 'Speichern', ... }`: **one** object for the whole editor, the file picker and the rich text editor. A key you leave out stays English. See "Speaking your visitors' language". |
205
+ | `apiUrl` | As for the File Browser. |
206
+
207
+ Events: `ready` `{ name, widgetId }` (the composition has loaded and is on screen), `dirty` `{ dirty }` (there is, or is
208
+ no longer, work that is not saved), `saved` `{ composition, savedAt }` (a save went through), and `error`
209
+ `{ message, code?, fatal, during?, status?, retryable?, sessionEnded?, correlationId? }`. The editor shows a problem to the
210
+ visitor itself (with "Try again" where that helps); `error` is for your page. `fatal: true` means the editor cannot go on
211
+ by itself: the composition cannot be opened, or the session is over (`sessionEnded`), so give it a new session or take it
212
+ away. `correlationId` is what Widgetic's support needs to find the request.
213
+
214
+ Methods (on `editor.module` when you mounted it with the SDK): `save()` saves what is unsaved now, `flush()` saves
215
+ everything and waits, both resolving `true` when nothing is left unsaved; `isDirty()`; `reload()` loads the composition
216
+ again (unsaved edits are lost); `setTheme(theme)` (see "Looking like your product"); `setLanguage({ locale?, messages? })`, and
217
+ `CompositionEditorModule.defaultMessages` and `checkMessages(messages)`, which are also on the instance (see "Speaking your
218
+ visitors' language").
219
+
220
+ **Taking it away.** `unmount()` saves what is unsaved first (waiting up to 10 seconds), so closing the editor never loses
221
+ the last edits. If some could not be saved, an `error` with code `UNSAVED_ON_UNMOUNT` says so (the SDK keeps your
222
+ handlers connected until `unmount()` has finished, so you hear it). `editor.module.unmount({ discard: true })` throws the
223
+ unsaved edits away instead.
224
+
225
+ **What it puts on your page.** Besides the `<widgetic-ui-module>` host and the namespaced font rules every module adds,
226
+ a font the visitor looks at in the font picker adds Google's stylesheet for it to `<head>` (fonts cannot be loaded from
227
+ inside a shadow root). Those stylesheets are taken away again on `unmount()`. Your own `<link>`s, `<meta>`s and
228
+ everything else in `<head>` and `<body>` stay exactly as they are; the editor keeps its own storage under the
229
+ `widgetic:editor:` prefix.
230
+
231
+ ## Using the widget creator module
232
+
233
+ Widgetic's whole canvas, on your page: a managed user draws frames, describes a widget to the chat, watches it being
234
+ built, changes its settings and publishes it, without leaving your product. It is the creator of the Widgetic app
235
+ (`@widgetic/creator`, 0.4.0 or newer, which knows it is a guest), so everything the canvas does is there; the module
236
+ only gives it a shadow root, a session and a way to tell your page what happened.
237
+
238
+ The session you mint needs the `creator` surface, and `editor` and `files` for the settings panel and the file pickers:
239
+ `surfaces: ['creator', 'editor', 'files']`. It works on the canvases and widgets of the managed user it was minted for,
240
+ and nothing else: another user's canvas is answered with 404, exactly as if it did not exist. It can list and make the
241
+ compositions of the user's own widgets, but not delete them (the creator's advanced features, where deleting lives, are
242
+ off in a session).
243
+
244
+ ```js
245
+ import { mountModule } from '@widgetic/ui-sdk';
246
+
247
+ const creator = await mountModule('widget-creator', {
248
+ container: '#creator', // give it a height: it fills its container
249
+ canvasId: savedCanvasIdOfThisUser, // optional: the one `canvasChanged` gave you last time
250
+ getToken: async ({ reason }) => (await fetch('/my-server/widgetic-editor-session')).json(), // { token, expiresAt }
251
+ theme: 'light',
252
+ on: {
253
+ ready: ({ canvasId }) => {},
254
+ canvasChanged: ({ canvasId }) => rememberForNextVisit(canvasId),
255
+ widgetRenamed: ({ widgetId, name }) => setTitleOfTheUsersWork(name),
256
+ widgetPublished: ({ widgetId, version }) => showInMyProduct(widgetId),
257
+ limitReached: ({ message, code }) => offerMore(),
258
+ error: ({ message, code, fatal, sessionEnded }) => report(code, message),
259
+ },
260
+ });
261
+ // later: await creator.unmount();
262
+ ```
263
+
264
+ Without the SDK it is the same class as the other modules' (`new WidgetCreatorModule(container, config)`, `on`, `await
265
+ mount()`, `await unmount()`), imported from `https://cdn.widgetic.com/modules/widget-creator/<version>/index.js`.
266
+
267
+ | Option | |
268
+ | --- | --- |
269
+ | `getToken` | **Required**, and the same as for the other modules. It is called once before the creator appears (a `getToken` that fails fails the mount), and again when the token is about to run out or the API refuses it (`reason: 'expired'`, once per refusal). |
270
+ | `canvasId` | The canvas to open, as `canvasChanged` gave it to you. It has to be the user's own. Without one the creator opens the user's latest canvas, or makes a new one when they have none. |
271
+ | `widgetId` | The widget of that canvas to open (needs `canvasId`). |
272
+ | `startWithNewWidget` | Start from an empty canvas with a new widget instead of the latest canvas. |
273
+ | `presets` | `'pick'` (the default) or `'off'`. A visitor who has made nothing yet is shown your presets before the creator opens and gets a copy of the one they pick; `'off'` never shows them (see "Starting points for a visitor who has made nothing yet"). |
274
+ | `presetsOnly` | When `true`, hides "Start from scratch" and offers only your presets. If you have none, the visitor sees a clear empty state (not a blank screen) and the module logs one warning. Default: `false`. |
275
+ | `startFromPreset` | The key of one of your presets. A visitor who has made nothing yet gets a copy of it without being asked, and the creator opens on it. |
276
+ | `presetLabels` | The words of the picker, for a tone of your own: `{ heading, intro, startFromScratch, startFromScratchHint, copying, copyFailed, presetGone, checking }`. A shortcut for the eight `presetPicker.` messages (see "Speaking your visitors' language"): a word that `messages` also says is `messages`'s. Any word neither says stays English. |
277
+ | `locale`, `messages` | The creator's language: the plural rules, numbers and dates, and the words as ONE flat object of message keys and texts for the whole creator (its own words, the chat's, the canvas's, the picker's). See "Speaking your visitors' language"; `setLanguage({ locale?, messages? })` changes them while it is on screen. |
278
+ | `mediaLibrary` | Your own media library for the settings panel file pickers (see "Showing your own media library"). When `upload` is given, chat attachments and canvas/prompt images use it too (`purpose`: `chat`, `canvas`, or `field` for pickers), with Widgetic upload as fallback. |
279
+ | `pickFile` | Your own file picker for file fields (see "Partner file picker (`pickFile`)"). Without it the built-in File Browser is used. |
280
+ | `widgetBuilderUrl` | The origin the live previews of widgets are served from. Default: Widgetic's. |
281
+ | `theme` | As for every module: a mode, or a look of your own (see "Looking like your product"). |
282
+ | `themeFromHost` | As for every module (see "Looking like your product"). |
283
+ | `apiUrl` | As for the File Browser. |
284
+
285
+ Events: `ready` `{ canvasId }` (the canvas is on screen; `canvasId` is `null` for a new, empty one; for a visitor who is
286
+ shown the picker it comes after they chose), `presetChosen` `{ key, canvasId, widgetId, widgetName, warnings, automatic }`
287
+ (a starting point was chosen: see "Starting points ..."), `canvasChanged`
288
+ `{ canvasId }` (the creator opened a canvas or made one: keep the id and give it back next time), `widgetRenamed`
289
+ `{ widgetId, name }` (the main widget has this name: said when the canvas opens and each time the user renames it, never
290
+ twice in a row for the same name, so you can keep a title for the user's work), `widgetPublished` `{ widgetId, version? }`,
291
+ `limitReached` `{ message, code? }` (the visitor ran into a limit; the creator tells them in plain words, this is for your
292
+ page: see "When a limit is reached"), `reloadRequested` (the creator would have reloaded the page to recover: unmount it and mount a new one),
293
+ and `error` `{ message, code?, fatal, during?, sessionEnded? }`. `fatal: false` with `during: 'presets'` is the starting points
294
+ not working (see "Starting points ...") and the creator opens as it always did. `fatal: true` means the creator cannot go on, and it has
295
+ said so on its own screen: either the session is over (`sessionEnded`, code `EDITOR_SESSION_REVOKED` or `SESSION_ENDED`
296
+ ...: mount again with a new one), or the `canvasId` you gave is not this user's (`during: 'canvas'`, code `NOT_FOUND`: mount
297
+ again without it). Either way, no `ready` comes, and the creator stops asking the API.
298
+
299
+ Methods: `getCanvasId()` (the canvas that is open now, or `null`), `setTheme(theme)` (see "Looking like your product"),
300
+ `setLanguage({ locale?, messages? })` and, to hand to a translator, `defaultMessages` and `checkMessages(messages)` (see
301
+ "Speaking your visitors' language"), `unmount()`.
302
+
303
+ **What it keeps.** It does not touch your page's `localStorage`, `sessionStorage`, cookies or address bar, and never
304
+ opens a window, reloads or navigates your page: what it remembers (the user's settings, colour presets, the canvas that
305
+ was open ...) lives in memory until `unmount()`, which is why `canvasChanged` exists. It makes no WebSocket connection;
306
+ it follows a generation over the API's event stream.
307
+
308
+ **When a limit is reached.** Your credits, your plan and your storage are yours: a visitor is never told what they hold.
309
+ The API refuses a session with one plain sentence ("This is not available right now. Please try again later.") and the
310
+ creator shows exactly that, in the chat with a *Retry* button and in a toast, and keeps working: the canvas, the chat and
311
+ the other widgets are still there. It also tells *your page*, with
312
+ `limitReached` `{ message: 'The visitor reached a limit.', code }`, where `code` is what the API answered:
313
+
314
+ | `code` | What happened |
315
+ | --- | --- |
316
+ | `BILLING_INSUFFICIENT_CREDITS` | Your account is out of credits |
317
+ | `AUTHZ_PLAN_RESTRICTION` | Your plan does not include what the visitor asked for |
318
+ | `QUOTA_STORAGE_EXCEEDED` | Your storage is full (a chat attachment was refused) |
319
+ | `COST_LIMIT_EXCEEDED` | The visitor used their allowance for the hour or the day (it comes back by itself; the creator says they reached a limit and does not suggest waiting 30 seconds) |
320
+ | `LIMIT_REACHED` | The visitor pressed an "Upgrade" button in the chat. The creator never opens a page or a window for it: what an upgrade means in your product is for you to show |
321
+
322
+ Your page hears about each `code` once in half a minute, however many requests are refused meanwhile. Ordinary rate
323
+ limiting (`RATE_LIMIT_EXCEEDED` and its kind) is **not** a limit: the creator asks the visitor to wait a moment and says
324
+ nothing to your page. The allowance of the hour or the day is counted for each visitor on their own, so one visitor
325
+ reaching it refuses and tells nobody else; credits, plan and storage are your account's, so when they run out every
326
+ visitor is refused. A visitor who presses *Stop* in the chat stops waiting for the answer; the server still finishes a
327
+ generation it has already started.
328
+
329
+ **Starting points for a visitor who has made nothing yet.** A visitor with no canvas would meet an empty one. When you have
330
+ made presets (the widgets of your account that you offer your customers: `PUT /partners/{partnerId}/presets/{key}`), the
331
+ creator shows them first: a page of cards (a thumbnail, a title and a line about it, in your order) and a *Start from
332
+ scratch* button. A pick is **copied** into the visitor's own work (a canvas with one widget, built on a fork of the preset's
333
+ code) and the creator opens on the copy; the visitor changes the copy, never your preset.
334
+
335
+ - **Who sees it.** Only a visitor with no canvas, on a page that names no `canvasId` and does not ask for
336
+ `startWithNewWidget`. A visitor who has work goes straight to their latest canvas, and costs one question to the API
337
+ (`GET /v1/canvases?page=1&size=1`). A page that gives `canvasId` back, as `canvasChanged` asks, or that sets
338
+ `presets: 'off'` asks nothing at all.
339
+ - **What your page hears.** `presetChosen` `{ key, canvasId, widgetId, widgetName, warnings, automatic }`: `key`, `canvasId`,
340
+ `widgetId` and `widgetName` are `null` when the visitor chose *Start from scratch*, `automatic` is `true` for
341
+ `startFromPreset`, and `warnings` are the sentences the copy answered with for you (a part that could not be copied exactly).
342
+ The creator reports the copy's canvas with its own `canvasChanged` right after, and `ready` when it is open.
343
+ - **`startFromPreset: 'welcome-quiz'`** copies that preset for a visitor with nothing, with no picker. When it cannot be had (the
344
+ key is not one of your presets any more, the API is not answering) the picker is shown, or the plain creator when
345
+ `presets` is `'off'`, and your page hears the `error` below.
346
+ - **Never in the way.** Whatever goes wrong while looking for starting points (you have none, a gateway that does not have
347
+ the routes yet, a refused or lost request) the creator opens as it always did, and your page hears one `error` with
348
+ `fatal: false` and `during: 'presets'`. A session that is over is the creator's to announce, once, as `fatal`. A copy
349
+ that fails keeps the picker on screen with a sentence for the visitor ("... could not be opened right now ...", in your
350
+ `presetLabels`), and pressing again sends the same `Idempotency-Key`, so a copy whose answer was lost is not made twice. A
351
+ preset you took away meanwhile leaves the picker with its own sentence.
352
+ - **Words and look.** The picker is drawn inside the module with its `theme` (a preset, your colours, the radius, the font,
353
+ light or dark), and every word is in `presetLabels`; a name the picker does not use is left out with one console warning, and
354
+ a value that is not a non-empty text is refused when the module is made, with a message that says which (so are a
355
+ `presets` that is not `'pick'` or `'off'` and a `startFromPreset` that is not a preset key).
356
+ - **Thumbnails** are the `thumbnailUrl` you gave the preset, and only `http` and `https` addresses are drawn. They load
357
+ from your page, so a strict Content-Security-Policy needs the thumbnails' origin in `img-src` (what does not load is
358
+ replaced by the first letter of the title, so a blocked thumbnail costs the look, not the picker).
359
+ - **Routes.** The picker uses two routes that exist for editor sessions only (`GET /v1/managed-users/me/presets` and
360
+ `POST /v1/managed-users/me/presets/copy`, both on the creator's list, and not in the public SDK). A partner who draws
361
+ their own picker uses the public `listPartnerPresets` and `copyPresetForManagedUser` from their server and gives the
362
+ copy's `canvasId` (and `widgetId`) to the module.
363
+ - **What a copy costs.** Each copy forks a repository, and there is no limit per customer on how many a customer makes; the
364
+ API's ordinary rate limit for the visitor's address is the only brake.
365
+ - **Deploying it.** The API first, then the SDK, then the modules: a module that meets an API without the routes opens the
366
+ plain creator.
367
+
368
+ **What it leaves alone.** Keys go to the canvas's shortcuts (Delete, the arrows, `v` `r` `h` ... , Ctrl+A) only while the
369
+ focus is inside the creator, so a user who clicked on your page keeps every key of it, and your page's own zoom
370
+ (Ctrl or Cmd with `+` `-` `0`, Ctrl with the wheel) works everywhere. The chat follows its newest message inside its own
371
+ box and never scrolls your page. A user gives the creator the keyboard by clicking on it or tabbing into it.
372
+
373
+ **What it needs from your page.** A container with a height (the creator fills it) and, under a strict
374
+ Content-Security-Policy, what the other modules need plus `frame-src` for the origin of `widgetBuilderUrl` (the live
375
+ previews are frames served from there) and `img-src data: blob:`. The harness runs the creator under a policy that allows
376
+ only the API's origin (connections, pictures and frames), `data:` fonts and `data:` and `blob:` pictures, and no `eval`.
377
+
378
+ **One creator per page.** Its chat, its file lists and its user are stores of the whole page, so a second `mount()` is
379
+ refused with a message that says so; unmount the first one before mounting another.
380
+
381
+ ## Looking like your product (themes)
382
+
383
+ Every module takes a `theme`. It changes **colours, the roundness of corners and the typeface**, never the layout or the
384
+ controls, so a page with a design system of its own can have the modules match it. Each module has its own theme: the File
385
+ Browser, the composition editor and the widget creator can look the same or different.
386
+
387
+ ```js
388
+ const editor = await mountModule('composition-editor', {
389
+ container: '#editor',
390
+ compositionId,
391
+ getToken,
392
+ theme: {
393
+ preset: 'ocean', // a built-in look to start from; default 'widgetic'
394
+ mode: 'light', // 'light' (default) or 'dark'
395
+ colors: { primary: '#e0541b' }, // your colours, on top of the preset's
396
+ radius: 'medium', // 'none' | 'small' | 'medium' | 'large', or a number of pixels from 0 to 32
397
+ font: {
398
+ family: 'Poppins',
399
+ stylesheetUrl: 'https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap',
400
+ },
401
+ },
402
+ });
403
+
404
+ editor.setTheme({ preset: 'violet', mode: 'dark' }); // later: settings replace the whole theme
405
+ editor.setTheme('dark'); // only the mode changes; the colours, radius and font stay
406
+ ```
407
+
408
+ `theme: 'light'` and `theme: 'dark'` still work, and a module given no theme looks exactly as it always did (nothing is
409
+ written on it), whatever your page declares on `:root`.
410
+
411
+ | Setting | |
412
+ | --- | --- |
413
+ | `preset` | `'widgetic'` (the default look), `'graphite'`, `'ocean'`, `'violet'` or `'sunset'`, each with a light and a dark look (below). A preset sets colours only. |
414
+ | `mode` | `'light'` or `'dark'`. (`'system'` belongs to the SDK's own `theme`, which turns it into one of the two and follows the visitor's setting; a module on its own takes the two.) |
415
+ | `colors` | Any of `primary`, `primaryForeground` (the text on the primary colour), `background`, `foreground` (the text), `muted` (quiet surfaces), `mutedForeground` (secondary text), `border`, `accent` (the soft highlight), `destructive` (errors), `surface` (panel and card backgrounds — mapped to `--background`, `--card`, `--popover` and `--surface-canvas`) and `secondary` (quiet fills and rows — mapped to `--muted`, `--secondary` and `--grey1`, unless you also set `muted`). Give only the ones you want to decide: the rest follows from them (hover tints, borders, the greys of icons and secondary text, and a readable text colour on your `primary`). Naming only a `primary` changes the brand colours and leaves the greys alone. |
416
+ | `radius` | `'none'` (square, pills too), `'small'` (4 px), `'medium'` (8 px) or `'large'` (12 px), or a number of pixels from 0 to 32. The larger corners (cards, dialogs) scale with it. Without it the corners are as they were. The **widget creator** follows `radius` on its panels, toolbar, menus and chat the same way as the File Browser and the composition editor. |
417
+ | `themeFromHost` | When `true`, the module reads colours and `radius` from the **host element** it is mounted in (the container you pass to the constructor), from computed CSS custom properties (ones set on a parent count): `--primary`, `--primary-foreground`, `--background`, `--foreground`, `--muted`, `--muted-foreground`, `--border`, `--accent`, `--destructive`, `--secondary`, `--surface`, `--radius`. Only variables that are set and that the module can read are used; the rest is left out and never fails the mount. Colours are read as `#rgb`, `#rrggbb` (with or without a transparency), `rgb()` and `hsl()`; a bare `H S% L%` triplet, `oklch()`, colour names and `var()` are not read. `--radius` is read in pixels (`8px`), in rem (`0.5rem`, at the page's root font size), as a bare number of pixels or as `none`, `small`, `medium`, `large`; more than 32 pixels is drawn as 32. It reads at mount and again when the host's own `style` or `class` attribute changes (at most once per animation frame; a change on a parent is not noticed). Values you pass in `theme` explicitly (including `setTheme` later) win over the host's. Default: `false`. An invalid value is ignored after one `console.warn` and behaves like `false`. |
418
+ | `font` | `{ family, stylesheetUrl? }`. `family` is a CSS `font-family` value: a single name (`'Poppins'`) gets system fonts behind it, a list (`'"Poppins", Arial, sans-serif'`) is used as written. It applies to the module's text, not to your page. |
419
+
420
+ The built-in themes:
421
+
422
+ | Preset | Brand colour, light | Brand colour, dark | For |
423
+ | --- | --- | --- | --- |
424
+ | `widgetic` | deep forest green on white (unchanged) | a lighter green on near-black | The Widgetic look. |
425
+ | `graphite` | `#1f2328` | `#6b7683` | Neutral and quiet: near-black controls; the content carries the colour. |
426
+ | `ocean` | `#0b69c7` | `#3b82f0` | Clear blue. |
427
+ | `violet` | `#6d3fd9` | `#8b5cf6` | A saturated purple. |
428
+ | `sunset` | `#e0541b` | `#e8602a` | Warm orange. |
429
+
430
+ Your own `colors` win over the preset's; a `primary` of yours without a `primaryForeground` gets the white or the dark ink
431
+ that reads better on it.
432
+
433
+ **Writing a colour.** `#rrggbb`, `#rgb`, `rgb(11 107 203)` or `hsl(210 90% 41%)` always work. A colour name or `oklch()` works
434
+ in a browser that understands it. `var(--brand)` and `currentColor` are refused: the module reads the colour when it is
435
+ given, it cannot look at your page's variables from there, so read the value in your page and pass it in. Transparency
436
+ is ignored (a colour is a colour). The module warns in the console (once for each theme it takes) about a combination
437
+ that would be hard to read: your text below 4.5:1 against your background, or your primary colour, or the text on it,
438
+ below 3:1.
439
+
440
+ **A font the page does not have yet.** A font can only be defined by the page itself, never from inside a shadow root.
441
+ Give `stylesheetUrl` (an `https` address; `http` only for `localhost`) and the module adds one
442
+ `<link rel="stylesheet" data-widgetic-ui-font>` to your `<head>`, once per address however many modules use it. Like the
443
+ `@font-face` rules every module adds, it stays after `unmount()`. A font your page already loads needs no
444
+ `stylesheetUrl`. Under a strict Content-Security-Policy, `style-src` has to allow the stylesheet's host and `font-src`
445
+ the font files (Google Fonts: `https://fonts.googleapis.com` and `https://fonts.gstatic.com`).
446
+
447
+ **A theme that cannot be used** (an unknown preset, a setting that does not exist, a colour that cannot be read, a radius
448
+ over 32) is refused with an error whose `code` is `INVALID_THEME` and whose message names the setting and what to write
449
+ instead. `new Module(...)` and `setTheme` throw it, and nothing changes: a module that was running keeps the look it had.
450
+
451
+ **With the SDK**, the theme can come from three places:
452
+
453
+ ```js
454
+ const ui = new WidgeticUI({ getToken, theme: { preset: 'ocean', radius: 'medium' } }); // the look of every module of this page
455
+ const files = await ui.mount('file-browser', { container: '#files' }); // takes the page's look
456
+ const editor = await ui.mount('composition-editor', {
457
+ container: '#editor',
458
+ compositionId,
459
+ theme: { preset: 'violet', mode: 'dark' }, // a look of its own
460
+ });
461
+
462
+ ui.updateTheme('dark'); // the mode of every module; each keeps its colours, radius and font
463
+ ui.updateTheme({ preset: 'sunset' }); // new page-wide settings: modules without a look of their own take them
464
+ editor.setTheme({ radius: 'none' }); // one module alone
465
+ ```
466
+
467
+ - A mode (`'light'`, `'dark'`, `'system'`, or `{ mode }`) changes the mode of every module and keeps the rest of its look.
468
+ - Settings given to `updateTheme` replace the page-wide settings and reach the modules that have none of their own.
469
+ A module whose mount call (or its own `setTheme`) brought settings **keeps them**; it follows the mode when the call
470
+ names one (`ui.updateTheme('dark')`, `ui.updateTheme({ preset: 'x', mode: 'dark' })`), and is left completely alone
471
+ when the call does not (a page that changes a preset does not turn a dark module light).
472
+ - `ui.getTheme()` answers `{ mode, ...settings }` for the page. `'system'` stays `'system'` there.
473
+ - `updateTheme` throws `INVALID_THEME` for a theme of the wrong shape (an unknown key, an empty object, a list). When it is
474
+ the module that refuses the values (an unknown preset name, a colour it cannot read), the SDK cannot know in advance:
475
+ it reports `The "<module>" module could not apply the theme ...` with `console.error`, the other modules still take
476
+ theirs, and the refusing module keeps its look. `mounted.setTheme(...)` and a theme in a mount call throw (the mount
477
+ fails with `MOUNT_FAILED` and leaves its container empty).
478
+
479
+ **What a theme cannot do yet.**
480
+
481
+ - **The widget creator on a dark theme.** A dark
482
+ `mode`, or colours of your own for `background`, `foreground`, `muted`, `mutedForeground` and `border`, restyle its panels,
483
+ toolbar, menus, dialogs and chat, and every text of it stays readable (no text under 3 to 1 in the states a visitor reaches,
484
+ for each built-in preset and for neutral colours of your own, checked in a browser). The `font` applies to all of its
485
+ text. Your `primary` colour is the creator's accent: the selected tool, the sliders, the buttons that act ("Convert to
486
+ widget", "Load"), the chat's Send button and the toggles of the text properties, darker under the pointer (lighter on a
487
+ dark surface). The text and icons on an accent are your `primaryForeground` when you give one, else white or a dark ink,
488
+ whichever reads on your colour: a light yellow gets dark text. Accents used as text (an active icon, a label) take your
489
+ colour made readable on the surface it sits on. Without a `primary` the accents are Widgetic's own green and blue, exactly
490
+ as they were. The canvas board and the live widget previews stay light on purpose (they show the widget as your visitors
491
+ will see it), and the chat's message bubbles keep their own light colours. Not your brand colour: the selection handles
492
+ the canvas draws on the board, the few accents the creator sets in script (the colour of a drop-down's label and tick),
493
+ and the colours of a status (the green of "Live" and of a version, the red of an error). The canvas board and the live
494
+ previews keep Widgetic's own roundness in a few places. A light look follows `colors` the same way; with no
495
+ theme the creator's greys are Tailwind's own, never more than 4 of 255 from what they were in a colour channel. The
496
+ console says what stays light when a creator gets a dark theme. The File Browser and the composition editor follow a dark
497
+ theme.
498
+ - **No layout and no icons.** Components and spacing are Widgetic's. The words of the File Browser, the composition editor and the widget creator can be changed (see "Speaking your visitors' language").
499
+ - **Only colours the module can read as they are** (see "Writing a colour"): no CSS variables, and no gradient or image for a colour.
500
+ - The old `ThemeConfig` object (`{ mode, colors: { secondary, surface, text }, spacing }`) is no longer accepted by `theme`: it never
501
+ changed anything in a module. Use the settings above.
502
+
503
+ ## Speaking your visitors' language
504
+
505
+ The **File Browser**, the **composition editor** and the **widget creator** can speak your visitors' language. Every word
506
+ they show is a *message* with a key: your page hands over the words it wants to change and every key it leaves out stays
507
+ English, so a language can be added one screen at a time. The examples below are the File Browser's; "The composition
508
+ editor" and "The widget creator" say what is different.
509
+
510
+ ```js
511
+ const files = await mountModule('file-browser', {
512
+ container: '#media',
513
+ getToken,
514
+ locale: 'pl', // plural rules, numbers, dates and file sizes
515
+ messages: {
516
+ 'action.cancel': 'Anuluj',
517
+ 'action.addToEditor': 'Wybierz', // the button that hands the pick to your page
518
+ 'toolbar.deleteMany': '{count, plural, one {Usuń # plik} few {Usuń # pliki} many {Usuń # plików} other {Usuń # pliku}}',
519
+ },
520
+ });
521
+
522
+ files.setLanguage({ locale: 'de', messages: germanMessages }); // later, while it is on screen, with no new mount
523
+ ```
524
+
525
+ | Option | |
526
+ | --- | --- |
527
+ | `locale` | A BCP 47 language tag (`de`, `pt-BR`). It decides the plural rules and how numbers, dates ("2 days ago") and file sizes are written, through `Intl`. When a **translation pack** exists for the tag (see below), the module loads it as a lazy file next to `index.js` and applies those words before your `messages`. A tag with no pack keeps English for words; plural rules and direction still follow `locale`. Blank or left out is English. It is also the `lang` of the module's elements (a screen reader says the words in that language), and a language that is written right to left (`ar`, `he`, `fa`, `ur` ...) turns the whole screen of the File Browser, the composition editor and the widget creator around: see "Right to left". `new WidgeticUI({ locale })` hands it to every module of the page. |
528
+ | `messages` | The words you want to change, `{ 'action.cancel': 'Anuluj', ... }`. A key you leave out stays English. |
529
+ | `selectLabel` | The text of the button that hands the pick to your page, for a page that only wants to rename that one button (default "Select"). `messages['action.addToEditor']` does the same and wins when both are given. |
530
+ | `setLanguage({ locale?, messages? })` | On the handle (`files.setLanguage`) and on a module you made yourself. Changes the language at once, while the module is on screen or before `mount()`. A value the call leaves out keeps what it was. `messages` it gives **replace** all the earlier ones: a page that switches from German to French passes the French only, and `setLanguage({ locale: '', messages: {} })` goes back to English. `null` counts as "not said". When `locale` changes, the module loads the matching pack (if any) and applies it in one step; two quick calls end in the language of the last call. |
531
+
532
+ **Translation packs (shipped languages).** Each pack is one lazy file next to `index.js` (gzip budget per pack: File Browser **5 kB**, composition editor **9 kB**, widget creator **28 kB**; the build fails when a pack grows past its module's budget). **Twelve** languages ship today as lazy JSON packs on the CDN: the eight left-to-right ones (`fr`, `de`, `es`, `pt-BR`, `nl`, `da`, `sv`, `zh-CN`) and four right-to-left ones (`ar`, `he`, `fa`, `ur`; Hebrew also answers to the legacy tag `iw`). Every pack is **provisional** until a native speaker has reviewed it. Each module exposes `Module.supportedLocales` (the list above) and `Module.localePackStatus(tag)` (`'provisional' | 'reviewed' | null`). Master files for translators live in `modules/locales/<tag>.json` (union of all keys); the build splits them into one pack per module. Missing keys in a pack fall back to English. **Merge order:** pack → module English shortcuts (`selectLabel`, `presetLabels`, the File Browser's "Select" / "Files selected" toasts) → your `messages` (your page always wins). **Fallback examples:** `pt-PT` and `pt` → `pt-BR` pack; `fr-CA` → `fr`; `zh` / `zh-Hans` / `zh-SG` → `zh-CN`; `zh-TW` / `zh-Hant` → no pack (English words, Simplified is not used); `ar-SA`, `ar-EG` → `ar`; `he-IL` and `iw` → `he`; `fa-IR`, `fa-AF` → `fa`; `ur-PK`, `ur-IN` → `ur`; `en*` → no pack; unknown tag → English (no console line). A pack file that fails to load is reported once in the console; the module keeps working in English. On `mount()`, the module waits for the pack in parallel with its session token so the first paint can be in the pack language when the file arrives in time. Commands: `npm run locales:export-english`, `locales:import-shopify`, `locales:coverage`. Report a wrong translation to Widgetic support with the module name, `locale`, message key and what you expected.
533
+
534
+ **`action.addToEditor` vs Shopify.** The confirm button of the file picker is the message `action.addToEditor`. In these modules its English text is **Select** (`selectLabel` is a shortcut for the same key; `messages` wins over both). Packs seeded from the Shopify app's File Browser used Shopify's wording ("Add to Editor") for that key; the import script replaces it with Select in each language. There is no separate `action.select` key in the module catalogs (Shopify's JSON may list `action.select` for another button).
535
+
536
+ **Which keys there are.** `files.module.defaultMessages` (`FileBrowserModule.defaultMessages` when you load the module
537
+ yourself, without the SDK) is an object of every key and its English text, a new copy on every call. It holds a few
538
+ hundred messages, grouped by where the words appear (`action.`, `upload.`, `dialog.`, `preview.` ...), and it matches the
539
+ version of the module you load. It is the list to hand to a translator:
540
+
541
+ ```js
542
+ console.log(JSON.stringify(files.module.defaultMessages, null, 2));
543
+ ```
544
+
545
+ **Writing a message.** A message is text. `{name}` is a value the File Browser puts in (a number is written the way the
546
+ locale writes numbers). `{count, plural, one {# file} other {# files}}` picks the branch that fits the number in the page's
547
+ language: `other` is required, `=0 {none}` matches exactly 0, `#` is the number, and a language with more forms says so
548
+ (Polish has `one`, `few`, `many` and `other`). `\{`, `\}`, `\#` and `\\` write the character itself. A translation keeps the
549
+ `{names}` of the English message, in any order; it cannot ask for a value the message is never given. The File Browser's
550
+ README ("Languages") has the same rules.
551
+
552
+ **Checking before a visitor does.** `files.module.checkMessages(messages)` (also `FileBrowserModule.checkMessages`) says
553
+ what is wrong without showing anything: one sentence for each key that does not exist (with the nearest real one), value that
554
+ is not text, template that does not parse, or `{name}` the message is never given. An empty list means every message will
555
+ be used. Put it in a test of your page.
556
+
557
+ **Pop-ups.** The module draws the File Browser's pop-ups itself (see "Known gaps"), and they are messages like the rest:
558
+ the `toast.` keys. Thirty of them say what became of a rename, a delete, a new folder or a pick (`toast.rename.done`,
559
+ `toast.delete.doneMany` ...); `toast.regionLabel` ("Notifications") is the name of the region a screen reader announces
560
+ them in, and `toast.closeLabel` ("Close notification") the name of their close button. After a pick the module says
561
+ "Files selected" and "2 files selected" (`toast.filesAdded`, `toast.filesAddedDetail`; `defaultMessages` lists them with
562
+ the module's English), not "Added 2 files to the editor", which is a sentence about the Widgetic site. The sentence under
563
+ "Rename failed" or "Failed to delete" is your library's own, shown as it arrives.
564
+
565
+ **What a mistake does.**
566
+
567
+ - A message that cannot be used does not break the screen: the English text of that key is shown, and the console says
568
+ `[FileBrowser] ...` **once**. An unknown key is ignored the same way.
569
+ - A wrong **shape** is a mistake in your code, and it is refused where it is written: `messages: 'Abbrechen'` or
570
+ `locale: 5` throws a `TypeError` that names the option. `setLanguage` throws it itself and changes nothing; in
571
+ `mountModule` it comes as a `ModuleMountError` (`MOUNT_FAILED`) with the `TypeError` as its `cause`.
572
+
573
+ **Right to left.** Each of the three modules is read the way its `locale` is. For a language that is written right to left
574
+ (Arabic, Hebrew, Persian, Urdu and the others: the script of the language decides, not a list, so `ar-Latn` stays left to
575
+ right) the whole screen turns around and starts a line on the right. `setLanguage({ locale: 'ar' })` turns a module that is
576
+ on screen around, and `setLanguage({ locale: 'de' })` turns it back, with no new mount.
577
+
578
+ ```js
579
+ await mountModule('file-browser', { container: '#media', getToken, locale: 'ar' }); // read right to left from the first paint
580
+ ```
581
+
582
+ - **The File Browser:** the list starts on the right and the row that does not fit goes on under it, the search box, the
583
+ sort and filter controls, the selection bar, the upload panel and the windows are laid out from the right, a window's close
584
+ button is in the corner where a line starts, menus open toward the end of the line, the pop-ups come up in the bottom
585
+ left corner, arrows that mean back and forward are mirrored, and in the preview the arrow key that points toward the end
586
+ of the line goes on to the next file.
587
+ - **The composition editor:** the settings panel is docked at the start of the line (the right of the screen) and the
588
+ preview at the other side, the same distance from the middle as in English. The Design and Content tabs run from the start
589
+ of the line and each panel slides in from the side of its tab, the label of a control is at the start of its row, the
590
+ calendars start their week at the start of the line with the arrow that goes back at the start (and their arrows are
591
+ mirrored), a slider runs from the start of the line, the thumb of a switch that is off is at the start and travels toward
592
+ the end, the arrow keys of the date fields follow the line, and the file picker that opens from a file field is the File
593
+ Browser above, turned around with it.
594
+ - **The widget creator:** the tools of the toolbar run from the start of the line, the properties panel is docked at the
595
+ end of it, the context menu, the list of shapes, the publish history and the starting-point picker are laid out from the
596
+ start, the title of a widget in its panel keeps the room it needs, and the pop-up of the brand kit hangs from the
597
+ start edge of its button. The composition editor and the File Browser inside the creator are turned around the same
598
+ way.
599
+ - **What a visitor types** (a text field or the tags of the editor, the chat, a text in the quick edit of the creator) is
600
+ read by its own first letter on a right to left screen: a sentence in Latin letters is set from the left and one in
601
+ Arabic from the right, side by side. A field with nothing in it yet has no first letter, so it takes the direction of
602
+ the screen (its hint and its caret are at the start of the line). An email, a link (the editor's `email` and `url` kinds,
603
+ the link field of the creator) and a colour code stay left to right on every screen.
604
+ - **Only `locale` decides.** The direction of your page does not: a page written right to left (`<html dir="rtl">`) leaves
605
+ an English module alone, and a page written left to right does not stop an Arabic one. `messages` alone changes
606
+ nothing about it: it is the `locale` that says which way the words run.
607
+ - **Names of files and folders** are read by their own first letter, so a Latin name next to Arabic ones is not put in the
608
+ wrong order. A name that is put inside a sentence ("Failed to delete 2024 report.pdf") sits between two invisible marks
609
+ (Unicode isolates, U+2068 and U+2069), so the words around it cannot turn it around. A screen reader does not say them, and
610
+ a test that compares the text of a pop-up must leave them out. English and every other left to right language get none.
611
+ - **The video player's time line** stays left to right in every language: time runs that way.
612
+ - **Drawings stay left to right.** The drawing board of the widget creator (the canvas), the live previews of widgets and
613
+ the code are left to right in every language, as are the drawings that mean "left" and "right" in the composition editor
614
+ (the saturation and hue of the colour picker, the grid that places a box, the corners of a rounded box). A drawing is not
615
+ a line of text, and a widget's own preview must look the way its author made it.
616
+ - **Where it is not perfect.** (a) A calendar writes each weekday in one letter in a language written right to left whose
617
+ one-letter names the browser has (Arabic, Hebrew and Persian), and gives a screen reader the whole name, because the short
618
+ names of Arabic are whole words that do not fit a column. For Urdu the browser has no one-letter names (it answers with
619
+ English letters, which a calendar never shows), so its weekdays stay the short names and the row is tight. (b) The panel of
620
+ a widget in the creator opens on the side of its shape that has more room, as it does in English, and does not know where
621
+ the properties panel is: for a shape near the middle of the board it can open over that panel (in English, over the panel
622
+ at the other side).
623
+
624
+ **What stays as it is.**
625
+
626
+ - **Words that belong to someone else.** What your own media library says (the message of an error you throw from
627
+ `list`, `upload`, `rename` or `delete`), your file names, your library's `label`, the names of folders a visitor made,
628
+ and a sentence Widgetic's API sends back are shown as they arrive. The File Browser's own sentence is only used when the
629
+ library gave no reason (`libraryError.` messages).
630
+ - **`error` events.** `message` stays English: it is for your logs.
631
+ - **The loading spinner** shown while a module downloads is the SDK's, not the module's: its words are the `loadingLabel`
632
+ mount option (default "Loading"), which a screen reader says.
633
+
634
+ **The composition editor.** It takes the same `locale`, `messages`, `setLanguage`, `defaultMessages` and `checkMessages`
635
+ (`CompositionEditorModule.defaultMessages`, `editor.module.checkMessages(messages)` ...), with one difference:
636
+ **one flat `messages` object covers the whole editor.** The editor is made of three parts that each have their own words,
637
+ and it splits what you give between them, so you never need to know which part says a word:
638
+
639
+ - the editor's own words, the `editor.` keys: the Design and Content tabs, every control, the save button, the dates and
640
+ the failures it explains;
641
+ - the file picker that opens from its file fields, which is the File Browser: its keys (`action.`, `upload.`, `dialog.`,
642
+ `preview.` ...) are the ones described above, and the same `locale` and `messages` reach it;
643
+ - the rich text editor of its text fields, the `shadEditor.` keys. The editor draws its own text toolbar (`editor.` keys),
644
+ so these words are not on screen today, and a translation can leave them out.
645
+
646
+ `CompositionEditorModule.defaultMessages` lists all of them, with their English text: more than 500. A key that is in none
647
+ of the three parts is said once in the console as `[Editor] ...`, with the nearest real key, and ignored.
648
+
649
+ ```js
650
+ const editor = await mountModule('composition-editor', {
651
+ container: '#editor',
652
+ compositionId,
653
+ getToken,
654
+ locale: 'de',
655
+ messages: { 'editor.props.save': 'Speichern', 'action.cancel': 'Abbrechen' }, // a word of the editor, and one of its file picker
656
+ });
657
+
658
+ editor.setLanguage({ locale: 'pl', messages: polishMessages }); // labels and buttons change at once; what the visitor typed stays
659
+ ```
660
+
661
+ - **Dates follow `locale` without your help.** The names of the months and the weekdays in the calendars and the way a date
662
+ is written come from the browser's `Intl`; only the names of the calendars and of their buttons (what a screen reader
663
+ says) are messages. The date range control shows dates the way the language writes them: 7 October 2026 reads
664
+ `10/07/26` with `en` (and with no `locale`), `07/10/26` with `en-GB`, `07.10.26` with `de` and `pl`, and `26/10/07` with
665
+ `ja`, so give `en-GB` when you want the day first in English. A weekday heading in a calendar is the language's own short
666
+ name, not cut to two letters; in a language written right to left it is the one-letter name (Arabic `ح ن ث ر خ ج س`) with
667
+ the whole name as the label of the heading for a screen reader, and where the browser has no one-letter names (Urdu) it is
668
+ the short name. Values saved in the composition stay structured dates, not formatted strings.
669
+ - **What is saved with the composition stays English.** The title of a new item ("Item 03"), "Untitled Composition" and the
670
+ names a font weight or a position is saved under ("ExtraBold", "top-left") are written into the composition when they
671
+ are made. The editor shows the weights and the positions in your language and saves the English name.
672
+ - **The widget author's words stay as written:** the names, labels, descriptions and placeholders of the widget's settings,
673
+ its default texts, and the names of typefaces.
674
+ - **A change of language reaches what is on screen.** Labels and buttons change at once, and so do the banners of a
675
+ composition that could not be opened and of a save that failed (they are written when they are drawn). A sentence the
676
+ editor said once, such as why there is no preview, keeps the language it was said in until it says something new.
677
+ - **The `error` events stay English** (`message` is for your logs; use `code`), and what Widgetic's API sends back and what
678
+ your own media library says are shown as they arrive.
679
+ - **The file picker's pop-ups** are drawn inside the composition editor module's shadow root (a `<ToasterModal>` the module
680
+ renders, with `toast.regionLabel` and `toast.closeLabel` from the same `messages` list). After a pick the module says
681
+ "Files selected", not "Added … to the editor".
682
+
683
+ **The widget creator.** It takes the same `locale`, `messages`, `setLanguage`, `defaultMessages` and `checkMessages`
684
+ (`WidgetCreatorModule.defaultMessages`, `creator.module.checkMessages(messages)` ...), and like the composition editor it
685
+ takes **one flat `messages` object for all of it**. The creator is made of parts that each have their own words, and it
686
+ splits what you give between them, so you never need to know which part says a word:
687
+
688
+ - the creator's own words, the `creator.` keys: the widget's panel, publishing and versions, the brand kit (colors,
689
+ fonts and icon sources), the limits it explains, the lines of its status bar; the preset **Libraries** toggle and its
690
+ add-library control are drawn only in creator debug mode (`showPresetLibraries`), which the widget creator module does
691
+ not turn on, but their messages stay in the catalog for hosts that do;
692
+ - the chat's words (`chat.` keys) and the canvas's (`canvas.` keys: the toolbar, the zoom controls, the context menu, the
693
+ properties panel, the words the shapes draw on the canvas);
694
+ - the module's own: the eight words of the starting-point picker (`presetPicker.heading`, `presetPicker.intro`,
695
+ `presetPicker.startFromScratch` ...) and the two words of the region its pop-ups are announced in, `toast.regionLabel`
696
+ and `toast.closeLabel`, which are the File Browser's keys of the same names, so one translation serves both;
697
+ - the composition editor with its file picker and its rich text editor (the `editor.` keys, the File Browser's and
698
+ `shadEditor.`). The creator's *Edit* step is off in a session, so these are on no screen today and a translation can
699
+ leave them out.
700
+
701
+ `WidgetCreatorModule.defaultMessages` lists all of them, with their English text: more than 1,300.
702
+
703
+ ```js
704
+ const creator = await mountModule('widget-creator', {
705
+ container: '#creator',
706
+ getToken,
707
+ locale: 'pl',
708
+ messages: {
709
+ 'canvas.tool.select': 'Zaznacz', // the canvas
710
+ 'chat.input.placeholder': 'Wpisz wiadomość...', // the chat
711
+ 'creator.common.setLive': 'Ustaw jako aktywną', // the creator
712
+ 'presetPicker.heading': 'Od czego chcesz zacząć?', // the picker a visitor with nothing yet is shown
713
+ },
714
+ });
715
+
716
+ creator.setLanguage({ locale: 'de', messages: germanMessages }); // every screen that is open changes at once
717
+ ```
718
+
719
+ - **A language that comes later reaches everything on screen:** the canvas, the chat, the panels, the menus, the picker and
720
+ the pop-ups change without mounting the creator again. `setLanguage` keeps what the call leaves out and replaces the
721
+ messages, as for the other modules.
722
+ - **Dates follow `locale`.** The date and time of a version are written the way the language writes them (`10/01/2026 14:05`
723
+ in English, `01.10.2026 14:05` in Polish, `2026/10/01 14:05` in Japanese); only the words around them are messages.
724
+ - **`presetLabels` still works.** It is a shortcut for the picker's eight messages and sits under `messages`: when both say
725
+ a word, `messages` wins, and it stays in force after `setLanguage` for the words the new messages leave out.
726
+ - **A mistake never breaks the screen.** A key that none of the parts has is said once in the console as `[Creator] ...`,
727
+ with the nearest real key; a text that cannot be used is said once by the part that owns the key (`[Creator]`,
728
+ `[Chat]`, `[Canvas]`, `[Editor]`, `[FileBrowser]`, `[ShadEditor]`, or `[WidgetCreatorModule]` for the picker and the
729
+ pop-up region), and the English text of that message is shown. A wrong *shape* (`messages: 'Abbrechen'`, `locale: 5`)
730
+ throws a `TypeError` that names the option, and `setLanguage` throws it itself and changes nothing.
731
+ - **Lines the creator saved into the chat.** The API keeps them in English; on screen the creator translates known lines
732
+ (a failed generation, a restore, a version label) through the chat's `storedLineLabel`, with the same tables as its
733
+ status bar. A line the table does not know (a model reply) is shown as stored.
734
+ - **What stays as it is.** What the visitor and the AI write (the prompts, the answers, the names of widgets, the code);
735
+ the words a widget's author wrote for its settings; what Widgetic's API sends back, such as "Usage limit exceeded", which
736
+ is shown as it arrives; the `message` of the `error` and `limitReached` events (use `code`); and the parts a session
737
+ never draws (the sign-in screen, the standalone header, the debug panels, the preset **Libraries** section of the brand
738
+ kit, the list of keyboard shortcuts, the *Edit* and *Embed* steps). Its layout is turned around for a language written
739
+ right to left, as the composition editor's is (see "Right to left" above); the canvas board, the live previews and the
740
+ code stay left to right.
741
+
742
+ The page that makes sure of the first point is `harness/hostile.html?library=host&pseudo=1` (for the composition editor,
743
+ `harness/composition-editor.html?pseudo=1`, for the widget creator `harness/widget-creator.html?pseudo=1`), which gives the module a `messages` object holding **every** default message
744
+ wrapped in marks (`Delete` becomes `⟦Delete⟧`): anything a visitor can read that has no marks is English the module wrote
745
+ itself, which no `messages` could ever translate. The same trick works on your own page.
746
+
747
+ ## Commands
748
+
749
+ | Command | What it does |
750
+ | --- | --- |
751
+ | `npm install` | Installs, then `patch-package` applies any file in `patches/` (there is none at the moment: see "Workarounds, and when to delete each") |
752
+ | `npm run build` / `npm run build:file-browser` / `npm run build:composition-editor` / `npm run build:widget-creator` | Builds `dist/<name>/index.js` and the lazy files in `dist/<name>/chunks/` (+ source maps), prints the size, and fails when a file imports another to start, when it is over its budget or holds a script in a `data:` URL (see "Size budget" and "One file, and the parts that are not in it") |
753
+ | `npm test` | Unit tests (vitest): token source, session token provider, emitter, picked files, shadow mount, the composition editor and widget creator modules, the creator's route list, CSS transforms, fonts, the publishing rules, the R2 store, the release plan and the two scripts of the release pipeline |
754
+ | `npm run harness` | Serves `harness/hostile.html`, `harness/composition-editor.html`, `harness/widget-creator.html` and a mock Widgetic API on http://localhost:5290 |
755
+ | `npm run test:e2e` | Playwright against the harness (`PLAYWRIGHT_CHANNEL=chrome` uses the installed Google Chrome instead of Playwright's download) |
756
+ | `npm run check:creator-routes` | Reads the packages the creator is made of and checks that every route they can call is on the gateway's list for a creator session, or is listed with the reason a visitor can never reach it (`-- --inventory` prints it as JSON, see "What the end-to-end tests check") |
757
+ | `npm run publish:cdn -- <module> [options]` | Releases a module to the CDN: see "Publishing". `--help` lists every option |
758
+ | `npm run release:check -- --tag modules-v<x.y.z>` | The checks a release starts with (the tag against `package.json`, a lockfile the pipeline can install), on your machine: no keys, nothing written, no package needed |
759
+ | `npm run release:publish` | Releases every built module from the tag in `CI_COMMIT_TAG` (or `-- --tag modules-v<x.y.z>`), in three passes. This is what the pipeline's `publish` job runs; it needs the R2 settings. See "Releasing from a tag" |
760
+ | `npm run typecheck` | `tsc --noEmit` over `src`, `tests`, `e2e` |
761
+
762
+ Run `npm run build` (or the `build:<module>` of the one you test) before `npm run harness` / `npm run test:e2e`: the
763
+ harness serves `dist/`.
764
+
765
+ ### Size budget
766
+
767
+ A partner's page downloads, parses and runs `index.js` before the module appears, and fetches the lazy files only when a
768
+ visitor needs them. So a module has two sizes that matter, and every build ends by weighing both against the module's
769
+ budget in `scripts/lib/bundleBudget.mjs`:
770
+
771
+ - **first load** is `index.js`: what the visitor waits for. This is the one to keep small.
772
+ - **in all** is `index.js` and the lazy files: what a version weighs on the CDN, and the most a visitor who uses everything
773
+ downloads.
774
+
775
+ ```
776
+ [build-module] size file-browser: first load 1.50 MB of 1.60 MB, 395 kB gzip of 420 kB; in all 3.33 MB of 3.55 MB, 909 kB gzip of 970 kB (2 lazy files)
777
+ [build-module] lazy chunks/pdf-DyTSsyHP.js: 458 kB, 111 kB gzip
778
+ [build-module] lazy chunks/pdfWorker-BGng0wLJ.js: 1.38 MB, 403 kB gzip
779
+ ```
780
+
781
+ Over any of the four numbers, the build fails (exit code 1) and says by how much. The budgets sit a little above what each
782
+ module weighs today (`measured` in the same file has the day and the sizes), so a dependency bump passes and a new
783
+ library, or an import that lost its tree-shake, does not. When it fails, find what grew and take it out (or make it a lazy
784
+ file, see below); if the growth is worth it, raise the number in the same commit and say why. A module with no budget
785
+ fails too: a new module has to decide how big it may be.
786
+
787
+ The gzip figure is gzip at its best level, of each file on its own as a CDN serves it, measured by the script. It is a
788
+ little smaller than the one Vite prints just above it, which uses a lower level; the budget goes by the script's. A CDN
789
+ may do better with Brotli, but gzip is the floor every browser accepts.
790
+
791
+ The same step refuses a build that holds a script inside a `data:` URL, in any of its files (`data:text/javascript;base64,...`,
792
+ `scripts/lib/cspChecks.mjs`): a page with a strict Content-Security-Policy will not run one, so the module would load
793
+ fine and fail later, when the visitor first needs it. That is how the PDF viewer's worker was found (see "Workarounds").
794
+ Vite makes one of these of any JavaScript file named in a `new URL('./file.mjs', import.meta.url)` that it meets in a
795
+ library build, so a package that starts doing that fails the build instead of a partner's visitor.
796
+
797
+ ### What the end-to-end tests check
798
+
799
+ `harness/hostile.html` is a partner page that does everything wrong on purpose (`html { font-size: 62.5% }`, `button {
800
+ ... !important }`, rules for `.flex` and `.p-4`, `:root { --background: red }`, `* { cursor: crosshair }`, uppercase and
801
+ letter-spaced body text ...). The tests in `e2e/` assert that the module looks right there, that the partner's own
802
+ elements measure exactly the same before and after mounting, that nothing is left behind on unmount, that a hidden or
803
+ pointer-disabled region hides or disables the module too, that every request carries the session token and that a new
804
+ token replaces the old one, that a page taller than the window is not scrolled by clicks inside the module, and that
805
+ every font the module ships is accepted by the browser. They also cover the media libraries: the visitor's Widgetic
806
+ uploads (a refused token is renewed through `getToken({ reason: 'expired' })` exactly once, a token refused for good is
807
+ reported as `MEDIA_LIBRARY_UNAUTHORIZED`, a file over 10 MB is refused without any request, nothing is written to the
808
+ device) and a library the page brings (paging, picking, uploading, renaming and deleting with dialogs that stay inside
809
+ the shadow root, a read-only library without the buttons it cannot honour, a library that fails once and then works,
810
+ one that refuses the visitor, one that refuses every upload, rename and delete (the page gets an `error` event for each,
811
+ an upload failure is shown in the upload panel, and the files stay as they were), and no `getToken` call at all).
812
+
813
+ The harness also stands in for the CDN and the API (`/cdn/modules/<name>/...`, `/mock/v1/...`), so `e2e/sdkLoader.spec.ts`
814
+ drives the **built `@widgetic/ui-sdk`** (ES module and script-tag builds, run `npx rollup -c` in the parent first) through
815
+ the real load path: manifest, versioned file, retries, cancelling, and the real File Browser. One test of it opens the
816
+ page with `?csp=strict`, a Content-Security-Policy that allows only the CDN, the API and images (the policy is in the
817
+ SDK's README), and fails if the module needs anything more. `e2e/examplePage.spec.ts` opens the parent's
818
+ `examples/file-browser.html` with the CDN and the API redirected to the harness.
819
+
820
+ `harness/react-page.html` is a page built with React 18 (its browser builds come from this workspace's `node_modules`, so
821
+ the page needs no build) with the component of the SDK's README, for any module. `e2e/reactPage.spec.ts` runs it in
822
+ `<React.StrictMode>` (React runs the effect, cleans it up and runs it again) and out of it, for the File Browser, the
823
+ composition editor and the widget creator. The first run is cancelled before it counts as an instance, so the one-instance
824
+ guards do not refuse the second; the module is downloaded once; nothing reaches the console; a component that React
825
+ removes (its container leaves the page *before* the clean-up runs, and the module is taken down from it) leaves nothing
826
+ behind; one that comes back mounts a fresh module; and a pick goes to the newest `onPick` without mounting again. Taking
827
+ the `signal` or the `unmount()` out of that component turns these tests red, which is how the README's example is kept
828
+ honest.
829
+
830
+ `e2e/fileBrowserLanguage.spec.ts` checks the File Browser's words on the same page. It gives the module a **pseudo
831
+ language** (`?pseudo=1`: every default message wrapped in marks, `Delete` as `⟦Delete⟧`), walks the screens (the list and its
832
+ type menu, an empty type, one and two selected files, the selected-files, Rename and Delete windows, a preview, an upload,
833
+ a library that cannot be read) and fails on any text, label, hint or picture description that a visitor can read or hear
834
+ and that has no marks, apart from the page's own file names and its library's own sentence. An English word written into
835
+ a component, or a design system component used without its words, turns it red; it found the Rename window's hint ("file
836
+ name...") this way. With a real language (Polish, which has four plural forms) it checks `messages`, `locale`,
837
+ `selectLabel` against `messages`, `setLanguage` (at once, keeping what it is not told, replacing the messages, back to
838
+ English), that the partner's page is untouched by a change of language, `defaultMessages` and `checkMessages`, the one
839
+ console warning, and the `TypeError`s for a wrong shape.
840
+
841
+ `e2e/compositionEditorLanguage.spec.ts` does the same for the composition editor (`harness/composition-editor.html?pseudo=1`):
842
+ one pseudo language over the editor's own words, its file picker and its rich text editor, and a walk through both tabs, the
843
+ colour picker and the menus, the font menu, the text toolbar and its menus, the file picker, an opened item and the controls
844
+ that are dragged and typed, the two date pickers, and a composition that cannot be found, a session that ended and a save
845
+ that failed. It fails on any text, label or hint that a visitor can read or hear and that has no marks. A few kinds of
846
+ words are allowed to have none, from explicit lists in the test: the words of the widget's author (the names, labels and
847
+ default texts of its settings), typefaces, and stored values that are not words (`center-center`); a test of its own fails
848
+ when a listed word is also a message of the editor, so an allowance cannot hide a missing translation. The calendars are
849
+ checked with a real language instead of marks, because their months and weekdays come from `Intl` and not from a message:
850
+ Polish. With Polish it also checks `messages`, `locale`, `setLanguage` (at once, keeping what it is not told, replacing the
851
+ messages, back to English, with what the visitor typed untouched), the banners that follow a language that comes later,
852
+ that the partner's page is untouched, `defaultMessages`, `checkMessages`, the one console warning, and the `TypeError`s for
853
+ a wrong shape.
854
+
855
+ `e2e/widgetCreatorLanguage.spec.ts` checks the widget creator's words the same way (`harness/widget-creator.html?pseudo=1`:
856
+ every message of `WidgetCreatorModule.defaultMessages` wrapped in marks). It walks the canvas with a widget's shape selected
857
+ (the toolbar, the zoom controls, the properties panel and the pop-up region), the details of the widget (the chat, what it
858
+ sends, the version menu with its dates), the canvas's context menu with a shape selected and with nothing selected, More
859
+ Shapes, the question before a shape is removed (a sentence made of three pieces), the brand kit with its tooltips and hints
860
+ (not the preset **Libraries** section, which debug mode alone draws), a refusal and the pop-up it brings with its close
861
+ button, the moment before the picker, the picker and
862
+ a copy that fails, and fails on any text, label, hint or picture description a visitor can read or hear and that has no
863
+ marks. A short list of things that belong to the page (a hot key, the code of a colour, the name of a version, a unit, the
864
+ typeface "Inter") may have none, and a test of its own fails when one of them is also a message of the creator, so an
865
+ allowance cannot hide a missing translation. With Polish it also checks `messages`, `locale` (the dates of the versions),
866
+ `setLanguage` (at once, keeping what it is not told, replacing the messages, `null`, blank, back to English, and a pseudo
867
+ language that comes later), the picker with `presetLabels` under it, that the partner's page is untouched,
868
+ `defaultMessages`, `checkMessages`, the console warnings once each and by the part that owns the key, and the
869
+ `TypeError`s for a wrong shape. It found English that the creator's own audit of its source could not see (two sentences
870
+ in a JavaScript file), which is why that package now has a test that lists its JavaScript files.
871
+
872
+ `harness/composition-editor.html` is the same kind of page around the composition editor, with a stand-in for the
873
+ gateway's composition routes (`harness/mockCompositions.mjs`) that keeps the rules an editor session meets in production:
874
+ its own managed user's compositions only, a `PUT` only with an `Idempotency-Key`, no routes beyond the ones the editor
875
+ needs. `e2e/compositionEditorModule.spec.ts` edits a composition there (the design and content tabs, the colour, font,
876
+ rich text, time, position, dial, number and date controls, the file picker with Widgetic's uploads and with a library the
877
+ page brings, reordering items) and checks that it autosaves, that another user's composition is refused, that a token
878
+ the API refuses is renewed once, that a session that ended is reported, that `unmount()` saves first, and that a second
879
+ editor is refused. The page-facing half is as strict as the File Browser's: the partner's elements measure the same before
880
+ and after, the page does not move, the page's tree gets nothing but the module's host and its font rules, every
881
+ listener the editor put on the window, document, `<html>` and `<body>` is off again after `unmount()`, nothing is added
882
+ to `window` beyond the registries of the libraries it is made of, the partner's own Google Fonts `<link>` is not touched
883
+ and the editor's own font stylesheets leave with it, the partner's look-alike dialogs, menus and lists are never found
884
+ or changed, a keystroke in the partner's input is neither cancelled nor stopped, and the whole thing works under a strict
885
+ Content-Security-Policy.
886
+
887
+ `harness/widget-creator.html` is the same kind of page around the creator, in front of a stand-in for the gateway's creator
888
+ routes (`harness/mockCreator.mjs`: two managed users with a canvas each, a chat that "builds" a widget in 700 ms, and a
889
+ 501 for the routes it does not imitate). Every request passes `harness/creatorDoor.mjs` first, which holds it to **the
890
+ gateway's own list of what a creator session may call**: `harness/fixtures/editorSessionRoutes.json` is that list as the
891
+ gateway exports it (`npx tsx scripts/exportEditorSessionRoutes.ts --write <file>` in the gateway; the gateway's test pins
892
+ its digest, so the two cannot drift apart unnoticed), with the body fields each route may carry and the things a request
893
+ names that must be the managed user's. `e2e/widgetCreatorModule.spec.ts` opens a canvas there, asks the chat for a change
894
+ and follows what the creator asks the gateway: only listed routes, nothing refused, one generation with its
895
+ `Idempotency-Key`, its progress on the event stream, the first composition saved, and a foreign canvas answered as if it
896
+ did not exist. It draws a rectangle on an empty canvas, turns it into a widget and describes it, and checks that the
897
+ widget is made with the fields a session may write (the first thing a visitor does on a canvas, which once failed at its
898
+ last request). It also checks that the module tells the page what happened (`ready`, `canvasChanged`, `widgetRenamed`
899
+ once, the end of a session), that an expired token is renewed once, and that a second creator is refused. The
900
+ page-facing half is as strict as the editor's, with the same helpers (`e2e/support/hostilePage.ts`): the partner's elements
901
+ measure the same, the listeners the creator put on the window, document, `<html>` and `<body>` are all off after
902
+ `unmount()`, nothing is added to `window` beyond the libraries' registries, nothing goes to the page's storage under another
903
+ name than `widgetic:`, no window is opened and the address bar does not move, the partner's look-alike elements are left
904
+ alone, letters, Backspace and Delete typed into the chat reach the chat and do nothing to the canvas, keys typed or text
905
+ pasted into the partner's own fields are untouched (a Delete pressed on the partner's text does not remove the selected
906
+ shape; the browser's zoom keys are not cancelled), the partner's page is never scrolled, the live previews of the widgets
907
+ are drawn and can be dragged, a token that is refused for good and a canvas that is not the user's are each reported once
908
+ and the creator stops asking, and the whole thing works under a strict Content-Security-Policy. The record of what the
909
+ creator asked (`GET /mock/_creator-requests`) also holds the uploads and compositions it asked for, which the library and
910
+ the composition mock answer, each with the allow-list entry it matched (`route`, `null` when it matched none). The mock
911
+ publishes nothing, so a test that needs a published widget says so: `POST /mock/_config` with `{ publishedWidgets:
912
+ [<widget id>], publishHistory: { <widget id>: [{ version, commitSha, commitTitle?, publishedAt? }] } }`.
913
+
914
+ A test that needs the gateway to refuse says so the same way: `POST /mock/_config` with `{ refusals: [{ route, status,
915
+ code, message?, details?, times?, retryAfter?, user? }] }` makes the harness answer that route (as the allow-list writes
916
+ it, e.g. `POST /agent/code/generate`, or `POST /uploads`) with the gateway's refusal: the standard envelope, the neutral
917
+ sentence a session is told, `Retry-After` when given, for one managed user (`user: 'a'` or `'b'`) or both, a number of
918
+ times or until the list is replaced. The tests under "When a limit is reached" use it to check what the visitor sees and
919
+ what the page is told when the credits are out, the allowance of the hour is used up, the storage is full or an "Upgrade"
920
+ button is pressed (and that ordinary rate limiting is not reported as a limit). They also open the page in two browsers,
921
+ one for each managed user, to check that the two work at once on their own canvases without refusing, telling or showing
922
+ each other anything.
923
+
924
+ `e2e/widgetCreatorDarkMode.spec.ts` checks that the creator can be read in a dark look. It reads every text of the creator
925
+ the way the browser paints it (`e2e/support/contrastProbe.ts`: the colour of the text over what is behind it, through the
926
+ creator's shadow root and the chat's inside it, with an element's opacity and the translucent surfaces in between) and fails,
927
+ naming the texts, on any under 3 to 1, in the states a visitor reaches: the opening screen, a selected widget, the chat with
928
+ a reply made of code, a list, a quote and a table, the shapes menu, the context menu of a shape, the note of a generation the
929
+ gateway refused, a published widget and the properties of an image. It does that for the bare dark mode, each built-in preset
930
+ in its dark mode and neutral colours of a partner's own; a cream page with a brown ink must read about as well as Widgetic's
931
+ own light look (which has quiet labels of its own: the "px" beside a width is about 2.6 to 1). It also checks that the chat's
932
+ code block follows the module and not the visitor's system (a light creator on a system that prefers dark keeps a light
933
+ code block), and that with no theme the toolbar's buttons are exactly the soft grey they always were. With the build step
934
+ that points the greys at the theme switched off, 12 of its 15 tests fail.
935
+
936
+ **The routes, read from the code.** The tests only meet the routes of what they do. `npm run check:creator-routes` reads
937
+ the packages the creator is made of instead (`@widgetic/creator`, `@widgetic/canvas`, `@widgetic/chat`): every
938
+ `.operationName(` of the generated SDK is a call of that operation, and the few `fetch` calls written by hand are listed
939
+ in `scripts/lib/creatorRoutes.mjs`. It fails when a route the creator can call is neither on the gateway's list for a
940
+ creator session nor listed, with the reason, as one a visitor can never reach (sign-in and sign-up, the account's trial
941
+ counter, deleting a composition, the resumable upload), and when a listed reason no longer matches anything, so the list
942
+ cannot go stale. It cannot see a route built from a variable; the end-to-end tests hold the creator to the same list at
943
+ the door, so each covers the other. `npm run check:creator-routes -- --inventory` prints the same as JSON; the gateway
944
+ keeps a copy (`tests/fixtures/creatorRouteInventory.json`, checked by `tests/creatorRouteInventory.test.ts`), so changing
945
+ its list without the creator, or the creator without its list, fails there too. After a new creator release run the
946
+ command, fix what it reports, and refresh the copy:
947
+ `node scripts/creator-routes.mjs --inventory > <api-gateway-service>/tests/fixtures/creatorRouteInventory.json`.
948
+
949
+ ## How a module is built
950
+
951
+ ```
952
+ src/shared/ what every module uses
953
+ shadowMount.ts creates <widgetic-ui-module> + shadow root, the app root, the portal root, the theme switch
954
+ theme/ the look a partner asks for: presets, colour maths, the variables written on both roots (see "Looking like your product")
955
+ tokenSource.ts one in-flight getToken call, refresh ahead of expiry, retry only while the old token is valid
956
+ emitter.ts typed events; a throwing handler never stops the others
957
+ ShadowAwarePortal.svelte replaces the design system's Portal (see "Workarounds")
958
+ src/file-browser/ the module: index.ts (public API), FileBrowserHost.svelte, pickedFile.ts, module.css
959
+ src/composition-editor/ the module: index.ts (public API), CompositionEditorHost.svelte, module.css, tiptapBase.css
960
+ src/widget-creator/ the module: index.ts (public API), WidgetCreatorHost.svelte, module.css
961
+ scripts/build-module.mjs the Vite build; scripts/plugins/* the CSS and package fixes below
962
+ ```
963
+
964
+ `module.css` is compiled once by Tailwind and the build exports it as two strings: `shadowCss` (goes into the shadow
965
+ root) and `documentCss` (the few rules that must live in the page: `@font-face`).
966
+
967
+ ### One file, and the parts that are not in it
968
+
969
+ A module is `index.js`, which has everything the module needs to appear and to work, and the **lazy files** in `chunks/`:
970
+ parts that are heavy and that most visitors never need. Today that is pdf.js (0.46 MB) and its web worker (1.4 MB), for a
971
+ visitor who previews a PDF. `index.js` fetches one the first time it is needed, from the folder it was itself loaded
972
+ from (`import.meta.url`), so the files of a version work wherever that folder is: the CDN, a mirror, a partner's own copy.
973
+
974
+ ```
975
+ dist/file-browser/index.js 1.50 MB everything the File Browser needs to open
976
+ dist/file-browser/chunks/pdf-DyTSsyHP.js 0.46 MB pdf.js, when the first PDF is previewed
977
+ dist/file-browser/chunks/pdfWorker-BGng0wLJ.js 1.38 MB pdf.js's web worker, then too
978
+ ```
979
+
980
+ **Why not let the bundler split the module wherever it can?** Because a browser remembers a module file that failed to
981
+ load, for as long as the page lives. `@widgetic/ui-sdk` gets around that for `index.js`: when it fails it asks again at
982
+ another address (`index.js?retry=1`). But a file that `index.js` imports with `import ... from` has one address, so when
983
+ it fails once, the module can never be loaded in that page, however often the SDK asks. (`e2e/sdkLoader.spec.ts` pins this
984
+ in Chromium, with a module that has such a file.) So the rule, which the build checks and fails on, is:
985
+
986
+ - `index.js` imports nothing statically: a failed fetch of it is the SDK's to retry, as before.
987
+ - every lazy file is a leaf: it imports nothing and loads nothing, so nothing can fail inside it. `index.js` fetches it
988
+ through a small function the build puts at its top, which asks again after 300 ms and after 900 ms, each time at an
989
+ address nobody asked for before (`?retry=<n>`), shares one fetch between two visitors who ask at once, remembers a
990
+ file that loaded, and forgets one that failed so that asking later, when the network is back, starts again.
991
+
992
+ The bundler can only be told "split everything" or "split nothing", so `scripts/lib/lazyParts.mjs` does the choosing: the
993
+ dynamic imports named in `LAZY_IMPORTS` in `scripts/build-module.mjs` stay dynamic and become files, and every other
994
+ dynamic import, in this package and in the packages it bundles, is turned into a static one. (That is why the widget
995
+ creator, whose canvas and details panel are dynamic imports in its own code, is still one file: they are used at once and
996
+ share the Svelte runtime with the rest.)
997
+
998
+ **To make another part lazy**, add its import specifier to `LAZY_IMPORTS`, build, and look at the output. It has to stand
999
+ alone: a part that shares code with the rest of the module would have to import it from another file, and the build fails
1000
+ and says which file imports which. Then update the budget (`scripts/lib/bundleBudget.mjs`). The next candidate is
1001
+ highlight.js (275 kB in the composition editor and the creator): the design system's rich text editor imports `lowlight`
1002
+ statically, so it needs a change there first.
1003
+
1004
+ After a build, `scripts/build-module.mjs` fails when: a file is not `index.js` or `chunks/<name>.js` (the names the CDN's
1005
+ publishing rules accept), a file imports another or a lazy file loads one, a script is in a `data:` URL, or the size is
1006
+ over the budget.
1007
+
1008
+ ### Shadow DOM rules this workspace enforces
1009
+
1010
+ Each one was found by a test against the hostile page; the unit tests in `tests/shadowDomCss.test.mjs` and
1011
+ `tests/shadowMount.test.ts` pin them down.
1012
+
1013
+ 1. **No stylesheet from a package reaches the page.** Packages `import './x.css'` for themselves; those imports are
1014
+ dropped (`scripts/plugins/packageCss.mjs`) and everything comes from the one compiled module stylesheet.
1015
+ 2. **`rem` becomes `px` (1rem = 16px)** in the Tailwind output, in `@media` parameters and in Svelte `<style>` blocks. A
1016
+ partner's `html { font-size: 62.5% }` would otherwise shrink the whole module to 10/16.
1017
+ 3. **`:root` rules apply to `:host` and to `.widgetic-ui-root`.** The design tokens (`--background` ...) are declared
1018
+ on both, so they exist on the host and on every element below it.
1019
+ 4. **`@property` is never registered on the page.** It is global; it is turned into plain defaults (`*, ::before,
1020
+ ::after` for non-inheriting properties, `:host, .widgetic-ui-root` for inheriting ones) inside the shadow root.
1021
+ 5. **`@font-face` goes to the page, once, namespaced.** Fonts cannot be loaded from inside a shadow root. The rules are
1022
+ added to `<head>` once per module version (`data-widgetic-ui-document-rules`), and every family is renamed
1023
+ `Widgetic UI <name>` so it cannot clash with the partner's own `Inter`.
1024
+ 6. **The inheritance firewall.** A partner rule that matches the host element itself (`* { cursor: crosshair }`,
1025
+ `body { text-align: center }`) **beats** any `:host { ... }` rule of the module, and inherited properties flow into the
1026
+ shadow tree. So the first rule of the shadow stylesheet (`@layer widgetic-reset`, lowest priority) is
1027
+ `:host, .widgetic-ui-root { all: initial; visibility: inherit; pointer-events: inherit; display: block }` on the
1028
+ elements *inside* the tree, and the module's typography is declared on `.widgetic-ui-root`. `visibility` and
1029
+ `pointer-events` stay inherited on purpose: a partner that hides an inactive tab with `visibility: hidden`, or locks a
1030
+ region with `pointer-events: none`, must hide or disable the module too. `all` does not reset custom properties
1031
+ (the module declares its own) or `direction` (the root sets `direction: ltr`).
1032
+ 7. **Portals stay inside.** Dialogs, menus and tooltips render into the module's own portal root (`BitsConfig
1033
+ defaultPortalTo`, and `ShadowAwarePortal.svelte` for the design system's `Portal`).
1034
+ 8. **One page footprint.** The module adds one `<widgetic-ui-module>` to its container and, once per module build, one
1035
+ `<style>` with the font rules to `<head>`. Nothing on `<html>` or `<body>`; `unmount()` removes the host (the `<head>`
1036
+ rules stay: they are shared and namespaced). The composition editor's font picker also adds Google's stylesheet for
1037
+ each font it shows to `<head>`; those are tracked and taken away on `unmount()`, and the page's own links are never
1038
+ touched.
1039
+ 9. **Nothing global is searched or styled.** Inside a shadow root `document.querySelector`, `document.activeElement` and
1040
+ an event's `target` on the document are the host or the page's own elements, never the module's. The editor looks
1041
+ things up in its own tree (`@widgetic/editor`'s `src/lib/utils/shadowDom.ts`: `queryInTreeOf`, `activeElementIn`,
1042
+ `isEventInside`),
1043
+ listens for the scrolling of its own panels on the shadow root as well as the window (a `scroll` event does not leave a
1044
+ shadow root), shares one set of scroll listeners per tree, and shows the drag cursor on its host instead of the
1045
+ page's `<body>`.
1046
+
1047
+ A note for anyone writing tests against this: the File Browser's root has `transition: all 300ms`, which keeps
1048
+ `visibility: visible` for 300 ms after an ancestor becomes hidden. Poll; do not read it synchronously.
1049
+
1050
+ ## Workarounds, and when to delete each
1051
+
1052
+ Every one of these is a defect in a published package. Each is guarded (a test or a build error) so it cannot rot.
1053
+
1054
+ | Workaround | Why | Delete when |
1055
+ | --- | --- | --- |
1056
+ | `src/shared/ShadowAwarePortal.svelte` replaces `@widgetic/design-system/dist/components/modals/Portal.svelte` (`scripts/plugins/overrides.mjs`) | The design system's Portal looks its target up in `document` and creates a missing one in the partner's `<body>` | The design system's Portal accepts a target inside a shadow root. The build **fails** when the replaced file no longer exists, so a rename in the package cannot silently bring the bug back |
1057
+ | `scripts/fonts.mjs` drops the design system's `Inter`, `Cousine` and `JetBrains Mono` `@font-face` rules and ships Inter (variable, Latin, OFL-1.1, `@fontsource-variable/inter`) as a data URI | The WOFF2 files in `@widgetic/design-system` 0.5.15 and 0.5.16 are damaged (checked on 2026-10-09): each holds ~40,000 U+FFFD replacement characters and Chrome rejects them (`OTS parsing error`). The design system's own `fonts.css` header says so. Monospace falls back to system fonts. `interFontFaceCss()` fails the build if the replacement is not a sound WOFF2 (`tests/fonts.test.mjs`), and `e2e` asserts the browser accepts every font | `@widgetic/design-system` ships valid font files |
1058
+ | `TIPTAP_INJECTS_NO_STYLE_PATCH` in `scripts/build-module.mjs` (a one-line patch of `@widgetic/design-system`'s `shad-editor.svelte`, `patchPackageFilesPlugin` in `scripts/plugins/overrides.mjs`) turns `injectCSS` off, and `src/composition-editor/tiptapBase.css` plus the design system's `editor.css` (both imported by `module.css`) carry the rich text rules inside the shadow root | Tiptap adds its base rules as a `<style>` to the **page's** `<head>`, where they cannot reach into a shadow root (the rich text boxes then lose `white-space: pre-wrap` and `position: relative`) and where a partner would find them left behind. The design system's `editor.css` is a page stylesheet the module has to ask for, because package CSS imports are dropped | `shad-editor.svelte` passes `injectCSS: false` itself and ships Tiptap's base rules in its `editor.css`. The build **fails** when the line the patch changes is no longer there exactly once, or when no file matches |
1059
+ | `PDF_WORKER_FROM_BLOB_PATCH` in `scripts/build-module.mjs` (a one-line patch of `@widgetic/design-system`'s `PDFViewer.svelte`) makes pdf.js start its worker from `src/shared/pdfWorker.ts`: a `blob:` URL of `pdf.worker.min.mjs`, made in the page the first time a PDF is opened (the worker's text comes from a lazy file, so a visitor who never previews a PDF never downloads it) | The viewer gives pdf.js the worker as `new URL('pdfjs-dist/build/pdf.worker.min.mjs', import.meta.url)`, which a library build turns into a `data:` URL holding the 1.4 MB file. A browser only starts a worker from its own origin, so pdf.js wraps that address in a blob that imports it, and both steps run code from a `data:` URL: a page with a strict policy refuses, and the preview says "Failed to load PDF". With the blob the only thing a policy has to allow is `worker-src blob:`, and the bundle is 0.46 MB smaller (a string is smaller than its base64). The build **fails** if a script is left in a `data:` URL (`scripts/lib/cspChecks.mjs`), and when the line the patch changes is no longer there exactly once | `PDFViewer.svelte` takes the worker (a `workerSrc` or a `workerPort`) as a prop, or makes it from a blob itself |
1060
+ | `dropReferenceAtRulesPlugin` in `scripts/plugins/packageCss.mjs` removes every Tailwind `@reference` from the module stylesheet | The design system's `editor.css` says `@reference '../../styles/global.css'`; Vite flattens `@import`s before PostCSS runs, so that relative path is then resolved from `module.css`'s folder and the build fails. The module stylesheet already contains everything the reference points at | A design system release whose `editor.css` has no `@reference`, or the build resolves it from the right folder |
1061
+ | `scripts/stubs/app-environment.js` stands in for SvelteKit's `$app/environment` | The File Browser imports it | The File Browser stops importing SvelteKit |
1062
+ | `instanceOnPage` in `src/file-browser/index.ts` refuses a second File Browser | The component keeps its file list, its selection and its history in stores that belong to the whole page; two instances would show each other's files and picks | The component keeps them per instance |
1063
+
1064
+ The two `patch-package` patches this table used to list, for `@widgetic/editor` 4.1.0 and `@widgetic/creator` 0.4.0 (R-05a `lockPreviewSize`, R-16 `pickFile`, R-17 `storeFileUrl` and `urlResolver`, R-10 `mediaLibrary.upload` with a `purpose`), are gone: `@widgetic/editor` 4.1.3 and `@widgetic/creator` 0.4.3 ship that behaviour in their published `dist/`, and `tests/creatorPartnerUpload.test.ts` fails if the range allows a creator older than 0.4.3. `patch-package` stays installed and `postinstall` still runs it, so a future patch only needs a file in `patches/` (with none, it prints "No patch files found" and exits cleanly). Give it a row in this table, with the test or build error that guards it.
1065
+
1066
+ ## Known gaps
1067
+
1068
+ These are known, tracked for the File Browser work, and not hidden by the module:
1069
+
1070
+ - **The list of Widgetic uploads is the newest 100.** `GET /uploads` has a `limit` but no cursor yet, so there is no
1071
+ paging for the visitor's own Widgetic files. (A `mediaLibrary` of your own pages through cursors, up to 1,000 files;
1072
+ search and the type filter only look at the files that were loaded.)
1073
+ - **Widgetic uploads cannot be renamed or deleted, and files over 10 MB cannot be uploaded.** The API has no rename or
1074
+ delete call for uploads yet, so the module does not show those buttons (a button that only hid the file on the
1075
+ visitor's own device would be a lie), and an editor session cannot use the resumable (TUS) upload, so a bigger file is
1076
+ refused up front with `MEDIA_LIBRARY_NOT_SUPPORTED` before anything is sent.
1077
+ - **The layout follows the window, not the container.** The File Browser picks mobile, tablet or wide layouts from
1078
+ `window.innerWidth` and `document.querySelector('.widgetic-breakpoints')`, which cannot see into a shadow root, so a
1079
+ container much narrower than the window gets the wide layout.
1080
+ - **The File Browser's stores are page-wide.** The file list, the selection and the history are module-level stores of
1081
+ the component, shared by everything on the page; this is why only one File Browser fits on a page. (Nothing is read
1082
+ from or written to `localStorage`: the module turns that off.)
1083
+ - **Files on another website need CORS for some previews.** Pictures, audio and video are shown without it; the text,
1084
+ PDF and font previews read the file with a script and need `Access-Control-Allow-Origin` on the file's host.
1085
+ - **Words you can change.** The File Browser, the composition editor and the widget creator take `locale` and `messages`
1086
+ (see "Speaking your visitors' language"); what each leaves in English is listed there and under its own known gaps.
1087
+ - **Right to left: what is left out.** The canvas board, the live previews and the code of the widget creator stay left to
1088
+ right on purpose (see "Right to left"), and two small things are open: the weekday names of an Urdu calendar are the
1089
+ short ones, which are whole words (the browser has no one-letter names for Urdu), and the panel of a widget in the
1090
+ creator does not know where the properties panel is. In the File Browser a name in
1091
+ Latin letters inside Arabic text follows the standard bidirectional rules of the browser (a name that starts with a
1092
+ digit or has a hyphen is kept in one piece by the marks described above), the filter menu opens upward and is cut off at
1093
+ the top of a short box in English too, and the folder tree, the Move window, the search window and the list of recent
1094
+ files are laid out the same way as the rest, but no browser test opens them in Arabic yet.
1095
+ - **Pop-ups come with the design system's toaster, and a few of its habits are not yours to change.** The module answers a
1096
+ rename, a delete, a new folder and a pick with a small pop-up in the bottom corner of the box you gave it (the right one, or the left one for a
1097
+ language written right to left; the box, not the window: the host contains them), in the module's theme and in the language of `locale` and `messages`. Your
1098
+ page can neither move nor switch them off yet. (a) The library moves focus to the newest pop-up when the visitor presses
1099
+ **Alt+T** anywhere on the page while one is shown; the region's name says so for a screen reader ("Notifications
1100
+ alt+T"). (b) A pop-up goes away by itself after about three seconds, and the visitor can close it. (c) The library
1101
+ keeps one list of pop-ups for the page, so two File Browsers on one page (already unsupported, see above) would each
1102
+ show every pop-up. They weigh about 57 kB in `index.js` (the File Browser's first load went from 1.44 to 1.50 MB; its
1103
+ budget is 1.60 MB now). Several end-to-end tests ("the pop-ups" in `e2e/fileBrowserModule.spec.ts`, and the pop-up tests
1104
+ of `e2e/fileBrowserLanguage.spec.ts`, which walk them in a pseudo language) keep all this true.
1105
+ - **Strict Content-Security-Policy.** The module's CSS is one inline `<style>` inside the shadow root, and the Svelte
1106
+ components add `<style>` elements of their own next to it, so a page whose `style-src` forbids inline styles blocks them
1107
+ (it needs `'unsafe-inline'`). Constructable stylesheets would remove that for the module's own CSS only, not for the
1108
+ components' styles, so they are not used until the components do the same. The lazy files are scripts from the CDN, the
1109
+ origin `script-src` already names for `index.js`. Fonts are `data:` URIs (`font-src data:`) and previews use `data:` and `blob:` images. Listing, picking, uploading
1110
+ images and previewing a PDF were verified with no violations under the policy in the SDK's README. A PDF preview
1111
+ needs one directive more, `worker-src blob:` (see "Workarounds": the design system's viewer would start pdf.js's
1112
+ worker from a `data:` URL, which no strict policy allows). A file on a server of the partner's own has to be named in
1113
+ `img-src` for its picture and, for a PDF, in `connect-src` too, because pdf.js downloads the PDF with a request (and
1114
+ the server has to allow the page's origin with CORS). The video and audio players were not tried under a policy (they
1115
+ probably need `media-src` for the server the files come from).
1116
+ - **Size.** 1.5 MB (0.4 MB gzip) to open, 3.3 MB (0.9 MB gzip) with the PDF viewer and its worker, which are lazy files
1117
+ fetched when a visitor first previews a PDF. In `index.js` the File Browser itself is 230 kB, its cache layer 155 kB,
1118
+ bits-ui 125 kB, tailwind-merge 115 kB, Svelte 110 kB, tus uploads 70 kB, its message catalog 70 kB, its pop-ups 57 kB,
1119
+ and 0.4 MB of it is CSS and the Inter font. The
1120
+ build holds every module to a budget for both sizes so it cannot grow unnoticed (see "Size budget").
1121
+
1122
+ ### Known gaps of the composition editor
1123
+
1124
+ - **One composition editor per page.** Its file lists, selection and font manager are stores of the whole page, so a
1125
+ second editor would show the first one's files. The second `mount()` is refused with a message that says so.
1126
+ - **Size.** 3.9 MB (0.9 MB gzip) to open, 5.7 MB (1.4 MB gzip) with the PDF viewer: everything the File Browser brings
1127
+ plus the editor itself (420 kB), Tiptap and ProseMirror, and highlight.js (275 kB). Two modules on one page download
1128
+ their shared parts twice.
1129
+ - **A few names on `window`.** The registries of the libraries it is made of: Svelte's version marker (`__svelte`), Bits
1130
+ UI's layer stacks and id counter, and pdf.js's `pdfjsLib` and `pdfjsTestingUtils`, which pdf.js takes even when the
1131
+ page already has its own pdf.js under them. Loading pdf.js only when a PDF is opened, and giving the names back, is open
1132
+ work; the end-to-end test lists the names so a new one cannot appear unnoticed.
1133
+ - **Strict Content-Security-Policy.** Needs what the File Browser needs, and `frame-src https://cdn.widgetic.com` for the
1134
+ preview (the widget's published page, served from the CDN). The font picker also needs
1135
+ `style-src https://fonts.googleapis.com` and `font-src https://fonts.gstatic.com` (and
1136
+ `connect-src https://www.googleapis.com` when you give it a `googleFontsApiKey`). The strict-policy test does not use
1137
+ the font picker.
1138
+ - **Google's fonts keep their plain family names.** A font the visitor looks at is loaded with Google's own stylesheet,
1139
+ whose `@font-face` rules say `Roboto`, not `Widgetic UI Roboto`, because that stylesheet is Google's. While the editor is
1140
+ on the page a page that declares its own `Roboto` shares the name with it; the stylesheets go when the editor does.
1141
+ - **The preview needs a published widget.** A composition whose widget has no published version has no preview page; the API
1142
+ answers 409 `WIDGET_NOT_PUBLISHED` and the editor says so.
1143
+ - **The file picker's pop-ups** are drawn inside the module's shadow root, in its theme and language (`toast.regionLabel`,
1144
+ `toast.closeLabel`, and the File Browser's other `toast.` keys). After a pick the module says "Files selected", not
1145
+ "Added … to the editor".
1146
+ - **Dates follow `locale`.** The date range control and the calendars use `Intl` for how dates are written and how
1147
+ weekday headings read (grapheme-safe, not fixed two-letter cuts; one letter, with the whole name for a screen reader,
1148
+ in a language written right to left). Saved composition values stay structured dates. With
1149
+ `en`, which is also what a page gets without a `locale`, the order is month first (`10/07/26`); the control used to write
1150
+ day first (`DD/MM/YY`) in every language, and `en-GB` gives that order back.
1151
+
1152
+ ### Known gaps of the widget creator
1153
+
1154
+ The creator is the Widgetic app's screen, written for a page that is all its own. The end-to-end spec found a number of
1155
+ things it did to a page that is not, and they are fixed (phase G4 of the partner-editors plan), each with a test that stays:
1156
+ the canvas's shortcuts took the keys typed into the chat (the shadow root hides the chat's text box from
1157
+ `document.activeElement`) and the keys pressed anywhere on your page, the toolbar cancelled the browser's zoom on the whole
1158
+ page, the chat scrolled your page to follow its messages, the canvas library left a `<style>` in your `<head>` and the
1159
+ creator a counter in your `sessionStorage`, menus and pickers closed on every click made inside the shadow root (the
1160
+ canvas's context menu before its items got their click), the text being edited was typed into a hidden text area in
1161
+ your `<body>` (which scrolled your page, and left the keyboard on nothing when the editing ended), drags put their
1162
+ cursor on your `<body>`, a session that could not be renewed or a canvas that is not the user's were never reported
1163
+ (and asked for again and again), and the creator asked for the same canvas a dozen times while it started. The work is
1164
+ in `@widgetic/canvas`, `@widgetic/chat` and `@widgetic/creator`; the design system needed no change, because the module
1165
+ replaces its `Portal` (see "Workarounds").
1166
+
1167
+ What is left:
1168
+
1169
+ - **The fixes are released.** They were in branches of those packages (`feat/embed-in-shadow-root` of the canvas and the
1170
+ chat, `feat/partner-host-mode` of the creator); `package.json` now asks for `@widgetic/canvas` ^0.5.19,
1171
+ `@widgetic/chat` ^0.1.18 and `@widgetic/creator` ^0.4.0, which are on npm, and the lockfile pins them.
1172
+ - **Size.** 6.1 MB (1.4 MB gzip) to open, which is 96% of its 6.3 MB budget, and 7.9 MB (1.9 MB gzip) with the PDF viewer:
1173
+ the creator itself (510 kB), the whole canvas with fabric (370 kB), the chat, the editor's controls and their libraries. The canvas and the details panel
1174
+ stay in `index.js` on purpose: the creator asks for the canvas as soon as it starts, and they share the Svelte runtime
1175
+ and most of the creator, which a lazy file cannot (see "One file, and the parts that are not in it").
1176
+ - **Stop only stops the creator waiting.** The Stop button ends the creator's wait for a generation. The gateway's cancel
1177
+ route is on the creator's list but the creator never calls it, because cancelling only changes a status on the server
1178
+ and stops nothing: the generation, and the credits it uses, run on.
1179
+ - **A chat attachment over 10 MB is refused**, before anything is sent: a session cannot use the resumable (TUS) upload,
1180
+ as in the File Browser.
1181
+ - **No composition steps in a session.** The creator's advanced features (the *Edit* step with a widget's compositions, and
1182
+ the *Embed* step) are off, and a partner's page cannot switch them on: the creator ignores the `widgetic:host-*`
1183
+ events of the Widgetic site's header there. Compositions are edited with the composition editor module.
1184
+ - **Publishing is covered by the gateway's tests, not by the end-to-end ones.** The harness answers 501 for publishing a
1185
+ widget, setting a version live and previewing a version.
1186
+
1187
+ ## Publishing
1188
+
1189
+ Partners' pages load three kinds of file from the CDN (`https://cdn.widgetic.com`, the `widgets` bucket on Cloudflare R2,
1190
+ the one the API gateway writes to), and a fourth is there for the partner to read:
1191
+
1192
+ | File | Rule |
1193
+ | --- | --- |
1194
+ | `modules/<name>/<version>/index.js` | **Never changes once published.** Partners pin versions, and a page must get the same bytes next year. Cached for a year (`immutable`). |
1195
+ | `modules/<name>/<version>/chunks/<file>.js` | The module's lazy files (pdf.js and its worker, see "One file, and the parts that are not in it"), in a folder next to `index.js`, which fetches them from there. The same rule: **never changes once published**, cached for a year (`immutable`). Named after their content (`pdf-DyTSsyHP.js`), and a version carries its own copies, so a file is never shared between versions. |
1196
+ | `modules/<name>/manifest.json` | `{ "name", "version", "entry": "<version>/index.js" }`. What a page that does not pin a version gets. Cached for a minute. Overwritten at every release, as `changelog.json` is: the only two files that ever are. |
1197
+ | `modules/<name>/changelog.json` | What changed in each version, newest first, up to the version the manifest names (see "Versions and the changelog"). Written from `src/<name>/CHANGELOG.md` just before the manifest moves. Cached for a minute. |
1198
+
1199
+ A release is made in one of two ways, and both end in the same rules (`scripts/lib/publishModule.mjs`): **by pushing a
1200
+ tag**, which the pipeline turns into a release ("Releasing from a tag", the normal way), or **by one command run by a
1201
+ person** who has the R2 write keys ("By hand"). The command is how a module's first release is made, how a release
1202
+ candidate or a rollback can be made, and what the pipeline itself runs. Whoever can publish can run code on every
1203
+ partner's page, so neither way is open to everyone: "What to set up once" says who can push the tag and who can see the keys.
1204
+
1205
+ ### Releasing from a tag
1206
+
1207
+ Every module is released at the one version in `package.json`, and each one needs an entry for that version in its
1208
+ `src/<name>/CHANGELOG.md` ("Versions and the changelog", below): a version that says nothing about what it changed is not
1209
+ released. To release them:
1210
+
1211
+ ```bash
1212
+ cd Frontend/ui-sdk/modules
1213
+ # first, add the entry for <x.y.z> to src/file-browser/, src/composition-editor/ and src/widget-creator/CHANGELOG.md
1214
+ npm version <x.y.z> --no-git-tag-version # the version in package.json is the version that gets published
1215
+ git commit -am "Modules <x.y.z>" # merged into main the way every change is
1216
+ git switch main && git pull
1217
+ git tag modules-v<x.y.z> && git push origin modules-v<x.y.z>
1218
+ ```
1219
+
1220
+ The tag starts a pipeline (`Frontend/ui-sdk/.gitlab-ci.yml`). Nothing else does: a push to a branch and a merge request
1221
+ make no pipeline, so the CDN never changes because someone merged. A tag whose name is not `modules-v<version>` makes no
1222
+ pipeline either, so if nothing started, check the name first.
1223
+
1224
+ - **`verify`** holds no key. It refuses a tag that is not protected, a commit that is not on the default branch, a tag
1225
+ whose version is not the one in `package.json`, a lockfile the pipeline cannot install, and a module whose changelog
1226
+ has no entry for the version. Then it runs the typecheck, the unit tests and the build with its size budgets. It does
1227
+ not run the browser tests (`npm run test:e2e`, which need browsers): run them before you tag.
1228
+ - **`publish`** is the only job that sees the keys. It releases **every module in `dist/`** in three passes
1229
+ (`scripts/release-modules.mjs`, which runs the commands of "By hand" for each module):
1230
+ 1. *ask*: `--dry-run --skip-build`. It reads the CDN and refuses, before anything is written, a version that is already
1231
+ there with other bytes and a module that has no manifest yet.
1232
+ 2. *write*: `--yes --skip-build --skip-manifest`. The files of every module, each checked at its public address. No
1233
+ manifest has moved, so nobody who follows the manifests has changed yet.
1234
+ 3. *switch*: `--yes --manifest-only`. Only now do the manifests name the version, one after the other, when every file
1235
+ of the release is there. For each module the `changelog.json` is written and checked first, then the manifest
1236
+ moves.
1237
+ - **A release candidate** (`modules-v1.3.0-rc.1`, with `1.3.0-rc.1` in `package.json`) stops after pass 2: its files are on
1238
+ the CDN for a partner who pins that version, and no manifest names it.
1239
+ - **When it fails**, the log says what the CDN holds and what to do. Run the `publish` job again from the pipeline page
1240
+ once the cause is fixed (a CORS rule, say): the files already there are recognised and the manifests that already name
1241
+ the version are left alone. A version already on the CDN with other bytes is never overwritten: raise the version.
1242
+ - **The pipeline never makes a module's first release.** It passes no `--allow-create`, so a module that has no manifest
1243
+ is refused in pass 1, and a new or misspelt module name cannot appear on the CDN because a tag was pushed.
1244
+ - The manifest a release replaces is saved before the new one is written, and the job keeps it as an artifact
1245
+ (`modules/.cdn-backups/`, 30 days): it is the way back.
1246
+ - `npm run release:check -- --tag modules-v<x.y.z>` runs the tag, lockfile and changelog checks on your machine, and
1247
+ prints the breaking changes the release announces. It needs no keys and no installed package, and writes nothing.
1248
+
1249
+ #### Versions and the changelog
1250
+
1251
+ A published version never changes, so a partner can stay on the one they tested (`mountModule('file-browser', { version:
1252
+ '1.2.0' })`) and move when they choose; a partner who gives no `version` follows the manifest and gets every release as it
1253
+ happens. What lets them choose is knowing what each version changed, so **a version is not released without saying so**:
1254
+
1255
+ - Every module keeps a `src/<name>/CHANGELOG.md`, newest version first. The modules share the one version of
1256
+ `package.json`, so each release needs an entry in each of them (for a module that did not change, one sentence that
1257
+ says so).
1258
+ - An entry starts with `## <version> - <YYYY-MM-DD>`, may have a paragraph about the release, and then lists under
1259
+ `### Breaking`, `### Added`, `### Changed`, `### Deprecated`, `### Removed`, `### Fixed` and `### Security`, each item
1260
+ starting with `- ` (only the lists it needs). Work that is not released yet goes under `## Unreleased`, which is neither
1261
+ read nor published. A release candidate may be listed under its own version or under the one it leads to.
1262
+ - A version with no entry is refused, by `npm run release:check` and the `verify` job, by the release before it reads the
1263
+ CDN, and by `publish:cdn` before it builds. So is a file that cannot be read (the message says which line), and **a
1264
+ version that lists breaking changes without being a new major version** (a new minor one while the major is 0). The
1265
+ breaking items are printed in the log of the check and of the release, for whoever releases.
1266
+ - The release publishes `modules/<name>/changelog.json`, made from the file, **before** the manifest moves (nobody is
1267
+ pointed at a version whose changes cannot be read yet) and with only the versions up to the one released:
1268
+
1269
+ ```json
1270
+ { "name": "file-browser", "format": 1, "versions": [ { "version": "1.2.0", "date": "2026-10-20", "breaking": false,
1271
+ "summary": "…", "changes": { "breaking": [], "added": ["…"], "changed": [], "deprecated": [], "removed": [], "fixed": [], "security": [] } } ] }
1272
+ ```
1273
+
1274
+ Newest first, every list always present. A release candidate publishes none (it moves no manifest), and a rollback
1275
+ (`--manifest-only --version <earlier>`) leaves it as it is: the versions after the one the manifest names are still
1276
+ published, so a partner who is on one of them can still read what it changed. It is replaced whenever the file says
1277
+ something else: a mistake in an entry is corrected by committing the fix and running `npm run publish:cdn --
1278
+ <name>` again, which finds everything else in place and writes only the changelog.
1279
+ - The partner's side of this, how to pin a version and where to read what changed, is the page `docs/partners/module-versions`
1280
+ of the docs site.
1281
+
1282
+ #### What to set up once
1283
+
1284
+ By a person who can change the project's settings in GitLab.
1285
+
1286
+ 1. **Protect the tag pattern `modules-v*`** (Settings, Repository, Protected tags; allowed to create: Maintainers).
1287
+ `verify` refuses a tag that is not protected, and the keys below reach only a protected tag.
1288
+ 2. **The keys, as CI/CD variables** (Settings, CI/CD, Variables): `CLOUDFLARE_PUBLIC_ENDPOINT`, `R2_WIDGETS_NAME`,
1289
+ `R2_ACCESS_KEY_ID` and `R2_SECRET_ACCESS_KEY` (the same settings as under "By hand"). Each one **Protected**, with the
1290
+ environment scope **`cdn`** (the `publish` job is the only one that runs in that environment), and the two secrets
1291
+ **Masked**. Use an R2 token of its own, limited to the `widgets` bucket with object read and write, so that it can be
1292
+ rotated without touching the gateway's.
1293
+ 3. **Keep `main` reviewed.** A tag must be on `main`, and whoever can change `.gitlab-ci.yml` or `modules/` on `main`
1294
+ changes what the next release does: protect the branch the way the project's others are.
1295
+ 4. **A lockfile the pipeline can install.** `npm ci` installs exactly what `package-lock.json` lists, from the registry.
1296
+ Release the `@widgetic/*` packages the modules are built from first, then run `npm install` in `modules/` once and
1297
+ commit the lockfile. `npm run release:check` says what is missing, and `verify` stops at its first step when the
1298
+ lockfile cannot be installed, which is where it should. (Done on 2026-10-09: every package is released, the ranges
1299
+ in `package.json` ask for them and `npm run release:check -- --tag modules-v0.1.0` passes.)
1300
+ 5. **The first release of every module is made by hand,** with `--allow-create` (below).
1301
+
1302
+ ### The first release, in order
1303
+
1304
+ The pipeline never makes a module's first release, so the first one is made by a person, once. These are the steps in the
1305
+ order they have to be done, because each one checks the one before it. They need your credentials, so nobody else can do
1306
+ them for you. State on 2026-10-09: the packages are released, the lockfile is committed, `npm run release:check` passes
1307
+ and the build is inside its budgets; none of the steps below has been done, and every manifest answers 404.
1308
+
1309
+ 1. **Put the work on `main`.** `publish:cdn` refuses a `modules/` with uncommitted changes, and a release has to come
1310
+ from a commit that is on the default branch.
1311
+ 2. **Give the command the R2 keys.** The four names are the API gateway's own, so the values are in its Doppler config.
1312
+ Use an R2 token of its own, limited to the `widgets` bucket with object read and write, and keep the file out of git
1313
+ (`modules/.env` is ignored):
1314
+
1315
+ ```bash
1316
+ cd Frontend/ui-sdk/modules
1317
+ cat > .env <<'EOF'
1318
+ CLOUDFLARE_PUBLIC_ENDPOINT=...
1319
+ R2_WIDGETS_NAME=...
1320
+ R2_ACCESS_KEY_ID=...
1321
+ R2_SECRET_ACCESS_KEY=...
1322
+ EOF
1323
+ ```
1324
+
1325
+ 3. **Look at CORS before you write anything.** A page on another origin `import()`s the module and `fetch`es its manifest,
1326
+ so the CDN must answer `Access-Control-Allow-Origin: *` for `modules/*`. On 2026-10-09 it already does, even for the
1327
+ 404 of a manifest that does not exist yet, and for `sdks/browser/embed-sdk.js`:
1328
+
1329
+ ```bash
1330
+ curl -s -D - -o /dev/null -H 'Origin: https://example.com' https://cdn.widgetic.com/modules/file-browser/manifest.json | grep -i '^access-control'
1331
+ ```
1332
+
1333
+ If that prints nothing, add a CORS rule to the `widgets` bucket (Cloudflare dashboard, R2, the bucket, Settings, CORS
1334
+ policy) before step 5:
1335
+
1336
+ ```json
1337
+ [{ "AllowedOrigins": ["*"], "AllowedMethods": ["GET", "HEAD"], "AllowedHeaders": ["*"], "MaxAgeSeconds": 86400 }]
1338
+ ```
1339
+
1340
+ 4. **Build once, from a clean install, and publish from what you built.** A build on another machine can differ by a
1341
+ byte, and a published version is never overwritten, so every command below uses the same `dist/`:
1342
+
1343
+ ```bash
1344
+ cd Frontend/ui-sdk/modules
1345
+ npm ci
1346
+ npm run build # every module against its size budget
1347
+ npm run release:check -- --tag modules-v0.1.0
1348
+ ```
1349
+
1350
+ 5. **Dry run, then publish, one module at a time.** A dry run of a module with no manifest needs `--allow-create` too: it
1351
+ shows the plan and writes nothing. The real run asks you to type `publish`:
1352
+
1353
+ ```bash
1354
+ for module in file-browser composition-editor widget-creator; do
1355
+ npm run publish:cdn -- "$module" --skip-build --allow-create --dry-run
1356
+ done
1357
+ for module in file-browser composition-editor widget-creator; do
1358
+ npm run publish:cdn -- "$module" --skip-build --allow-create
1359
+ done
1360
+ ```
1361
+
1362
+ If a step stops (a missing CORS header, a file that did not arrive), fix the cause and run the same command again: the
1363
+ files already there are recognised, and the manifest has not moved.
1364
+
1365
+ 6. **Look at what a partner's page gets:**
1366
+
1367
+ ```bash
1368
+ for module in file-browser composition-editor widget-creator; do
1369
+ curl -s "https://cdn.widgetic.com/modules/$module/manifest.json"; echo
1370
+ done
1371
+ ```
1372
+
1373
+ Each answers `{ "name", "version": "0.1.0", "entry": "0.1.0/index.js" }`. Then open any page that calls
1374
+ `mountModule('file-browser', ...)` from `@widgetic/ui-sdk` (the SDK's own demo does), with no `version` pinned, and
1375
+ check that it no longer fails with `MODULE_NOT_FOUND`.
1376
+
1377
+ 7. **Set up the pipeline, so every later release is a tag.** In GitLab (`widgeticai/Frontend/ui-sdk`): protect the tag
1378
+ pattern `modules-v*` (Settings, Repository, Protected tags, allowed to create: Maintainers) and add the four variables
1379
+ of step 2 (Settings, CI/CD, Variables), each **Protected** with the environment scope **`cdn`**, and the two secrets
1380
+ **Masked**. The same with the GitLab API, with a token that has the `api` scope:
1381
+
1382
+ ```bash
1383
+ export GITLAB_TOKEN=... # a personal access token with the api scope
1384
+ export PROJECT='widgeticai%2FFrontend%2Fui-sdk'
1385
+ curl --request POST --header "PRIVATE-TOKEN: $GITLAB_TOKEN" \
1386
+ "https://gitlab.com/api/v4/projects/$PROJECT/protected_tags" --form 'name=modules-v*' --form 'create_access_level=40'
1387
+ set -a; . ./.env; set +a
1388
+ for name in CLOUDFLARE_PUBLIC_ENDPOINT R2_WIDGETS_NAME R2_ACCESS_KEY_ID R2_SECRET_ACCESS_KEY; do
1389
+ masked=false; case "$name" in R2_ACCESS_KEY_ID|R2_SECRET_ACCESS_KEY) masked=true;; esac
1390
+ curl --request POST --header "PRIVATE-TOKEN: $GITLAB_TOKEN" "https://gitlab.com/api/v4/projects/$PROJECT/variables" \
1391
+ --form "key=$name" --form "value=${!name}" --form 'protected=true' --form "masked=$masked" --form 'environment_scope=cdn'
1392
+ done
1393
+ ```
1394
+
1395
+ (`${!name}` is bash. In zsh write `${(P)name}`.)
1396
+
1397
+ 8. **The next release goes by tag and proves the pipeline:** `npm version 0.1.1 --no-git-tag-version`, commit, merge,
1398
+ `git tag modules-v0.1.1 && git push origin modules-v0.1.1`.
1399
+
1400
+ Publish the modules **before** a `@widgetic/ui-sdk` version whose defaults point at them: `@widgetic/ui-sdk` 0.1.1 is on
1401
+ npm already, and until step 5 is done its `mountModule` fails with `MODULE_NOT_FOUND`.
1402
+
1403
+ ### By hand
1404
+
1405
+ ```bash
1406
+ cd Frontend/ui-sdk/modules
1407
+ npm version <x.y.z> --no-git-tag-version # the version in package.json is the version that gets published
1408
+ git commit -am "File Browser module <x.y.z>" # a modules/ with uncommitted changes is refused (--allow-dirty)
1409
+ npm run publish:cdn -- file-browser --dry-run # builds, checks, compares with the CDN; writes nothing
1410
+ npm run publish:cdn -- file-browser # shows the plan and asks you to type "publish"
1411
+ ```
1412
+
1413
+ What it does, in this order (`scripts/lib/publishModule.mjs` holds the rules, with tests):
1414
+
1415
+ 1. Builds `dist/<name>/` (`--skip-build` uses what is there) and refuses a build that has a file the CDN has no rule
1416
+ for (only `index.js` and `chunks/<name>.js`, and their source maps, are published), a file that is tiny, or one that
1417
+ contains an R2 key, the Cloudflare token, or any secret-looking value from the `.env` files around it.
1418
+ 2. Reads the bucket and **refuses before writing anything** if this version is already there with other bytes in any of
1419
+ its files (raise the version), if the manifest would point at a version that is not there, or if the module has no
1420
+ manifest yet and you did not say `--allow-create`.
1421
+ 3. Shows the plan; `--dry-run` stops here. Otherwise it asks (`--yes` skips the question and is required outside a terminal).
1422
+ 4. Writes the version's files, **the lazy files first and `index.js` last**: a page that pins the version can only find
1423
+ `index.js` when everything it fetches is already there, so a version that has `index.js` is complete. Then it asks
1424
+ the **public** address of every file the way a partner's page would (from another origin) and checks the bytes, a
1425
+ JavaScript content type and `Access-Control-Allow-Origin`. A CDN can lag behind a write, so it retries for a few
1426
+ seconds. **If anything is wrong it stops; the manifest has not been touched.**
1427
+ 5. Saves the manifest it is about to replace in `.cdn-backups/` (git-ignored), writes the new one, and checks it the same
1428
+ way. With `--purge` it then purges that one address from Cloudflare's cache; otherwise everyone has it within a minute.
1429
+
1430
+ **Running it again is safe.** If step 4 fails (say the CORS rule is missing), the version's files are already on the CDN
1431
+ and the manifest still names the old version. Fix the cause and run the same command: the build is byte-for-byte
1432
+ reproducible (two builds on one machine give the same SHA-256 for every file), so the files are recognised as already
1433
+ published rather than refused as a conflict, and only the missing steps are done (a run that stopped after some of the
1434
+ lazy files and before `index.js` is completed the same way). A rebuild on a different machine may differ; if it
1435
+ reports "different bytes", run with `--skip-build` from the `dist/` you published from, or raise the version.
1436
+
1437
+ Each file ends with a `//# sourceMappingURL=<file>.map` comment (`index.js.map`, `chunks/pdf-DyTSsyHP.js.map`). Without
1438
+ `--with-source-map` those files are not on the CDN, so a browser's DevTools (and only DevTools) shows a 404 for them;
1439
+ nothing else is affected.
1440
+
1441
+ The settings are the API gateway's own names, so the same values work: `CLOUDFLARE_PUBLIC_ENDPOINT`, `R2_WIDGETS_NAME`,
1442
+ `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY` (and `CLOUDFLARE_API_TOKEN` + `CLOUDFLARE_ZONE_ID` for `--purge`). The real
1443
+ environment wins over `modules/.env` (git-ignored, or `--env-file <path>`). Nothing prints them.
1444
+
1445
+ | I want to | Run (after `npm run publish:cdn --`) |
1446
+ | --- | --- |
1447
+ | make the first release of a module | `file-browser --allow-create` |
1448
+ | try a version before everyone gets it | `file-browser --skip-manifest`, then mount it with `version: '<x.y.z>'`; later `file-browser --manifest-only --version <x.y.z>` |
1449
+ | roll back | `file-browser --manifest-only --version <earlier>`. The earlier file is still there; only the manifest changes |
1450
+ | publish the source map too | `file-browser --with-source-map` (off by default) |
1451
+
1452
+ **Prerequisite: CORS on the CDN.** A page on another origin `import()`s the module and `fetch`es the manifest, so the CDN
1453
+ must answer `Access-Control-Allow-Origin: *` for `modules/*` (an R2 bucket CORS rule allowing `GET` from any origin, or
1454
+ a Cloudflare response-header rule for `/modules/*`). Step 4 checks it and stops before the manifest if it is missing, but
1455
+ only a real publish can: a dry run has nothing on the CDN to ask.
1456
+
1457
+ Publish a module **before** the `@widgetic/ui-sdk` version whose defaults point at it: the SDK looks at
1458
+ `https://cdn.widgetic.com/modules`, which has nothing in it until the first release.
1459
+
1460
+ ## Not done yet
1461
+
1462
+ - The first release of the three modules. Everything they are built from is released (checked on 2026-10-09:
1463
+ `@widgetic/design-system` 0.5.16, `@widgetic/file-browser` 0.5.26, `@widgetic/canvas` 0.5.19, `@widgetic/chat` 0.1.18,
1464
+ `@widgetic/creator` 0.4.0, `@widgetic/editor` 4.1.0), `package.json` asks for them and the lockfile pins them, so
1465
+ `npm run release:check` passes and `npm ci` can recreate `node_modules`. What is left is done by a person with the keys,
1466
+ in this order: the CORS rule on `modules/*`, the GitLab protected tag and the four variables, then the first release of
1467
+ each module with `--allow-create` ("Publishing", "What to set up once" and "By hand"). Until then
1468
+ `https://cdn.widgetic.com/modules/<name>/manifest.json` answers 404.
1469
+ - The composition editor on the Widgetic site itself: the site still has its own copy of the editor screen; it moves to
1470
+ the shared `CompositionEditorApp` the module uses.
1471
+ - More lazy files. pdf.js and its worker are done; highlight.js (275 kB, in the composition editor and the creator) is
1472
+ the next, and needs the design system's editor to import it when a code block is used. After that the size is the
1473
+ editors themselves (see "Known gaps", "Size").
1474
+ - One version for the whole workspace (`package.json`): every module is published at it. When a second module ships,
1475
+ decide whether modules are versioned on their own (`publish:cdn` would read the version from the module's folder).
1476
+
1477
+ ## Adding a module
1478
+
1479
+ 1. Create `src/<name>/` with `index.ts` (a class extending `ModuleEmitter`, using `TokenSource` and `createShadowMount`),
1480
+ a host `.svelte` file and a `module.css` that imports the design-system styles and sets `@source` for the package's
1481
+ components.
1482
+ 2. Register it in `MODULES` in `scripts/build-module.mjs`, build it, and give it a size budget in
1483
+ `scripts/lib/bundleBudget.mjs` a little above what it weighs, for the first load and for the module with its lazy files
1484
+ (see "Size budget"): a module with no budget fails the build. If it has a heavy part that few visitors need, see
1485
+ "One file, and the parts that are not in it" before adding it to `LAZY_IMPORTS`.
1486
+ 3. Add a harness page, an end-to-end spec on the hostile page, and unit tests for anything with logic.
1487
+ 4. Anything a package does that cannot work inside a shadow root goes into "Workarounds" above with its removal
1488
+ condition, never into the partner's page.