@widgetic/ui-sdk 0.0.0-stage → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +725 -2
- package/dist/index.d.ts +53 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.esm.js +2525 -0
- package/dist/index.esm.js.map +1 -0
- package/dist/index.js +2559 -0
- package/dist/index.js.map +1 -0
- package/dist/sdk/core/component.d.ts +47 -0
- package/dist/sdk/core/component.d.ts.map +1 -0
- package/dist/sdk/core/events.d.ts +26 -0
- package/dist/sdk/core/events.d.ts.map +1 -0
- package/dist/sdk/core/index.d.ts +33 -0
- package/dist/sdk/core/index.d.ts.map +1 -0
- package/dist/sdk/core/lifecycle.d.ts +97 -0
- package/dist/sdk/core/lifecycle.d.ts.map +1 -0
- package/dist/sdk/core/local-events.d.ts +25 -0
- package/dist/sdk/core/local-events.d.ts.map +1 -0
- package/dist/sdk/core/messaging.d.ts +58 -0
- package/dist/sdk/core/messaging.d.ts.map +1 -0
- package/dist/sdk/core/state.d.ts +58 -0
- package/dist/sdk/core/state.d.ts.map +1 -0
- package/dist/sdk/core/theme-mode.d.ts +44 -0
- package/dist/sdk/core/theme-mode.d.ts.map +1 -0
- package/dist/sdk/core/theme.d.ts +58 -0
- package/dist/sdk/core/theme.d.ts.map +1 -0
- package/dist/sdk/index.d.ts +4 -0
- package/dist/sdk/index.d.ts.map +1 -0
- package/dist/sdk/integration/host.d.ts +54 -0
- package/dist/sdk/integration/host.d.ts.map +1 -0
- package/dist/sdk/integration/index.d.ts +19 -0
- package/dist/sdk/integration/index.d.ts.map +1 -0
- package/dist/sdk/layers/index.d.ts +36 -0
- package/dist/sdk/layers/index.d.ts.map +1 -0
- package/dist/sdk/loader/ui.d.ts +165 -0
- package/dist/sdk/loader/ui.d.ts.map +1 -0
- package/dist/sdk/modules/index.d.ts +9 -0
- package/dist/sdk/modules/index.d.ts.map +1 -0
- package/dist/sdk/modules/loader.d.ts +84 -0
- package/dist/sdk/modules/loader.d.ts.map +1 -0
- package/dist/sdk/types/component.d.ts +177 -0
- package/dist/sdk/types/component.d.ts.map +1 -0
- package/dist/sdk/types/events.d.ts +112 -0
- package/dist/sdk/types/events.d.ts.map +1 -0
- package/dist/sdk/types/index.d.ts +42 -0
- package/dist/sdk/types/index.d.ts.map +1 -0
- package/dist/sdk/types/messaging.d.ts +41 -0
- package/dist/sdk/types/messaging.d.ts.map +1 -0
- package/dist/sdk/types/module-language.d.ts +45 -0
- package/dist/sdk/types/module-language.d.ts.map +1 -0
- package/dist/sdk/types/module-theme.d.ts +93 -0
- package/dist/sdk/types/module-theme.d.ts.map +1 -0
- package/dist/sdk/types/state.d.ts +38 -0
- package/dist/sdk/types/state.d.ts.map +1 -0
- package/dist/sdk/types/theme.d.ts +76 -0
- package/dist/sdk/types/theme.d.ts.map +1 -0
- package/dist/sdk/utils/config.d.ts +70 -0
- package/dist/sdk/utils/config.d.ts.map +1 -0
- package/dist/sdk/utils/errors.d.ts +56 -0
- package/dist/sdk/utils/errors.d.ts.map +1 -0
- package/dist/sdk/utils/http.d.ts +21 -0
- package/dist/sdk/utils/http.d.ts.map +1 -0
- package/dist/sdk/utils/security.d.ts +95 -0
- package/dist/sdk/utils/security.d.ts.map +1 -0
- package/dist/sdk/utils/validation.d.ts +64 -0
- package/dist/sdk/utils/validation.d.ts.map +1 -0
- package/dist/sdk/version.d.ts +8 -0
- package/dist/sdk/version.d.ts.map +1 -0
- package/dist/services/dataService.d.ts +10 -0
- package/dist/services/dataService.d.ts.map +1 -0
- package/dist/umd/ui-sdk.js +2 -0
- package/dist/umd/ui-sdk.js.map +1 -0
- package/dist/utils/caseConversion.d.ts +3 -0
- package/dist/utils/caseConversion.d.ts.map +1 -0
- package/package.json +91 -4
package/README.md
CHANGED
|
@@ -1,3 +1,726 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @widgetic/ui-sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Put Widgetic's ready-made pieces into your own web page with a few lines of code. Today that is the **File Browser**
|
|
4
|
+
(let your users pick and upload files in their Widgetic media library), the **composition editor** (let them change
|
|
5
|
+
the settings of a widget they own, beside a live preview) and the **widget creator** (Widgetic's whole canvas: let them
|
|
6
|
+
draw, describe a widget to the AI, watch it being built and publish it).
|
|
7
|
+
|
|
8
|
+
[](https://www.npmjs.com/package/@widgetic/ui-sdk)
|
|
9
|
+
[](https://opensource.org/licenses/MIT)
|
|
10
|
+
|
|
11
|
+
- **No API key in the browser.** Your server keeps the key and mints a short-lived *editor session* for one of your
|
|
12
|
+
users. The page only ever holds that session's token.
|
|
13
|
+
- **Your page stays yours.** A module draws inside a shadow root: your CSS cannot restyle it and its CSS cannot touch
|
|
14
|
+
your page. The SDK writes nothing to `<html>` or `<body>`, sends no `postMessage` and never clears your container.
|
|
15
|
+
- **Small.** This package is a loader of about 30 KB (minified). A module is downloaded from the Widgetic CDN when you
|
|
16
|
+
mount it, and only then.
|
|
17
|
+
|
|
18
|
+
## How it works
|
|
19
|
+
|
|
20
|
+
1. **Your server** asks Widgetic for an editor session for the user who is on the page
|
|
21
|
+
(`POST /v1/managed-users/{id}/editor-sessions`, authenticated with your API key) and returns the `token`.
|
|
22
|
+
2. **Your page** gives the SDK a `getToken` function that fetches that token from your server.
|
|
23
|
+
3. **The SDK** downloads the module, mounts it in your container, and calls `getToken` when the module starts and again
|
|
24
|
+
shortly before the token expires. The module talks to the Widgetic API with that token and nothing else.
|
|
25
|
+
|
|
26
|
+
### 1. On your server: mint an editor session
|
|
27
|
+
|
|
28
|
+
```js
|
|
29
|
+
// Express. WIDGETIC_API_KEY lives in your server's environment and goes nowhere else.
|
|
30
|
+
app.post('/widgetic-session', requireLoggedInUser, async (request, response) => {
|
|
31
|
+
const widgeticManagedUserId = await lookUpWidgeticIdOf(request.user); // the managed user you created for them
|
|
32
|
+
|
|
33
|
+
const widgetic = await fetch(`https://api.widgetic.com/v1/managed-users/${widgeticManagedUserId}/editor-sessions`, {
|
|
34
|
+
method: 'POST',
|
|
35
|
+
headers: { Authorization: `Bearer ${process.env.WIDGETIC_API_KEY}`, 'Content-Type': 'application/json' },
|
|
36
|
+
body: JSON.stringify({
|
|
37
|
+
surfaces: ['files'], // what the session may do: 'files' (media library), 'editor' (edit a composition), 'creator' (the widget creator)
|
|
38
|
+
expires_in_seconds: 3600, // 60 to 14400
|
|
39
|
+
allowed_origin: 'https://app.example.com', // optional: refuse the token from any other web page
|
|
40
|
+
}),
|
|
41
|
+
});
|
|
42
|
+
if (!widgetic.ok) return response.status(502).json({ error: 'Could not start a Widgetic session' });
|
|
43
|
+
|
|
44
|
+
const { data: session } = await widgetic.json(); // every answer of the API is { success, data }
|
|
45
|
+
response.set('Cache-Control', 'no-store').json({ token: session.token, expiresAt: session.expiresAt });
|
|
46
|
+
});
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### 2. On your page: mount the module
|
|
50
|
+
|
|
51
|
+
```js
|
|
52
|
+
import { mountModule } from '@widgetic/ui-sdk';
|
|
53
|
+
|
|
54
|
+
const fileBrowser = await mountModule('file-browser', {
|
|
55
|
+
container: document.querySelector('#media-library'), // an element, or a CSS selector
|
|
56
|
+
getToken: async () => (await fetch('/widgetic-session', { method: 'POST' })).json(), // { token, expiresAt }
|
|
57
|
+
maxSelections: 1,
|
|
58
|
+
on: {
|
|
59
|
+
select: ({ files }) => useFiles(files), // [{ id, name, url, mimeType?, size?, thumbnail? }]
|
|
60
|
+
},
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
// later:
|
|
64
|
+
await fileBrowser.unmount();
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Give the container a height; the module fills it.
|
|
68
|
+
|
|
69
|
+
## Install
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
npm install @widgetic/ui-sdk
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
With a script tag (pin the version; do not use `@latest`):
|
|
76
|
+
|
|
77
|
+
```html
|
|
78
|
+
<script src="https://unpkg.com/@widgetic/ui-sdk@0.1.0/dist/umd/ui-sdk.js"></script>
|
|
79
|
+
<script>
|
|
80
|
+
WidgeticUISDK.mountModule('file-browser', {
|
|
81
|
+
container: '#media-library',
|
|
82
|
+
getToken: () => fetch('/widgetic-session', { method: 'POST' }).then((response) => response.json()),
|
|
83
|
+
on: { select: ({ files }) => console.log(files) },
|
|
84
|
+
});
|
|
85
|
+
</script>
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
The package ships ES modules (`dist/index.esm.js`), CommonJS (`dist/index.js`) and a UMD file that adds one global,
|
|
89
|
+
`WidgeticUISDK`.
|
|
90
|
+
|
|
91
|
+
## `mountModule(name, options)`
|
|
92
|
+
|
|
93
|
+
Mounts one module and resolves with a handle once it is on screen.
|
|
94
|
+
|
|
95
|
+
| Option | Type | |
|
|
96
|
+
| --- | --- | --- |
|
|
97
|
+
| `container` | `HTMLElement` or CSS selector | **Required.** Where the module is drawn. |
|
|
98
|
+
| `getToken` | `({ reason }) => Promise<string \| { token, expiresAt }>` | **Required to show the visitor's Widgetic data.** Not needed when the module is given its data by your page: the File Browser with your own [`mediaLibrary`](#showing-your-own-media-library). See [Tokens](#tokens). |
|
|
99
|
+
| `version` | `string` | Pin an exact module version such as `1.2.0`. Default: the newest. |
|
|
100
|
+
| `theme` | `'light' \| 'dark' \| 'system'`, or `{ preset, mode, colors, radius, font }` | Default `light`. `system` follows the visitor's setting. An object gives the module your colours, corner radius and font: see [Looking like your product](#looking-like-your-product). |
|
|
101
|
+
| `locale` | `string` | A BCP 47 tag such as `en` or `de`. Every module uses it for plural rules and for how numbers, dates and sizes are written; their words come from `messages`. See [Speaking your visitors' language](#speaking-your-visitors-language). |
|
|
102
|
+
| `apiUrl` | `string` | The Widgetic API. Default `https://api.widgetic.com`. |
|
|
103
|
+
| `moduleBaseUrl` | `string` | Where modules are served from. Default `https://cdn.widgetic.com/modules`. |
|
|
104
|
+
| `on` | `{ [event]: handler }` | Event handlers, connected before the module starts so you see `ready`. |
|
|
105
|
+
| `callbacks` | `{ onReady, onError }` | The same two events as plain callbacks. |
|
|
106
|
+
| `signal` | `AbortSignal` | Cancels the mount. See [Cancelling](#cancelling-a-mount). |
|
|
107
|
+
| `placeholder` | `boolean` | `false` skips the loading spinner shown while the module downloads. |
|
|
108
|
+
| `loadingLabel` | `string` | What a screen reader says for that spinner. Default `Loading`: give it in your visitors' language. |
|
|
109
|
+
| *anything else* | | Handed to the module. File Browser: `maxSelections`, `initialFilter`, `selectLabel`, `messages`, `mediaLibrary`. Composition editor: `compositionId`, `mediaLibrary`, `googleFontsApiKey`, `autosaveDelayMs`, `messages`. Widget creator: `canvasId`, `widgetId`, `startWithNewWidget`, `presets`, `startFromPreset`, `presetLabels`, `messages`, `mediaLibrary`, `widgetBuilderUrl`. |
|
|
110
|
+
|
|
111
|
+
The handle:
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
{
|
|
115
|
+
id: string; type: string; version: string; // version is the one that was actually loaded
|
|
116
|
+
container: HTMLElement;
|
|
117
|
+
module: UIModule; // the module instance, for module-specific methods
|
|
118
|
+
on(event, handler): () => void; // returns a function that unsubscribes
|
|
119
|
+
off(event, handler): void;
|
|
120
|
+
setTheme(theme): void; // this module's look alone: see "Looking like your product"
|
|
121
|
+
setLanguage({ locale?, messages? }): void; // this module's words alone: see "Speaking your visitors' language"
|
|
122
|
+
unmount(): Promise<void>; // takes the module and its listeners down
|
|
123
|
+
}
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
### Showing your own media library
|
|
127
|
+
|
|
128
|
+
If your platform already has a media library (a CMS, an S3 bucket, a DAM), give the File Browser plain functions that
|
|
129
|
+
read and write it, and visitors browse, upload and pick from **your** files with the same screen. The module then never
|
|
130
|
+
talks to Widgetic, so there is no session to mint and no `getToken`:
|
|
131
|
+
|
|
132
|
+
```js
|
|
133
|
+
const fileBrowser = await mountModule('file-browser', {
|
|
134
|
+
container: '#media-library',
|
|
135
|
+
mediaLibrary: {
|
|
136
|
+
id: 'acme-assets',
|
|
137
|
+
label: 'Acme assets', // shown as the list's title. Default "My uploads"
|
|
138
|
+
// Required. One page of files, newest first. `cursor` is the `nextCursor` you returned for the page before.
|
|
139
|
+
list: async ({ cursor, limit, signal }) => {
|
|
140
|
+
const response = await fetch(`/api/assets?cursor=${cursor ?? ''}&limit=${limit}`, { signal });
|
|
141
|
+
if (!response.ok) throw Object.assign(new Error('Could not load your files'), { status: response.status });
|
|
142
|
+
const page = await response.json();
|
|
143
|
+
return {
|
|
144
|
+
items: page.assets.map((asset) => ({ id: asset.id, name: asset.fileName, url: asset.publicUrl, mimeType: asset.contentType })),
|
|
145
|
+
nextCursor: page.next ?? null, // null: that was the last page
|
|
146
|
+
};
|
|
147
|
+
},
|
|
148
|
+
// Optional. A button is shown only for the functions you give.
|
|
149
|
+
upload: async ({ file, onProgress, signal }) => uploadToAcme(file, onProgress, signal), // return the stored file
|
|
150
|
+
rename: async ({ id, name, signal }) => renameInAcme(id, name, signal),
|
|
151
|
+
delete: async ({ id, signal }) => deleteInAcme(id, signal),
|
|
152
|
+
},
|
|
153
|
+
on: {
|
|
154
|
+
select: ({ files }) => useFiles(files), // your files, as your library described them
|
|
155
|
+
error: ({ message, code, action }) => report(code, action, message), // MEDIA_LIBRARY_FORBIDDEN, MEDIA_LIBRARY_NETWORK ...
|
|
156
|
+
},
|
|
157
|
+
});
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
A failure inside your functions is reported through the `error` event with `fatal: false`; the code is
|
|
161
|
+
`MEDIA_LIBRARY_` plus `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, `NETWORK`, `INVALID_RESPONSE`, `NOT_SUPPORTED` or
|
|
162
|
+
`FAILED`, and `action` says what the visitor was doing (`load`, `upload`, `rename`, `delete`). Throw an error with a
|
|
163
|
+
`status` property (a failed `fetch` response) and it is sorted for you. The File Browser module shows the visitor a list
|
|
164
|
+
that cannot be read (with "Try again"), an upload that fails (in the upload panel) and a refused `rename` or `delete`
|
|
165
|
+
(in a pop-up, "Rename failed", with your library's sentence under it): the file stays as it was, and your page hears of
|
|
166
|
+
it as well, so use the event for your log, not for a second message. Everything your functions return is checked before it is shown: a file without an id, a name or a usable
|
|
167
|
+
address is skipped with a console warning rather than breaking the list. The File Browser's README has the whole
|
|
168
|
+
contract (file fields, paging, limits, CORS for text, PDF and font previews).
|
|
169
|
+
|
|
170
|
+
The `url` of a file is what a widget stores and shows. Once the visitor saves or publishes, everyone who sees the widget
|
|
171
|
+
loads that address, not only the person who picked it: give one that stays valid and needs no sign-in (a link that
|
|
172
|
+
expires after a few minutes, or one that checks a cookie, breaks the published widget). Widgetic keeps the `id` with the
|
|
173
|
+
file only so that the picker shows it as selected when it is opened again.
|
|
174
|
+
|
|
175
|
+
### The composition editor
|
|
176
|
+
|
|
177
|
+
Let a user change the texts, pictures, colours and fonts of a widget they own, beside a live preview, and save it. It is
|
|
178
|
+
the editor of Widgetic's own site, drawn in your page.
|
|
179
|
+
|
|
180
|
+
```js
|
|
181
|
+
const editor = await mountModule('composition-editor', {
|
|
182
|
+
container: '#editor', // give it a height: it fills its container
|
|
183
|
+
compositionId: 'cmp_123', // the composition of the user who is on the page; one editor edits one composition
|
|
184
|
+
getToken: async () => (await fetch('/widgetic-session', { method: 'POST' })).json(), // { token, expiresAt }
|
|
185
|
+
on: {
|
|
186
|
+
ready: ({ name, widgetId }) => showTitle(name),
|
|
187
|
+
dirty: ({ dirty }) => markUnsaved(dirty),
|
|
188
|
+
saved: ({ savedAt }) => markSaved(savedAt),
|
|
189
|
+
error: ({ message, code, fatal, sessionEnded }) => report(code, message),
|
|
190
|
+
},
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
// later: saves what is unsaved first, then takes the editor away
|
|
194
|
+
await editor.unmount();
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
- **The session needs the `editor` surface** (and `files` for the file pickers): mint it with
|
|
198
|
+
`surfaces: ['editor', 'files']`. It opens and changes the compositions of the managed user it was minted for and
|
|
199
|
+
nothing else; another user's composition is answered with 404. Create a user's composition with their `managedUserId`.
|
|
200
|
+
- **Saving.** The editor saves by itself shortly after the last change (`autosaveDelayMs`, default 2500; `0` turns it
|
|
201
|
+
off). `editor.module.save()` saves what is unsaved now, `editor.module.flush()` saves everything unsaved and waits until
|
|
202
|
+
it is (both resolve `true` when nothing is left unsaved), and `editor.module.isDirty()` tells whether anything is unsaved.
|
|
203
|
+
- **`unmount()` saves first**, for up to 10 seconds, so closing the editor never loses the last edits. If some could not
|
|
204
|
+
be saved you hear an `error` with code `UNSAVED_ON_UNMOUNT` (your `on` handlers stay connected until `unmount()` has
|
|
205
|
+
finished). `editor.module.unmount({ discard: true })` throws unsaved edits away instead.
|
|
206
|
+
- **Problems** are shown to the visitor by the editor itself, with "Try again" where that helps; `error` is for your page.
|
|
207
|
+
`fatal: true` means the editor cannot go on by itself: the composition cannot be opened, or the session is over
|
|
208
|
+
(`sessionEnded: true`), so mint a new session or take the editor away. Quote `correlationId` to Widgetic's support.
|
|
209
|
+
- **Your own files.** Pass `mediaLibrary` (above) and the editor's file pickers show your files instead of the user's
|
|
210
|
+
Widgetic uploads.
|
|
211
|
+
- **Fonts.** `googleFontsApiKey` is a Google Fonts Web Fonts API key for the font picker's list; without one the picker
|
|
212
|
+
lists a short set of popular families.
|
|
213
|
+
- **One composition editor per page** for now; a second is refused with a clear message.
|
|
214
|
+
|
|
215
|
+
### The widget creator
|
|
216
|
+
|
|
217
|
+
Widgetic's whole canvas, on your page: a user draws frames, describes a widget to the AI in the chat, watches it being
|
|
218
|
+
built, changes its settings and publishes it, without leaving your product. It is the creator of the Widgetic app, so
|
|
219
|
+
everything the canvas does is there; the module gives it a shadow root, a session and a way to tell your page what
|
|
220
|
+
happened.
|
|
221
|
+
|
|
222
|
+
```js
|
|
223
|
+
const creator = await mountModule('widget-creator', {
|
|
224
|
+
container: '#creator', // give it a height: it fills its container
|
|
225
|
+
canvasId: savedCanvasIdOfThisUser, // optional: the one `canvasChanged` gave you last time
|
|
226
|
+
getToken: async () => (await fetch('/widgetic-session', { method: 'POST' })).json(), // { token, expiresAt }
|
|
227
|
+
on: {
|
|
228
|
+
ready: ({ canvasId }) => {},
|
|
229
|
+
canvasChanged: ({ canvasId }) => rememberForNextVisit(canvasId),
|
|
230
|
+
widgetRenamed: ({ widgetId, name }) => setTitleOfTheUsersWork(name),
|
|
231
|
+
widgetPublished: ({ widgetId, version }) => showInMyProduct(widgetId),
|
|
232
|
+
limitReached: ({ message, code }) => offerMore(),
|
|
233
|
+
error: ({ message, code, fatal, sessionEnded }) => report(code, message),
|
|
234
|
+
},
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
// later:
|
|
238
|
+
await creator.unmount();
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
- **The session needs the `creator`, `editor` and `files` surfaces together**: `surfaces: ['creator', 'editor', 'files']`
|
|
242
|
+
(the settings panel saves through `editor`, and chat attachments and file pickers go through `files`). It works on
|
|
243
|
+
the canvases and widgets of the managed user it was minted for and nothing else; another user's canvas is answered
|
|
244
|
+
with 404, as if it did not exist. Tag what you create for a user with their `managedUserId`.
|
|
245
|
+
- **Remembering where the user was.** The creator writes nothing to your `localStorage`, `sessionStorage`, cookies or
|
|
246
|
+
address bar, and never opens a window or reloads your page. Keep the id from `canvasChanged` and give it back as
|
|
247
|
+
`canvasId` next time. Without one it opens the user's latest canvas, or makes a new one. `widgetId` picks the widget
|
|
248
|
+
of that canvas to open, and `startWithNewWidget: true` starts from an empty canvas.
|
|
249
|
+
- **Starting points.** A user who has made nothing yet is shown your presets (the widgets of your account that you
|
|
250
|
+
offer as starting points) before the creator opens, and gets their own copy of the one they pick: `presets: 'off'`
|
|
251
|
+
turns that off, `startFromPreset: '<key>'` copies one for them without asking, `presetLabels` are the picker's words,
|
|
252
|
+
and your page hears `presetChosen`. A user who has work, and a page that gives `canvasId` back, never see it. If the
|
|
253
|
+
starting points cannot be had for any reason the creator opens as always and `error` says so with `fatal: false` and
|
|
254
|
+
`during: 'presets'`. Deploy the API first, then the SDK, then the modules. Details: `modules/README.md`, "Starting
|
|
255
|
+
points for a visitor who has made nothing yet".
|
|
256
|
+
- **Publishing** saves a version of the widget (the user can go back to an earlier one) and you hear `widgetPublished`.
|
|
257
|
+
A session can never make a widget public in Widgetic's catalogue: what a user builds stays private to your account.
|
|
258
|
+
- **Credits and limits are yours.** The AI is paid for by your account, as your own calls are. When your credits run out
|
|
259
|
+
(or a plan limit or the storage limit is reached), the creator tells the user in plain words ("This is not available
|
|
260
|
+
right now. Please try again later.") and keeps working; it never shows what your account holds. Your page hears
|
|
261
|
+
`limitReached` `{ message, code }` once per `code` in half a minute (`BILLING_INSUFFICIENT_CREDITS`,
|
|
262
|
+
`AUTHZ_PLAN_RESTRICTION`, `QUOTA_STORAGE_EXCEEDED`, `COST_LIMIT_EXCEEDED`, or `LIMIT_REACHED` when the user pressed an
|
|
263
|
+
"Upgrade" button; the creator opens no page for it, so what an upgrade means in your product is for you to show).
|
|
264
|
+
Ordinary rate limiting is not a limit and is not reported.
|
|
265
|
+
- **Problems** are shown to the user by the creator itself; `error` is for your page. `fatal: true` means it cannot go on:
|
|
266
|
+
the session is over (`sessionEnded`: mount again with a new token), or the `canvasId` you gave is not this user's
|
|
267
|
+
(`during: 'canvas'`: mount again without it); `fatal: false` is a problem it went on past (a token refresh that will
|
|
268
|
+
be retried, or the starting points not working: `during: 'presets'`). `reloadRequested` means the creator would have reloaded the page to
|
|
269
|
+
recover: unmount it and mount a new one.
|
|
270
|
+
- **Your own files.** Pass `mediaLibrary` (above) and the settings panel's file pickers show your files instead of the
|
|
271
|
+
user's Widgetic uploads. Pictures dropped on the canvas and the chat's attachments (up to 10 MB) still go to Widgetic.
|
|
272
|
+
- **Keyboard.** Its shortcuts work only while the focus is inside it, so your page keeps every key it had; your page's
|
|
273
|
+
own zoom works everywhere.
|
|
274
|
+
- **Size and weight.** The module is about 5.8 MB (1.4 MB gzip), downloaded when you mount it and not before. A user who
|
|
275
|
+
previews a PDF downloads two more files then (1.8 MB, 0.5 MB gzip). Call `preload('widget-creator')` on a `WidgeticUI`
|
|
276
|
+
(below) when the page that will host it opens.
|
|
277
|
+
- **One creator per page** for now; a second is refused with a clear message. The composition steps (*Edit* with a
|
|
278
|
+
widget's compositions, *Embed*) are off in a session: edit compositions with the composition editor.
|
|
279
|
+
|
|
280
|
+
### Several modules on one page: `WidgeticUI`
|
|
281
|
+
|
|
282
|
+
```js
|
|
283
|
+
import { WidgeticUI } from '@widgetic/ui-sdk';
|
|
284
|
+
|
|
285
|
+
const ui = new WidgeticUI({ getToken, theme: 'system' }); // touches nothing until you mount
|
|
286
|
+
await ui.preload('file-browser'); // optional: download it ahead of time
|
|
287
|
+
const files = await ui.mount('file-browser', { container: '#files' });
|
|
288
|
+
|
|
289
|
+
ui.updateTheme('dark'); // every mounted module, and later ones (colours, radius, font stay)
|
|
290
|
+
await files.unmount();
|
|
291
|
+
await ui.destroy(); // unmounts whatever is left
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
`mountModule` creates a `WidgeticUI`, mounts one module with it, and destroys it again when you `unmount()`.
|
|
295
|
+
|
|
296
|
+
### Looking like your product
|
|
297
|
+
|
|
298
|
+
A module can wear your colours, corner roundness and typeface. The components and the layout stay Widgetic's; only
|
|
299
|
+
the look follows your design system. Each module has its own theme. (The words are a separate choice: see
|
|
300
|
+
[Speaking your visitors' language](#speaking-your-visitors-language).)
|
|
301
|
+
|
|
302
|
+
```js
|
|
303
|
+
const ui = new WidgeticUI({
|
|
304
|
+
getToken,
|
|
305
|
+
theme: { preset: 'ocean', radius: 'medium', font: { family: 'Poppins', stylesheetUrl: 'https://fonts.googleapis.com/css2?family=Poppins&display=swap' } },
|
|
306
|
+
});
|
|
307
|
+
const files = await ui.mount('file-browser', { container: '#files' }); // takes the page's look
|
|
308
|
+
const editor = await ui.mount('composition-editor', {
|
|
309
|
+
container: '#editor',
|
|
310
|
+
compositionId,
|
|
311
|
+
theme: { preset: 'violet', mode: 'dark', colors: { primary: '#e0541b' } }, // a look of its own
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
ui.updateTheme('dark'); // the mode of every module; each keeps its colours, radius and font
|
|
315
|
+
ui.updateTheme({ preset: 'sunset' }); // new page-wide settings, for the modules that have none of their own
|
|
316
|
+
editor.setTheme({ radius: 'none' }); // one module alone
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
| Setting | |
|
|
320
|
+
| --- | --- |
|
|
321
|
+
| `preset` | `'widgetic'` (the default look), `'graphite'`, `'ocean'`, `'violet'` or `'sunset'`. Colours only. |
|
|
322
|
+
| `mode` | `'light'`, `'dark'`, or (page-wide, for a visitor's own setting) `'system'`. |
|
|
323
|
+
| `colors` | Any of `primary`, `primaryForeground`, `background`, `foreground`, `muted`, `mutedForeground`, `border`, `accent`, `destructive`, written out (`#0b69c7`, `rgb(11 105 199)`, `hsl(210 90% 41%)`). Name only what you want to decide: the rest follows. |
|
|
324
|
+
| `radius` | `'none'`, `'small'`, `'medium'`, `'large'`, or pixels from 0 to 32. |
|
|
325
|
+
| `font` | `{ family, stylesheetUrl? }`. A font your page does not load yet needs the `https` address of its stylesheet; the module adds one `<link>` to your `<head>`. |
|
|
326
|
+
|
|
327
|
+
- A bare mode (`'dark'`, `{ mode: 'dark' }`) changes the mode and keeps the rest; settings replace the whole look.
|
|
328
|
+
- Settings in a mount call, or in `mounted.setTheme(...)`, are that module's own: `ui.updateTheme(settings)` does not
|
|
329
|
+
take them away, and a page that changes a preset does not turn a dark module light. A call that names a mode reaches every module.
|
|
330
|
+
- A theme that cannot be used throws `INVALID_THEME`, with the setting and what to write instead, and changes nothing.
|
|
331
|
+
When only the module can tell (an unknown preset, a colour it cannot read), `updateTheme` reports it in the console
|
|
332
|
+
and the module keeps its look; `mounted.setTheme` and the mount call throw.
|
|
333
|
+
- The widget creator takes a theme's mode, neutral colours, brand colour and font, but not yet its corners: a dark look
|
|
334
|
+
restyles its panels, toolbar, menus and chat (the canvas board, the live widget previews and the chat's message bubbles
|
|
335
|
+
stay light), and `primary` is its accent (selected tool, sliders, the Send button, with the text on them white or dark,
|
|
336
|
+
whichever reads), while most corners are Widgetic's own for now.
|
|
337
|
+
|
|
338
|
+
The presets, how a colour must be written, fonts under a Content-Security-Policy and what a theme cannot change are in
|
|
339
|
+
[the modules' README](modules/README.md#looking-like-your-product-themes).
|
|
340
|
+
|
|
341
|
+
### Speaking your visitors' language
|
|
342
|
+
|
|
343
|
+
The File Browser, the composition editor and the widget creator can show their words in your visitors' language. Two
|
|
344
|
+
options do it, and `mounted.setLanguage(...)` changes them while the module is on screen (the examples are the File
|
|
345
|
+
Browser's; the differences of the composition editor and the widget creator are in the last bullets):
|
|
346
|
+
|
|
347
|
+
- **`locale`**, a [BCP 47](https://www.rfc-editor.org/info/bcp47) tag such as `de` or `pt-BR`. It sets the plural rules
|
|
348
|
+
("1 file", "2 files"; Polish and Arabic have more forms) and how numbers, dates and file sizes are written (`1,5 KB` in
|
|
349
|
+
German). It translates nothing by itself. A tag the browser has no data for (`xx`) is reported in the console and
|
|
350
|
+
English is used, so two languages never mix on one screen.
|
|
351
|
+
- **`messages`**, the words: an object of message keys and texts. A key you leave out stays English, so a language can be
|
|
352
|
+
added one screen at a time.
|
|
353
|
+
|
|
354
|
+
```js
|
|
355
|
+
const files = await mountModule('file-browser', {
|
|
356
|
+
container: '#files',
|
|
357
|
+
getToken,
|
|
358
|
+
locale: 'de',
|
|
359
|
+
messages: {
|
|
360
|
+
'action.addToEditor': 'Auswählen', // the button that hands the pick to your page (English: "Select")
|
|
361
|
+
'action.cancel': 'Abbrechen',
|
|
362
|
+
'search.placeholder': 'Suchen...',
|
|
363
|
+
'folder.itemCount': '{count, plural, one {# Element} other {# Elemente}}',
|
|
364
|
+
},
|
|
365
|
+
loadingLabel: 'Wird geladen', // what a screen reader says for the spinner while the module downloads
|
|
366
|
+
});
|
|
367
|
+
|
|
368
|
+
files.setLanguage({ locale: 'fr', messages: frenchMessages }); // the screens that are open change at once
|
|
369
|
+
files.setLanguage({ locale: 'it' }); // what is not said keeps its value: the words stay French
|
|
370
|
+
files.setLanguage({ locale: '', messages: {} }); // back to English
|
|
371
|
+
```
|
|
372
|
+
|
|
373
|
+
- **A message is plain text.** `{name}` is a value the File Browser puts in. `{count, plural, one {# file} other {# files}}`
|
|
374
|
+
picks the form that fits the number in your language (`other` is required, `=0 {…}` matches exactly zero, `#` is the
|
|
375
|
+
number). `\{`, `\}`, `\#` and `\\` write the character itself; nothing else is special, so `Delete '{name}'?` works.
|
|
376
|
+
- **Every key, with its English text,** is `files.module.defaultMessages`: start a language from it. What each message is
|
|
377
|
+
for, and what values it is given, is in [the modules' README](modules/README.md#speaking-your-visitors-language).
|
|
378
|
+
- **A mistake in a message never breaks the screen.** A key that does not exist (the console says which one you probably
|
|
379
|
+
meant), a text that is not a string, a template that cannot be read, a value the message is never given: each is said
|
|
380
|
+
once in the console as `[FileBrowser] …`, and the English text is used for that message. `files.module.checkMessages(messages)`
|
|
381
|
+
returns the same sentences without mounting anything, for a test of your own. Only a *wrong shape* throws, naming the
|
|
382
|
+
option: `messages: 'Abbrechen'` or `locale: 5`.
|
|
383
|
+
- **`selectLabel`** still works: it is the message `action.addToEditor`. When both are given, `messages` wins.
|
|
384
|
+
- **Not translated:** what the module tells your code (the `message` of an `error` event stays English; use its `code`),
|
|
385
|
+
file names, and the name your own media library gives itself. **Right to left:** the File Browser, the composition
|
|
386
|
+
editor and the widget creator are read the way their `locale` is, so Arabic, Hebrew, Persian or Urdu turns the whole
|
|
387
|
+
screen around (and `setLanguage` turns it around or back while it is on screen); the canvas board, the live previews
|
|
388
|
+
and the code of the creator stay left to right. See
|
|
389
|
+
[the modules' README](modules/README.md#speaking-your-visitors-language).
|
|
390
|
+
**Pop-ups** (a refused `rename`, a pick ...) are drawn by the module and
|
|
391
|
+
are messages like the rest: the `toast.` keys, with `toast.regionLabel` and `toast.closeLabel` for a screen reader.
|
|
392
|
+
After a pick it says "Files selected", not the site's "Added 2 files to the editor".
|
|
393
|
+
- **The composition editor** takes the same `locale`, `messages` and `setLanguage`, with **one** `messages` object for all of
|
|
394
|
+
it: its own words (`editor.` keys), the file picker that opens from its file fields (the File Browser's keys) and its
|
|
395
|
+
rich text editor (`shadEditor.` keys), which it splits between them, so you never need to know which part says a word.
|
|
396
|
+
`editor.module.defaultMessages` lists them all. Month and weekday names in its calendars follow `locale` by themselves.
|
|
397
|
+
What is saved with the composition (the title of a new item, "Untitled Composition"), the words the widget's author wrote
|
|
398
|
+
for its settings, and the `error` events stay as they are. Its file picker's pop-ups use the same `toast.` keys inside
|
|
399
|
+
the module's shadow root. [The modules' README](modules/README.md#speaking-your-visitors-language) has the list.
|
|
400
|
+
- **The widget creator** takes the same `locale`, `messages` and `setLanguage`, with **one** `messages` object for all of it:
|
|
401
|
+
its own words (`creator.` keys), the chat's (`chat.`), the canvas's (`canvas.`: the toolbar, the zoom controls, the
|
|
402
|
+
menus, the properties panel), the starting-point picker's (`presetPicker.` keys: the `presetLabels` option is a shortcut
|
|
403
|
+
for them that sits under `messages`) and the two words of its pop-up region (`toast.regionLabel`, `toast.closeLabel`).
|
|
404
|
+
`creator.module.defaultMessages` lists every key, more than 1,300. The dates of a widget's versions follow `locale`.
|
|
405
|
+
What the visitor and the AI write, the words a widget's author wrote for its settings, what Widgetic's API sends back
|
|
406
|
+
(shown as it arrives), and the `message` of the `error` and `limitReached` events stay as they are. Lines the creator
|
|
407
|
+
saved into the chat stay English in the API and are translated on screen when the table knows them.
|
|
408
|
+
[The modules' README](modules/README.md#speaking-your-visitors-language) has the list.
|
|
409
|
+
|
|
410
|
+
### Events
|
|
411
|
+
|
|
412
|
+
| Event | Payload | |
|
|
413
|
+
| --- | --- | --- |
|
|
414
|
+
| `ready` | | The module is on screen. (Composition editor: `{ name, widgetId }`, once the composition has loaded. Widget creator: `{ canvasId }`, once the first canvas has loaded; `null` for a new, empty one.) |
|
|
415
|
+
| `error` | `{ message, code?, fatal }` | `fatal: true`: the module has stopped. `false`: it carries on (a failed token refresh that will be retried). The composition editor adds `during`, `status`, `retryable`, `sessionEnded` and `correlationId`; the widget creator adds `during` and `sessionEnded`. |
|
|
416
|
+
| `select` | `{ files: PickedFile[] }` | File Browser: the visitor confirmed a pick. |
|
|
417
|
+
| `dirty` | `{ dirty: boolean }` | Composition editor: there is, or is no longer, work that is not saved. |
|
|
418
|
+
| `saved` | `{ composition, savedAt }` | Composition editor: a save went through. |
|
|
419
|
+
| `canvasChanged` | `{ canvasId }` | Widget creator: it opened a canvas or made one. Keep the id and give it back as `canvasId` next time. |
|
|
420
|
+
| `widgetRenamed` | `{ widgetId, name }` | Widget creator: the main widget has this name (said when the canvas opens and each time the user renames it). |
|
|
421
|
+
| `widgetPublished` | `{ widgetId, version? }` | Widget creator: the user published a version of a widget. |
|
|
422
|
+
| `limitReached` | `{ message, code? }` | Widget creator: the user ran into a limit (credits, plan, storage, allowance). The creator has told them already. |
|
|
423
|
+
| `reloadRequested` | | Widget creator: it would have reloaded the page to recover. Unmount it and mount a new one. |
|
|
424
|
+
|
|
425
|
+
## Tokens
|
|
426
|
+
|
|
427
|
+
`getToken` is the only credential the SDK takes. It is called with `{ reason }`:
|
|
428
|
+
|
|
429
|
+
- `'initial'`: the module is starting.
|
|
430
|
+
- `'expiring'`: the current token runs out in about a minute; return its replacement now.
|
|
431
|
+
- `'expired'`: the current token has already run out (the page was asleep, or an earlier refresh failed).
|
|
432
|
+
|
|
433
|
+
Return the token itself, or `{ token, expiresAt }` (ISO string, epoch milliseconds or `Date`). With `expiresAt` the
|
|
434
|
+
module renews the token in time and the visitor is never interrupted. The gateway's answer to the mint call already has
|
|
435
|
+
this shape.
|
|
436
|
+
|
|
437
|
+
When `getToken` answers an `'expired'` call with the very token the API had refused, the module takes it that you have no
|
|
438
|
+
better one: it does not ask again for five seconds, whatever asks, so a session that was ended is reported once and not once
|
|
439
|
+
per request.
|
|
440
|
+
|
|
441
|
+
Rules worth keeping:
|
|
442
|
+
|
|
443
|
+
- Mint a session **per page open, per user**, from an endpoint that checks who is logged in. Never hand one user's token
|
|
444
|
+
to another.
|
|
445
|
+
- Pass `allowed_origin` so a copied token is useless from any other web page.
|
|
446
|
+
- Keep tokens out of logs, local storage and URLs.
|
|
447
|
+
- End sessions when the user signs out: `DELETE /v1/managed-users/{id}/editor-sessions`.
|
|
448
|
+
|
|
449
|
+
An `apiKey` option is refused with `API_KEY_NOT_ALLOWED`. The message never contains the key.
|
|
450
|
+
|
|
451
|
+
## Cancelling a mount
|
|
452
|
+
|
|
453
|
+
Mounting takes a moment (the module has to download). When your component can go away before that, pass an
|
|
454
|
+
`AbortSignal`. If it aborts before the module is running, nothing is left in the container and the promise rejects with
|
|
455
|
+
an `AbortError` (code `MOUNT_ABORTED`), which neither logs nor calls `onError`. If it aborts while the module is
|
|
456
|
+
starting, the module is taken down again.
|
|
457
|
+
|
|
458
|
+
### React
|
|
459
|
+
|
|
460
|
+
```jsx
|
|
461
|
+
import { useEffect, useRef } from 'react';
|
|
462
|
+
import { mountModule } from '@widgetic/ui-sdk';
|
|
463
|
+
|
|
464
|
+
export function MediaLibrary({ getToken, onPick }) {
|
|
465
|
+
const containerRef = useRef(null);
|
|
466
|
+
const onPickRef = useRef(onPick);
|
|
467
|
+
onPickRef.current = onPick;
|
|
468
|
+
|
|
469
|
+
useEffect(() => {
|
|
470
|
+
const controller = new AbortController();
|
|
471
|
+
let mounted = null;
|
|
472
|
+
|
|
473
|
+
mountModule('file-browser', {
|
|
474
|
+
container: containerRef.current,
|
|
475
|
+
getToken,
|
|
476
|
+
signal: controller.signal,
|
|
477
|
+
on: { select: ({ files }) => onPickRef.current(files) },
|
|
478
|
+
}).then(
|
|
479
|
+
(handle) => { mounted = handle; },
|
|
480
|
+
(error) => { if (error.name !== 'AbortError') console.error(error); },
|
|
481
|
+
);
|
|
482
|
+
|
|
483
|
+
return () => {
|
|
484
|
+
controller.abort(); // before the module is running: it never appears
|
|
485
|
+
mounted?.unmount(); // after: it is taken down
|
|
486
|
+
};
|
|
487
|
+
}, []); // StrictMode runs this twice; the first run is cancelled cleanly
|
|
488
|
+
|
|
489
|
+
return <div ref={containerRef} style={{ height: 600 }} />;
|
|
490
|
+
}
|
|
491
|
+
```
|
|
492
|
+
|
|
493
|
+
The same component mounts the other modules: give `mountModule` the module's name (`'composition-editor'`,
|
|
494
|
+
`'widget-creator'`) and its options. The build tests run it in a React 18 page, in `<React.StrictMode>` and out of it,
|
|
495
|
+
for all three modules: a component that goes away while its module downloads leaves nothing behind, one that comes back
|
|
496
|
+
mounts a fresh module, and the one-instance-per-page guards do not refuse the second run of a StrictMode effect.
|
|
497
|
+
|
|
498
|
+
### Vue 3
|
|
499
|
+
|
|
500
|
+
```vue
|
|
501
|
+
<script setup>
|
|
502
|
+
import { onBeforeUnmount, onMounted, ref } from 'vue';
|
|
503
|
+
import { mountModule } from '@widgetic/ui-sdk';
|
|
504
|
+
|
|
505
|
+
const props = defineProps({ getToken: Function });
|
|
506
|
+
const emit = defineEmits(['pick']);
|
|
507
|
+
const container = ref(null);
|
|
508
|
+
const controller = new AbortController();
|
|
509
|
+
let mounted = null;
|
|
510
|
+
|
|
511
|
+
onMounted(async () => {
|
|
512
|
+
try {
|
|
513
|
+
mounted = await mountModule('file-browser', {
|
|
514
|
+
container: container.value,
|
|
515
|
+
getToken: props.getToken,
|
|
516
|
+
signal: controller.signal,
|
|
517
|
+
on: { select: ({ files }) => emit('pick', files) },
|
|
518
|
+
});
|
|
519
|
+
} catch (error) {
|
|
520
|
+
if (error.name !== 'AbortError') throw error;
|
|
521
|
+
}
|
|
522
|
+
});
|
|
523
|
+
onBeforeUnmount(() => {
|
|
524
|
+
controller.abort();
|
|
525
|
+
mounted?.unmount();
|
|
526
|
+
});
|
|
527
|
+
</script>
|
|
528
|
+
|
|
529
|
+
<template><div ref="container" style="height: 600px"></div></template>
|
|
530
|
+
```
|
|
531
|
+
|
|
532
|
+
### Svelte
|
|
533
|
+
|
|
534
|
+
```svelte
|
|
535
|
+
<script>
|
|
536
|
+
import { createEventDispatcher, onMount } from 'svelte';
|
|
537
|
+
import { mountModule } from '@widgetic/ui-sdk';
|
|
538
|
+
|
|
539
|
+
export let getToken;
|
|
540
|
+
const dispatch = createEventDispatcher();
|
|
541
|
+
let container;
|
|
542
|
+
|
|
543
|
+
onMount(() => {
|
|
544
|
+
const controller = new AbortController();
|
|
545
|
+
let mounted = null;
|
|
546
|
+
mountModule('file-browser', {
|
|
547
|
+
container, getToken, signal: controller.signal,
|
|
548
|
+
on: { select: ({ files }) => dispatch('pick', files) },
|
|
549
|
+
}).then(
|
|
550
|
+
(handle) => (mounted = handle),
|
|
551
|
+
(error) => { if (error.name !== 'AbortError') console.error(error); },
|
|
552
|
+
);
|
|
553
|
+
return () => { controller.abort(); mounted?.unmount(); };
|
|
554
|
+
});
|
|
555
|
+
</script>
|
|
556
|
+
|
|
557
|
+
<div bind:this={container} style="height: 600px"></div>
|
|
558
|
+
```
|
|
559
|
+
|
|
560
|
+
## Server-side rendering
|
|
561
|
+
|
|
562
|
+
Importing the SDK and constructing `WidgeticUI` do nothing on a server. Mounting needs a page, so it must start from an
|
|
563
|
+
effect or an event handler; calling `mountModule` or `preload` while rendering on the server rejects with
|
|
564
|
+
`NOT_IN_BROWSER` and a message that says so.
|
|
565
|
+
|
|
566
|
+
## Versions and self-hosting
|
|
567
|
+
|
|
568
|
+
Modules are static files, so there is nothing to call and nothing that can change under your feet when you pin:
|
|
569
|
+
|
|
570
|
+
```
|
|
571
|
+
<moduleBaseUrl>/<name>/manifest.json { "name": "file-browser", "version": "1.2.0", "entry": "1.2.0/index.js" }
|
|
572
|
+
<moduleBaseUrl>/<name>/<version>/index.js never changes once published
|
|
573
|
+
<moduleBaseUrl>/<name>/<version>/chunks/<file>.js the parts the module fetches later (the PDF viewer); never change either
|
|
574
|
+
<moduleBaseUrl>/<name>/changelog.json what changed in each version up to the one the manifest names, newest first
|
|
575
|
+
```
|
|
576
|
+
|
|
577
|
+
- Without `version` the SDK reads the manifest and loads the version it names. With `version: '1.2.0'` it loads that
|
|
578
|
+
file directly. **Production pages should pin**; upgrade when you have looked at the release.
|
|
579
|
+
- **Read what changed before you move.** `changelog.json` lists every version with a flag for the ones that break
|
|
580
|
+
something (`breaking: true`) and, for each, its changes in seven lists (`breaking`, `added`, `changed`, `deprecated`,
|
|
581
|
+
`removed`, `fixed`, `security`). A release that lists breaking changes is always a new major version (a new minor one
|
|
582
|
+
while the major is 0), so going from `1.2.0` to `1.4.1` should not break anything you use, and a new major version is
|
|
583
|
+
the one to read first. The same text is in each module's `src/<name>/CHANGELOG.md`, which a release needs an entry in
|
|
584
|
+
("Publishing" in `modules/README.md`).
|
|
585
|
+
- A page runs one version of each module: every `WidgeticUI` on the page that uses the same `moduleBaseUrl` shares one
|
|
586
|
+
loader, so the module is downloaded once.
|
|
587
|
+
- To serve modules yourself, copy that layout to your own origin (the whole `<version>` folder: `index.js` fetches its
|
|
588
|
+
`chunks/` files from the folder it was loaded from) and set `moduleBaseUrl`. The manifest's `entry` must be a `.js`
|
|
589
|
+
file inside the module's own folder on the same origin, or it is refused (`MANIFEST_INVALID`).
|
|
590
|
+
- Failed downloads are retried twice (network errors and 5xx, not 404), and the SDK asks the browser for a fresh copy
|
|
591
|
+
by adding `?retry=N`, because browsers remember a failed module import. The module also asks twice more, the same way,
|
|
592
|
+
when a file it fetches later fails. Requests to the CDN carry no cookies.
|
|
593
|
+
|
|
594
|
+
## What the SDK puts on your page
|
|
595
|
+
|
|
596
|
+
- On import and on `new WidgeticUI(...)`: nothing.
|
|
597
|
+
- While the module downloads: one `div[data-widgetic-ui-loading]` in your container, removed when the module is up.
|
|
598
|
+
- A mounted module: one `<widgetic-ui-module>` element in your container, holding a shadow root. The File Browser also
|
|
599
|
+
adds one `<style data-widgetic-ui-document-rules>` to `<head>` with `@font-face` rules for fonts that are named
|
|
600
|
+
`Widgetic UI …` so they cannot collide with yours. The composition editor adds the same, and Google's stylesheet for
|
|
601
|
+
each font the user looks at in its font picker; those `<link>`s go when the editor is unmounted, and your own
|
|
602
|
+
`<link>`s and `<meta>`s are never touched. The widget creator adds that one `<style>` and nothing else to your
|
|
603
|
+
`<head>`. That `<style>` stays when a module is unmounted: every module on the page shares it and it is never added
|
|
604
|
+
twice.
|
|
605
|
+
- Never: global CSS or CSS variables, changes to `<html>`/`<body>`, `postMessage`, or removing your own elements.
|
|
606
|
+
|
|
607
|
+
### Content Security Policy
|
|
608
|
+
|
|
609
|
+
If your page sends a Content-Security-Policy, the File Browser works with this and nothing more. The build tests load
|
|
610
|
+
it under the same policy (with the CDN and the API on a local address), list, pick and upload images and preview a PDF;
|
|
611
|
+
each source below is needed: the test fails without it:
|
|
612
|
+
|
|
613
|
+
```
|
|
614
|
+
default-src 'none';
|
|
615
|
+
script-src 'self' https://cdn.widgetic.com; # plus whatever your own page needs
|
|
616
|
+
connect-src https://cdn.widgetic.com https://api.widgetic.com;
|
|
617
|
+
style-src 'unsafe-inline'; # the module's styles are <style> elements in its shadow root
|
|
618
|
+
font-src data:; # its fonts are embedded
|
|
619
|
+
img-src https://cdn.widgetic.com data: blob:; # data: for its icons, blob: for an upload's preview
|
|
620
|
+
worker-src blob:; # only to preview a PDF: pdf.js reads it in a worker made from a blob
|
|
621
|
+
```
|
|
622
|
+
|
|
623
|
+
`img-src` also needs the address your users' files are served from (the `url` of a picked file). To preview a PDF, that
|
|
624
|
+
address also goes in `connect-src` (pdf.js downloads the PDF with a request, so the file server has to allow your page's
|
|
625
|
+
origin with CORS) and the policy needs the `worker-src blob:` above; without it the preview says "Failed to load PDF"
|
|
626
|
+
and everything else works. No `data:` in `script-src` and no `'unsafe-eval'` are needed: a build of a module fails if a
|
|
627
|
+
script is left inside a `data:` URL. The PDF viewer is downloaded when the first PDF is previewed, from the same folder
|
|
628
|
+
of the CDN as the module itself, so `script-src` needs nothing more. The tests open a PDF under this policy, from the API and from a file server of
|
|
629
|
+
their own that the policy names.
|
|
630
|
+
|
|
631
|
+
The composition editor works under the same policy plus `frame-src https://cdn.widgetic.com`, for the live preview (the
|
|
632
|
+
widget's published page, served from the CDN). Its font picker also needs `style-src https://fonts.googleapis.com` and
|
|
633
|
+
`font-src https://fonts.gstatic.com` (and `connect-src https://www.googleapis.com` if you give it a `googleFontsApiKey`);
|
|
634
|
+
the build tests do not use the font picker under a policy.
|
|
635
|
+
|
|
636
|
+
The widget creator needs what the composition editor needs plus `frame-src https://wbuilder.widgetic.com
|
|
637
|
+
https://cdn.widgetic.com` (the live previews of widgets are frames served from those two; set `widgetBuilderUrl` to use
|
|
638
|
+
another builder origin) and the same two origins in `connect-src` (it asks whether a preview exists before it shows
|
|
639
|
+
it). The build tests run it under a policy that allows only the API's origin for connections, pictures and frames, `data:`
|
|
640
|
+
fonts, `data:` and `blob:` pictures and no `eval`, with the API's origin standing in for the two preview hosts; they have
|
|
641
|
+
not been run against the real ones.
|
|
642
|
+
|
|
643
|
+
## Errors
|
|
644
|
+
|
|
645
|
+
Every error carries a `code`.
|
|
646
|
+
|
|
647
|
+
| Code | Meaning |
|
|
648
|
+
| --- | --- |
|
|
649
|
+
| `INVALID_GET_TOKEN` | `getToken` was given but is not a function. (A module that needs a token and has none fails to start with `MOUNT_FAILED`, and says so.) |
|
|
650
|
+
| `API_KEY_NOT_ALLOWED` | An `apiKey` (or `partner.apiKey`) option was given. Mint an editor session on your server instead. |
|
|
651
|
+
| `NOT_IN_BROWSER` | Mounting or preloading on a server. |
|
|
652
|
+
| `MISSING_CONTAINER`, `CONTAINER_NOT_FOUND`, `INVALID_CONTAINER` | `container` is missing, matches nothing, or is not an element. |
|
|
653
|
+
| `INVALID_MODULE_NAME`, `INVALID_VERSION`, `INVALID_MODULE_BASE_URL` | The name, pinned version or module address is not valid. |
|
|
654
|
+
| `MODULE_NOT_FOUND` | The CDN has no such module (404/403 on its manifest). |
|
|
655
|
+
| `MANIFEST_UNAVAILABLE` | The manifest could not be fetched, even after retrying. |
|
|
656
|
+
| `MANIFEST_INVALID` | The manifest is not JSON, names another module or an invalid version, or points outside the module's folder. |
|
|
657
|
+
| `MODULE_LOAD_FAILED` | The module file could not be imported, even after retrying. |
|
|
658
|
+
| `MODULE_INVALID` | The file loaded but does not export a module class. |
|
|
659
|
+
| `MOUNT_FAILED` | The module loaded but failed to start; `cause` has its own error. Nothing is left in the container. |
|
|
660
|
+
| `MOUNT_ABORTED` | The mount was cancelled through `signal`. |
|
|
661
|
+
| `INSTANCE_NOT_FOUND` | `unmountComponent` was given an id that is not mounted. |
|
|
662
|
+
| `INVALID_THEME` | `updateTheme` was given something other than `light`, `dark`, `system` or an object of theme settings; or a module refused a theme (`mounted.setTheme`, a mount call): the message names the setting. |
|
|
663
|
+
|
|
664
|
+
Load errors are `ModuleLoadError` and mount errors `ModuleMountError`; both are exported.
|
|
665
|
+
|
|
666
|
+
## Migrating from 0.0.x
|
|
667
|
+
|
|
668
|
+
0.1.0 is a breaking release. The API key left the browser, and a module is now one static file.
|
|
669
|
+
|
|
670
|
+
| Before | Now |
|
|
671
|
+
| --- | --- |
|
|
672
|
+
| `apiKey`, `partner.apiKey`, `StaticApiKeyProvider`, `EndpointTokenProvider`, `AuthManager` | `getToken` that returns an editor session token from your server |
|
|
673
|
+
| `initializeUISDK(...)`, `HighLevelUIAPI.initialize({ apiKey })` | `new WidgeticUI({ getToken })` or `mountModule(...)`. `HighLevelUIAPI.initialize({ getToken })` still works. |
|
|
674
|
+
| `MidLevelUIAPI`, `LowLevelUIAPI`, `HTTPClient`, `RegistryService`, `VersionManager`, `AccessManager`, `PlatformIntegration` | Removed. |
|
|
675
|
+
| Modules fetched from your own origin at `/modules/<type>/index.js`, with a development API address by default | Modules from `https://cdn.widgetic.com/modules`, API `https://api.widgetic.com`. |
|
|
676
|
+
| `widget-creator`, `embed-editor` | They were empty placeholders. `widget-creator` is now a real module (the whole canvas with the AI), as are `file-browser` and `composition-editor`; `embed-editor` does not exist (the composition editor has the embed settings). |
|
|
677
|
+
| The SDK set ~30 CSS variables on your `<html>`, cleared your container, and posted events to `window.parent` | It does none of that. |
|
|
678
|
+
|
|
679
|
+
`EventSystem`, `StateManager`, `ThemeManager`, `Core` and the validation helpers are still exported for code that used
|
|
680
|
+
them directly; they are deprecated and no longer used by the SDK itself.
|
|
681
|
+
|
|
682
|
+
## Development
|
|
683
|
+
|
|
684
|
+
```bash
|
|
685
|
+
npm install
|
|
686
|
+
npm test # unit tests (vitest, jsdom)
|
|
687
|
+
npm run build # dist/index.esm.js, dist/index.js, dist/umd/ui-sdk.js
|
|
688
|
+
npm run build:sdk # each part as its own IIFE and ES file in dist/browser and dist/esm, with no .env values
|
|
689
|
+
# (REPLICABLE=1). Not part of the npm package, and it empties dist/ first: run `npm run build` after it
|
|
690
|
+
```
|
|
691
|
+
|
|
692
|
+
The modules themselves (Svelte, the design system) live in [`modules/`](modules/README.md), a separate workspace so this
|
|
693
|
+
package stays free of them. Its browser tests also exercise this SDK as built: `cd modules && npm run build:file-browser
|
|
694
|
+
&& PLAYWRIGHT_CHANNEL=chrome npm run test:e2e` loads `dist/` from a CDN on another origin, with the real File Browser.
|
|
695
|
+
|
|
696
|
+
### Sibling packages
|
|
697
|
+
|
|
698
|
+
This package consumes sibling `@widgetic/*` checkouts through a link in `node_modules` that resolves the checkout
|
|
699
|
+
itself — its built output, not its source. The link is made by hand rather than through the `@widgetic/dev-tools`
|
|
700
|
+
dev-alias setup the adopting apps use, so a sibling edit stays invisible here until that package rebuilds its `dist/`.
|
|
701
|
+
Setup is the install script this package ships: it reinstalls and then links the sibling, so `node_modules` keeps
|
|
702
|
+
resolving the checkout rather than the published package. The dev-alias workflow these packages have not adopted, and
|
|
703
|
+
the reasons the adopting apps use it, are described in [the dev-tools README](../dev-tools/README.md).
|
|
704
|
+
|
|
705
|
+
The SDK itself no longer imports `@widgetic/api-sdk`; the one sibling linked here is the `api-sdk` checkout, for the
|
|
706
|
+
local demo app in `demo/`. `npm run i` is the whole setup: it reinstalls `node_modules`, then re-links that checkout.
|
|
707
|
+
|
|
708
|
+
```sh
|
|
709
|
+
npm run i # install, then link the api-sdk checkout
|
|
710
|
+
npm run lapisdk # re-link only, after a fresh node_modules
|
|
711
|
+
```
|
|
712
|
+
|
|
713
|
+
## Contributing
|
|
714
|
+
|
|
715
|
+
We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
|
|
716
|
+
|
|
717
|
+
## License
|
|
718
|
+
|
|
719
|
+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
|
720
|
+
|
|
721
|
+
## Support
|
|
722
|
+
|
|
723
|
+
- [Documentation](https://widgetic.mintlify.app)
|
|
724
|
+
- [Discord Community](https://discord.gg/widgetic)
|
|
725
|
+
- [Email Support](mailto:support@widgetic.com)
|
|
726
|
+
- [Report Issues](https://github.com/widgetic/widgetic-ui-sdk/issues)
|