@widgetic/ui-sdk 0.1.14 → 0.1.16
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 +33 -3
- package/dist/index.cjs +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/sdk/types/component.d.cts +4 -2
- package/dist/sdk/types/component.d.ts +4 -2
- package/dist/sdk/types/component.d.ts.map +1 -1
- package/dist/sdk/types/module-events.d.cts +22 -0
- package/dist/sdk/types/module-events.d.ts +22 -0
- package/dist/sdk/types/module-events.d.ts.map +1 -1
- package/dist/sdk/version.d.cts +1 -1
- package/dist/sdk/version.d.ts +1 -1
- package/dist/umd/ui-sdk.js +1 -1
- package/modules/README.md +179 -20
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -108,7 +108,7 @@ Mounts one module and resolves with a handle once it is on screen.
|
|
|
108
108
|
| `signal` | `AbortSignal` | Cancels the mount. See [Cancelling](#cancelling-a-mount). |
|
|
109
109
|
| `placeholder` | `boolean` | `false` skips the loading spinner shown while the module downloads. |
|
|
110
110
|
| `loadingLabel` | `string` | What a screen reader says for that spinner. Default `Loading`: give it in your visitors' language. |
|
|
111
|
-
| *anything else* | | Handed to the module. Every module: `themeFromHost` (see [Looking like your product](#looking-like-your-product)). File Browser: `maxSelections`, `initialFilter`, `selectLabel`, `messages`, `mediaLibrary`. Composition editor: `compositionId`, `mediaLibrary`, `pickFile`, `lockPreviewSize`, `googleFontsApiKey`, `autosaveDelayMs`, `presence`, `messages`. Widget creator: `canvasId`, `widgetId`, `startWithNewWidget`, `presets`, `startFromPreset`, `presetLabels`, `messages`, `mediaLibrary`, `pickFile`, `widgetBuilderUrl
|
|
111
|
+
| *anything else* | | Handed to the module. Every module: `themeFromHost` (see [Looking like your product](#looking-like-your-product)). File Browser: `maxSelections`, `initialFilter`, `selectLabel`, `messages`, `mediaLibrary`, `allowSelecting` (`false` for a library page: no ticking, no confirm button), `allowResumableUploads`. Composition editor: `compositionId`, `mediaLibrary`, `pickFile`, `lockPreviewSize`, `googleFontsApiKey`, `autosaveDelayMs`, `presence`, `messages`. Widget creator: `canvasId`, `widgetId`, `startWithNewWidget`, `presets`, `startFromPreset`, `presetLabels`, `messages`, `mediaLibrary`, `pickFile`, `widgetBuilderUrl`, `mascot`, `showCanvasFileBrowser` (a "Files" entry on the canvas that opens your `mediaLibrary`), and for a page that draws its own header around it `toolbarPosition`, `showSaveButton`, `showZoomControls`, `limitNotices`, `initialMessage` (see [The widget creator](#the-widget-creator)). Workflows: `workspaceId` (required), `workflowId`, `presence`, `messages`. The types of your library, your picker and the files they handle are exported (see [Your own files, typed](#your-own-files-typed)). |
|
|
112
112
|
|
|
113
113
|
The handle:
|
|
114
114
|
|
|
@@ -351,6 +351,34 @@ await creator.unmount();
|
|
|
351
351
|
points for a visitor who has made nothing yet".
|
|
352
352
|
- **Publishing** saves a version of the widget (the user can go back to an earlier one) and you hear `widgetPublished`.
|
|
353
353
|
A session can never make a widget public in Widgetic's catalogue: what a user builds stays private to your account.
|
|
354
|
+
- **Your own header around the creator.** A page that draws its own bar (a Back arrow, the name of the widget, a Publish
|
|
355
|
+
button) is given what it needs: `publishStateChanged` `{ widgetId, canPublish, publishing, label, unpublished }` says
|
|
356
|
+
what Publish would do now (`creator.module.getPublishState()` gives the last state to a button drawn later),
|
|
357
|
+
`await creator.module.publish()` presses it for the user, `await creator.module.flush()` puts what the user changed on
|
|
358
|
+
the server before your page takes them away, and `creator.module.setWidgetName(name, widgetId?)` renames a widget from
|
|
359
|
+
your own header (the creator shows and saves the name, and says `widgetRenamed`). The options that go with it:
|
|
360
|
+
`toolbarPosition: 'BL' | 'BC' | 'BR'` puts the drawing toolbar bottom left, bottom centre (the default) or bottom right,
|
|
361
|
+
for a page that has something of its own over the middle of the bottom edge; `showSaveButton: false` takes away the
|
|
362
|
+
canvas's Save button and its dot (the creator saves by itself, five seconds after the last change, at the latest fifteen
|
|
363
|
+
seconds into continuous work, and when the page is hidden or closed); `showZoomControls: false` takes away the canvas's
|
|
364
|
+
zoom buttons (the wheel, a pinch and the keyboard still zoom); `limitNotices: 'chat'` tells a refusal because of a
|
|
365
|
+
limit in the chat only, not also in a toast; `initialMessage: { text, send: true, attachments? }` puts words in the chat
|
|
366
|
+
of a new widget, with the photos you give it as `File`s, and sends them as the first message. A creator older than these ignores the options, and `publish()` and
|
|
367
|
+
`setWidgetName()` reject while `flush()` resolves at once. Details: `modules/README.md`, "A header of your own around
|
|
368
|
+
the creator".
|
|
369
|
+
- **Your files on the canvas.** `showCanvasFileBrowser: true` adds a "Files" entry to the canvas's Shapes menu (right before
|
|
370
|
+
"Image") that opens the File Browser in the state of choosing, so the user puts the pictures and SVG files they already
|
|
371
|
+
have on the sketch: it lists pictures and vector files only, and takes several at once. It lists YOUR `mediaLibrary` (the
|
|
372
|
+
one the chat and canvas uploads use; pass one whose `list` is implemented) and the user's own Widgetic uploads when you did
|
|
373
|
+
not pass one; with `pickFile` your own picker opens instead (asked for `image/*`, `image/svg+xml` and `.svg`, `multiple: true`). Default
|
|
374
|
+
`false`. Pictures on the sketch that are not in your library yet (a photo the user dropped, a drawing) are saved to it, in
|
|
375
|
+
the background, through your `mediaLibrary.upload` (`purpose: 'canvas'`) when the user sends their first message and when
|
|
376
|
+
the sketch is turned into the widget; taking a picture off the sketch never deletes the file from the library. The
|
|
377
|
+
assistant that sketches for the user can place SVG icons and pictures from that library. Details: `modules/README.md`,
|
|
378
|
+
option table of the widget creator.
|
|
379
|
+
- **The assistant's look.** The chat draws its assistant as Widgetic's animated mascot, a scribble that thinks, writes and
|
|
380
|
+
ends in its success or error look, with small sounds. `mascot: false` draws it as a plain round avatar and keeps the
|
|
381
|
+
chat silent; nothing else about the chat changes. Details: the option table of the widget creator in `modules/README.md`.
|
|
354
382
|
- **Credits and limits are yours.** The AI is paid for by your account, as your own calls are. When your credits run out
|
|
355
383
|
(or a plan limit or the storage limit is reached), the creator tells the user in plain words ("This is not available
|
|
356
384
|
right now. Please try again later.") and keeps working; it never shows what your account holds. Your page hears
|
|
@@ -442,7 +470,7 @@ await workflows.unmount();
|
|
|
442
470
|
[Speaking your visitors' language](#speaking-your-visitors-language)) and speaks the twelve languages of the other
|
|
443
471
|
modules from lazy packs (provisional until a native speaker has read them): a `locale` that has a pack shows its words
|
|
444
472
|
from the first paint, any other `locale` keeps the English, and your `messages` win over the pack, key by key.
|
|
445
|
-
`workflows.module.defaultMessages` lists the
|
|
473
|
+
`workflows.module.defaultMessages` lists the 439 messages with their English text, and
|
|
446
474
|
`workflows.module.checkMessages(messages)` reports mistakes in yours without mounting anything. A language written right
|
|
447
475
|
to left (Arabic, Hebrew, Persian, Urdu) turns the screen around, except the canvas, which is read from its first block
|
|
448
476
|
forward and is drawn left to right in every language.
|
|
@@ -600,7 +628,7 @@ files.setLanguage({ locale: '', messages: {} }); // back to Englis
|
|
|
600
628
|
saved into the chat stay English in the API and are translated on screen when the table knows them.
|
|
601
629
|
[The modules' README](modules/README.md#speaking-your-visitors-language) has the list.
|
|
602
630
|
- **Workflows** takes the same `locale`, `messages` and `setLanguage`, with **one** `messages` object for all of it: its
|
|
603
|
-
`workflows.` keys,
|
|
631
|
+
`workflows.` keys, 439 today (`workflows.module.defaultMessages` lists them). It has packs for the same twelve
|
|
604
632
|
languages as the other modules (`workflows.module.supportedLocales` lists them, every one provisional): a `locale` that
|
|
605
633
|
has a pack shows its words, one that has not keeps the English, and in both it sets the plural rules your messages use
|
|
606
634
|
and which way the screen reads. Your `messages` win over the pack, key by key. The `message` of its `error` events stays
|
|
@@ -622,6 +650,7 @@ files.setLanguage({ locale: '', messages: {} }); // back to Englis
|
|
|
622
650
|
| `presetChosen` | `{ key, canvasId, widgetId, widgetName, warnings, automatic }` | Widget creator: a starting point was chosen, before the creator opens on the copy. `key`, `canvasId`, `widgetId` and `widgetName` are `null` when the visitor chose *Start from scratch*; `automatic` is `true` when your `startFromPreset` was copied for them; `warnings` are sentences for you, not the visitor (usually empty). The creator then says `canvasChanged` for the copy. |
|
|
623
651
|
| `widgetRenamed` | `{ widgetId, name }` | Widget creator: the main widget has this name (said when the canvas opens and each time the user renames it). |
|
|
624
652
|
| `widgetPublished` | `{ widgetId, version? }` | Widget creator: the user published a version of a widget. |
|
|
653
|
+
| `publishStateChanged` | `{ widgetId, canPublish, publishing, label, unpublished }` | Widget creator: what Publish would do now, for a page that draws its own Publish button (`creator.module.publish()` presses it). Said when the creator first knows and at every change, never twice with the same state. |
|
|
625
654
|
| `limitReached` | `{ message, code? }` | Widget creator: the user ran into a limit (credits, plan, storage, allowance). The creator has told them already. |
|
|
626
655
|
| `reloadRequested` | | Widget creator: it would have reloaded the page to recover. Unmount it and mount a new one. |
|
|
627
656
|
| `openWorkflow` | `{ workflowId }` | Workflows: the person opened a workflow, or went back to the list (`workflowId: null`). Keep your address in step; the screen has moved itself. |
|
|
@@ -651,6 +680,7 @@ const reportError = (error: CompositionEditorEvents['error']) => report(error.co
|
|
|
651
680
|
```
|
|
652
681
|
|
|
653
682
|
The types are exported: `FileBrowserEvents`, `CompositionEditorEvents`, `WidgetCreatorEvents` and `WorkflowsEvents` (one property per event);
|
|
683
|
+
`WidgetCreatorPublishState` (what `publishStateChanged` carries);
|
|
654
684
|
`PickedFile` and `LibraryAction` (what `select` and the File Browser's `error` carry); `ModuleErrorEvent` (what every
|
|
655
685
|
`error` carries), with `FileBrowserErrorEvent`, `CompositionEditorErrorEvent` and `WidgetCreatorErrorEvent` for what each
|
|
656
686
|
module adds, and `CompositionEditorErrorDuring` and `WidgetCreatorErrorDuring` for the values of `during`;
|
package/dist/index.cjs
CHANGED
|
@@ -2482,7 +2482,7 @@ function createSecureContext(allowedOrigins = []) {
|
|
|
2482
2482
|
* `scripts-sdk/check-version.js` fails `npm run build` when the two disagree, and
|
|
2483
2483
|
* `tests/unit/version.test.ts` fails the same way in the suite.
|
|
2484
2484
|
*/
|
|
2485
|
-
const SDK_VERSION = '0.1.
|
|
2485
|
+
const SDK_VERSION = '0.1.16';
|
|
2486
2486
|
const SDK_NAME = '@widgetic/ui-sdk';
|
|
2487
2487
|
|
|
2488
2488
|
/**
|
package/dist/index.esm.js
CHANGED
|
@@ -2478,7 +2478,7 @@ function createSecureContext(allowedOrigins = []) {
|
|
|
2478
2478
|
* `scripts-sdk/check-version.js` fails `npm run build` when the two disagree, and
|
|
2479
2479
|
* `tests/unit/version.test.ts` fails the same way in the suite.
|
|
2480
2480
|
*/
|
|
2481
|
-
const SDK_VERSION = '0.1.
|
|
2481
|
+
const SDK_VERSION = '0.1.16';
|
|
2482
2482
|
const SDK_NAME = '@widgetic/ui-sdk';
|
|
2483
2483
|
|
|
2484
2484
|
/**
|
|
@@ -121,12 +121,14 @@ export interface MountConfig<Name extends ModuleName = ModuleName> {
|
|
|
121
121
|
/**
|
|
122
122
|
* The File Browser, the composition editor and the widget creator: your own media library, so that their pickers
|
|
123
123
|
* show your files and not the user's Widgetic uploads. Only `list` is required; `urlResolver` turns a listed
|
|
124
|
-
* address into the one that is saved.
|
|
124
|
+
* address into the one that is saved. The widget creator also lists it in the canvas's "Files" entry when you turn
|
|
125
|
+
* on `showCanvasFileBrowser: true` (an option of the widget creator), limited to pictures and SVG files.
|
|
125
126
|
*/
|
|
126
127
|
mediaLibrary?: PartnerMediaLibrary;
|
|
127
128
|
/**
|
|
128
129
|
* The composition editor and the widget creator: your own picker for file fields, instead of the File Browser.
|
|
129
|
-
* Resolve the files chosen, or `[]` when the visitor cancelled.
|
|
130
|
+
* Resolve the files chosen, or `[]` when the visitor cancelled. The widget creator also calls it for the canvas's
|
|
131
|
+
* "Files" entry (`showCanvasFileBrowser: true`), asking for pictures and SVG files, several at once.
|
|
130
132
|
*/
|
|
131
133
|
pickFile?: PickFileFn;
|
|
132
134
|
/**
|
|
@@ -121,12 +121,14 @@ export interface MountConfig<Name extends ModuleName = ModuleName> {
|
|
|
121
121
|
/**
|
|
122
122
|
* The File Browser, the composition editor and the widget creator: your own media library, so that their pickers
|
|
123
123
|
* show your files and not the user's Widgetic uploads. Only `list` is required; `urlResolver` turns a listed
|
|
124
|
-
* address into the one that is saved.
|
|
124
|
+
* address into the one that is saved. The widget creator also lists it in the canvas's "Files" entry when you turn
|
|
125
|
+
* on `showCanvasFileBrowser: true` (an option of the widget creator), limited to pictures and SVG files.
|
|
125
126
|
*/
|
|
126
127
|
mediaLibrary?: PartnerMediaLibrary;
|
|
127
128
|
/**
|
|
128
129
|
* The composition editor and the widget creator: your own picker for file fields, instead of the File Browser.
|
|
129
|
-
* Resolve the files chosen, or `[]` when the visitor cancelled.
|
|
130
|
+
* Resolve the files chosen, or `[]` when the visitor cancelled. The widget creator also calls it for the canvas's
|
|
131
|
+
* "Files" entry (`showCanvasFileBrowser: true`), asking for pictures and SVG files, several at once.
|
|
130
132
|
*/
|
|
131
133
|
pickFile?: PickFileFn;
|
|
132
134
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"component.d.ts","sourceRoot":"","sources":["../../../src/sdk/types/component.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAClE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,KAAK,EAAE,mBAAmB,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AACjF,OAAO,KAAK,EAAE,mBAAmB,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AACnG,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAEjD;;;;;GAKG;AACH,MAAM,WAAW,mBAAmB;IAChC,MAAM,EAAE,SAAS,GAAG,UAAU,GAAG,SAAS,CAAC;CAC9C;AAED;;;;GAIG;AACH,MAAM,MAAM,WAAW,GACjB,MAAM,GACN;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,M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W,CAAC;IACvB,MAAM,EAAE,MAAM,CAAC;IACf,2EAA2E;IAC3E,EAAE,EAAE,CAAC,KAAK,SAAS,eAAe,CAAC,IAAI,CAAC,EACpC,SAAS,EAAE,KAAK,EAChB,OAAO,EAAE,CAAC,OAAO,EAAE,kBAAkB,CAAC,IAAI,EAAE,KAAK,CAAC,KAAK,IAAI,KAC1D,MAAM,IAAI,CAAC;IAChB,qDAAqD;IACrD,GAAG,EAAE,CAAC,KAAK,SAAS,eAAe,CAAC,IAAI,CAAC,EACrC,SAAS,EAAE,KAAK,EAChB,OAAO,EAAE,CAAC,OAAO,EAAE,kBAAkB,CAAC,IAAI,EAAE,KAAK,CAAC,KAAK,IAAI,KAC1D,IAAI,CAAC;IACV;;;;OAIG;IACH,QAAQ,EAAE,CAAC,KAAK,EAAE,WAAW,KAAK,IAAI,CAAC;IACvC;;;;;OAKG;IACH,WAAW,EAAE,CAAC,QAAQ,EAAE,cAAc,KAAK,IAAI,CAAC;IAChD,OAAO,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAChC;AAED;;;GAGG;AACH,MAAM,MAAM,aAAa,GACnB,gBAAgB,GAChB,oBAAoB,GACpB,cAAc,GACd,cAAc,GACd,WAAW,CAAC;AAElB;;;GAGG;AACH,MAAM,MAAM,UAAU,GAAG,aAAa,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC;AAEvD;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;CACjB;AAED,wCAAwC;AACxC,MAAM,MAAM,iBAAiB,GAAG,cAAc,CAAC"}
|
|
@@ -200,6 +200,19 @@ export interface CompositionEditorEvents {
|
|
|
200
200
|
presence: CompositionEditorPresenceEvent;
|
|
201
201
|
error: CompositionEditorErrorEvent;
|
|
202
202
|
}
|
|
203
|
+
/** What Publish would do now: the payload of the widget creator's `publishStateChanged` event and `getPublishState()`. */
|
|
204
|
+
export interface WidgetCreatorPublishState {
|
|
205
|
+
/** The widget `publish()` would publish; `null` while there is none yet. */
|
|
206
|
+
widgetId: string | null;
|
|
207
|
+
/** Publish can be pressed now: the widget has something to publish and nothing is running. */
|
|
208
|
+
canPublish: boolean;
|
|
209
|
+
/** A publish of that widget is running. */
|
|
210
|
+
publishing: boolean;
|
|
211
|
+
/** The words the creator's own Publish button would carry ("Publish", "Publish changes"). */
|
|
212
|
+
label: string;
|
|
213
|
+
/** The widget has changes that no published version has. */
|
|
214
|
+
unpublished: boolean;
|
|
215
|
+
}
|
|
203
216
|
/** The events of the widget creator (`'widget-creator'`): what `on` and `mounted.on` take, and the payload of each. */
|
|
204
217
|
export interface WidgetCreatorEvents {
|
|
205
218
|
/** The first canvas has loaded and the creator is ready to be used. `canvasId` is the one that is open. */
|
|
@@ -243,6 +256,15 @@ export interface WidgetCreatorEvents {
|
|
|
243
256
|
widgetId: string;
|
|
244
257
|
name: string;
|
|
245
258
|
};
|
|
259
|
+
/**
|
|
260
|
+
* What Publish would do now, for a page that draws its own Publish button next to the creator: `canPublish` (the
|
|
261
|
+
* widget has something to publish and nothing is running), `publishing` (a publish of that widget is running), `label`
|
|
262
|
+
* (the words the creator's own button would carry, "Publish" or "Publish changes", in your page's language) and
|
|
263
|
+
* `unpublished` (the widget has changes no published version has), for `widgetId`, the widget `publish()` would
|
|
264
|
+
* publish (`null` while there is none). Said when the creator first knows, then at every change and never twice with
|
|
265
|
+
* the same state; `getPublishState()` gives the last one to a page that draws its button later.
|
|
266
|
+
*/
|
|
267
|
+
publishStateChanged: WidgetCreatorPublishState;
|
|
246
268
|
/**
|
|
247
269
|
* The user ran into a limit (credits used up, a cap reached, the storage full). The creator tells the user itself, in
|
|
248
270
|
* plain words; this is for your page, for instance to offer more. `code` is what the API answered
|
|
@@ -200,6 +200,19 @@ export interface CompositionEditorEvents {
|
|
|
200
200
|
presence: CompositionEditorPresenceEvent;
|
|
201
201
|
error: CompositionEditorErrorEvent;
|
|
202
202
|
}
|
|
203
|
+
/** What Publish would do now: the payload of the widget creator's `publishStateChanged` event and `getPublishState()`. */
|
|
204
|
+
export interface WidgetCreatorPublishState {
|
|
205
|
+
/** The widget `publish()` would publish; `null` while there is none yet. */
|
|
206
|
+
widgetId: string | null;
|
|
207
|
+
/** Publish can be pressed now: the widget has something to publish and nothing is running. */
|
|
208
|
+
canPublish: boolean;
|
|
209
|
+
/** A publish of that widget is running. */
|
|
210
|
+
publishing: boolean;
|
|
211
|
+
/** The words the creator's own Publish button would carry ("Publish", "Publish changes"). */
|
|
212
|
+
label: string;
|
|
213
|
+
/** The widget has changes that no published version has. */
|
|
214
|
+
unpublished: boolean;
|
|
215
|
+
}
|
|
203
216
|
/** The events of the widget creator (`'widget-creator'`): what `on` and `mounted.on` take, and the payload of each. */
|
|
204
217
|
export interface WidgetCreatorEvents {
|
|
205
218
|
/** The first canvas has loaded and the creator is ready to be used. `canvasId` is the one that is open. */
|
|
@@ -243,6 +256,15 @@ export interface WidgetCreatorEvents {
|
|
|
243
256
|
widgetId: string;
|
|
244
257
|
name: string;
|
|
245
258
|
};
|
|
259
|
+
/**
|
|
260
|
+
* What Publish would do now, for a page that draws its own Publish button next to the creator: `canPublish` (the
|
|
261
|
+
* widget has something to publish and nothing is running), `publishing` (a publish of that widget is running), `label`
|
|
262
|
+
* (the words the creator's own button would carry, "Publish" or "Publish changes", in your page's language) and
|
|
263
|
+
* `unpublished` (the widget has changes no published version has), for `widgetId`, the widget `publish()` would
|
|
264
|
+
* publish (`null` while there is none). Said when the creator first knows, then at every change and never twice with
|
|
265
|
+
* the same state; `getPublishState()` gives the last one to a page that draws its button later.
|
|
266
|
+
*/
|
|
267
|
+
publishStateChanged: WidgetCreatorPublishState;
|
|
246
268
|
/**
|
|
247
269
|
* The user ran into a limit (credits used up, a cap reached, the storage full). The creator tells the user itself, in
|
|
248
270
|
* plain words; this is for your page, for instance to offer more. `code` is what the API answered
|
|
@@ -1 +1 @@
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,CAAC;AAEF,0GAA0G;AAC1G,MAAM,MAAM,eAAe,CAAC,IAAI,SAAS,MAAM,GAAG,MAAM,IAAI,OAAO,CAAC,MAAM,YAAY,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,CAAC;AAEtG,oGAAoG;AACpG,MAAM,MAAM,kBAAkB,CAAC,IAAI,SAAS,MAAM,EAAE,KAAK,SAAS,eAAe,CAAC,IAAI,CAAC,IACnF,YAAY,CAAC,IAAI,CAAC,CAAC,KAAK,GAAG,MAAM,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC"}
|
package/dist/sdk/version.d.cts
CHANGED
|
@@ -6,5 +6,5 @@
|
|
|
6
6
|
* `scripts-sdk/check-version.js` fails `npm run build` when the two disagree, and
|
|
7
7
|
* `tests/unit/version.test.ts` fails the same way in the suite.
|
|
8
8
|
*/
|
|
9
|
-
export declare const SDK_VERSION = "0.1.
|
|
9
|
+
export declare const SDK_VERSION = "0.1.16";
|
|
10
10
|
export declare const SDK_NAME = "@widgetic/ui-sdk";
|
package/dist/sdk/version.d.ts
CHANGED
|
@@ -6,6 +6,6 @@
|
|
|
6
6
|
* `scripts-sdk/check-version.js` fails `npm run build` when the two disagree, and
|
|
7
7
|
* `tests/unit/version.test.ts` fails the same way in the suite.
|
|
8
8
|
*/
|
|
9
|
-
export declare const SDK_VERSION = "0.1.
|
|
9
|
+
export declare const SDK_VERSION = "0.1.16";
|
|
10
10
|
export declare const SDK_NAME = "@widgetic/ui-sdk";
|
|
11
11
|
//# sourceMappingURL=version.d.ts.map
|
package/dist/umd/ui-sdk.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).WidgeticUISDK={})}(this,function(e){"use strict";class t{static createError(e,t){const s=new Error(e);return s.code=t,s}static handleError(e,t){return e instanceof Error?e.code?e:this.createError(e.message,"UNKNOWN_ERROR"):"string"==typeof e?this.createError(e,"STRING_ERROR"):this.createError(`Unknown error in ${t}`,"UNKNOWN_ERROR")}static toSDKError(e){return{message:e.message,code:e.code||"UNKNOWN_ERROR",name:e.name,stack:e.stack,details:e}}}class s extends Error{constructor(e,t){super(e),this.field=t,this.name="ValidationError"}}class r extends Error{constructor(e,t){super(e),this.code=t,this.name="SecurityError"}}class n extends Error{constructor(e,t){super(e),this.componentId=t,this.name="ComponentError"}}class o{static validateId(e,s){if(!e||"string"!=typeof e||""===e.trim())throw t.createError(`Invalid ID provided in ${s}`,"INVALID_ID")}static validateContainer(e,s){if(o.requireBrowser(s),!e)throw t.createError(`Container is required in ${s}`,"MISSING_CONTAINER");if("string"==typeof e){const s=document.querySelector(e);if(!s)throw t.createError(`Container not found: ${e}`,"CONTAINER_NOT_FOUND");return s}if(!(e instanceof HTMLElement))throw t.createError(`Invalid container type in ${s}`,"INVALID_CONTAINER");return e}static requireBrowser(e){if("undefined"==typeof document)throw t.createError(`Widgetic modules can only be used in a browser (${e}). With server-side rendering, start them from an effect or an event handler, which only run on the client.`,"NOT_IN_BROWSER")}static rejectApiKey(e){const s=e??{},r=s.partner;if(void 0!==s.apiKey||void 0!==r?.apiKey)throw t.createError("The apiKey option is not accepted: an API key must never be in a browser. Mint an editor session on your server (POST /v1/managed-users/{id}/editor-sessions) and return its token from the getToken option.","API_KEY_NOT_ALLOWED")}static validateConfig(e,s,r){if(!e)throw t.createError(`Configuration is required in ${r}`,"MISSING_CONFIG");for(const n of s)if(!(n in e))throw t.createError(`Missing required field: ${String(n)} in ${r}`,"MISSING_REQUIRED_FIELD")}static validateEventType(e,s){if(!s.includes(e))throw t.createError(`Invalid event type: ${e}`,"INVALID_EVENT_TYPE")}static validateFileUpload(e,s,r){if(e.size>s)throw t.createError(`File size exceeds maximum allowed size of ${s} bytes`,"FILE_TOO_LARGE");if(!r.includes("*/*")&&!r.includes(e.type))throw t.createError(`File type ${e.type} is not allowed`,"INVALID_FILE_TYPE")}}const i=["mode","preset","colors","radius","font"],a=["light","dark","system"],c="(prefers-color-scheme: dark)";function h(e){return"string"==typeof e&&a.includes(e)}function d(e){const t="string"==typeof e?e:e?.mode;return h(t)?t:void 0}function l(e){if(!e||"object"!=typeof e||Array.isArray(e))return;const t=Object.fromEntries(Object.entries(e).filter(([e,t])=>"mode"!==e&&void 0!==t));return Object.keys(t).length>0?t:void 0}function u(e){return"system"===e?"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia(c).matches?"dark":"light":"dark"===e?"dark":"light"}function m(e,t){const s=d(e),r=s?u(s):t.mode,n=l(e)??t.settings;return n?{...n,mode:r}:r}class f extends Error{constructor(e,t){super(`The "${e}" module failed to start: ${t instanceof Error?t.message:String(t)}`),this.code="MOUNT_FAILED",this.name="ModuleMountError",this.moduleName=e,this.cause=t,Object.setPrototypeOf(this,f.prototype)}}class g{constructor(e,t){this.events=e,this.options=t,this.active=new Map}async mount(e,s){o.rejectApiKey(s);const r=o.validateContainer(s.container,"LifecycleManager.mount"),{version:n,theme:i,placeholder:a,loadingLabel:c,on:h,callbacks:d,signal:u,...g}=s,y=function(e){const t={...e};return delete t.container,t}(g),w=this.generateInstanceId(),E=!1===a?null:this.showPlaceholder(r,e,c);let M=null;const S=[];try{p(u,e);const t=await this.options.loader.load(e,{version:n});p(u,e);const{getToken:s,apiUrl:o,locale:a}=this.options.moduleDefaults;try{M=new t.Module(r,{apiUrl:o,locale:a,...s?{getToken:async e=>s(e)}:{},...y,theme:m(i,{mode:this.options.getThemeMode(),settings:this.options.getThemeSettings?.()})}),S.push(...this.connectEvents(w,M,{on:h,callbacks:d})),await M.mount()}catch(t){throw new f(e,t)}p(u,e);const c=this.createMountedModule(w,e,t.version,r,M);return this.active.set(w,{mounted:c,stopListening:S,hasOwnSettings:void 0!==l(i)}),c}catch(e){for(const e of S)e();throw await this.unmountQuietly(M),t.handleError(e,"LifecycleManager.mount")}finally{E?.remove()}}async unmount(e){const s=this.active.get(e);if(!s)throw t.createError(`No instance found for ID: ${e}`,"INSTANCE_NOT_FOUND");this.active.delete(e);try{await(s.mounted.module.unmount?.())}finally{for(const e of s.stopListening)e()}}get(e){return this.active.get(e)?.mounted}setThemeMode(e){for(const{mounted:t}of this.active.values())this.tellModule(t,e)}setDefaultTheme(e,t,s=!0){for(const{mounted:r,hasOwnSettings:n}of this.active.values())n?s&&this.tellModule(r,t):this.tellModule(r,{...e,mode:t})}tellModule(e,t){try{e.module.setTheme?.(t)}catch(s){console.error(`[widgetic-ui] The "${e.type}" module could not apply the theme ${JSON.stringify(t)}:`,s)}}async cleanup(){const e=await Promise.allSettled([...this.active.keys()].map(e=>this.unmount(e)));for(const t of e)"rejected"===t.status&&console.error("[widgetic-ui] A module failed to unmount during cleanup:",t.reason)}connectEvents(e,t,{on:s,callbacks:r}){const n=[];if("function"!=typeof t.on)return n;const o=(e,s)=>{n.push(t.on(e,s))};for(const[e,t]of Object.entries(s??{}))"function"==typeof t&&o(e,t);return o("ready",()=>{r?.onReady?.(),this.events.emit("ready",{componentId:e})}),o("error",t=>{const s=function(e){if(e instanceof Error)return e;const{message:t,code:s,fatal:r}=e??{},n=new Error("string"==typeof t?t:"The module reported an error");"string"==typeof s&&(n.code=s);"boolean"==typeof r&&(n.fatal=r);return n}(t);r?.onError?.(s),this.events.emit("error",{componentId:e,error:s})}),n}createMountedModule(e,t,s,r,n){return{id:e,type:t,version:s,container:r,module:n,on:(e,s)=>"function"!=typeof n.on?(console.warn(`[widgetic-ui] The "${t}" module does not report events.`),()=>{}):n.on(e,s),off:(e,t)=>n.off?.(e,t),setTheme:s=>{if("function"!=typeof n.setTheme)return void console.warn(`[widgetic-ui] The "${t}" module cannot change its look.`);n.setTheme(s);const r=this.active.get(e);r&&"object"==typeof s&&(r.hasOwnSettings=!0)},setLanguage:e=>{"function"==typeof n.setLanguage?n.setLanguage(e):console.warn(`[widgetic-ui] The "${t}" module has no words to translate yet.`)},unmount:()=>this.unmount(e)}}async unmountQuietly(e){try{await(e?.unmount?.())}catch(e){console.warn("[widgetic-ui] A module that failed to start also failed to clean up:",e)}}showPlaceholder(e,t,s){const r=document.createElement("div");r.setAttribute("data-widgetic-ui-loading",t),r.setAttribute("role","status"),r.setAttribute("aria-label","string"==typeof s&&""!==s.trim()?s:"Loading"),Object.assign(r.style,{display:"flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box",width:"100%",minHeight:this.getComponentMinHeight(t)});const n=document.createElement("div");return Object.assign(n.style,{width:"28px",height:"28px",border:"3px solid rgba(128, 128, 128, 0.25)",borderTopColor:"#3b82f6",borderRadius:"50%"}),"function"==typeof n.animate&&n.animate([{transform:"rotate(0deg)"},{transform:"rotate(360deg)"}],{duration:1e3,iterations:1/0}),r.appendChild(n),e.appendChild(r),r}getComponentMinHeight(e){switch(e){case"widget-creator":case"composition-editor":case"workflows":return"480px";case"embed-editor":case"file-browser":return"380px";default:return"280px"}}generateInstanceId(){return`widgetic-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}}function p(e,s){if(e?.aborted){const e=t.createError(`Mounting the "${s}" module was cancelled.`,"MOUNT_ABORTED");throw e.name="AbortError",e}}class y{constructor(){this.handlers=new Map}on(e,t){const s=this.handlers.get(e)??new Set;return s.add(t),this.handlers.set(e,s),()=>this.off(e,t)}off(e,t){const s=this.handlers.get(e);s&&(s.delete(t),0===s.size&&this.handlers.delete(e))}emit(e,t){const s=this.handlers.get(e);if(!s)return;const r={type:e,...t,timestamp:Date.now()};for(const t of[...s])try{t(r)}catch(t){console.error(`[widgetic-ui] A handler for "${e}" threw:`,t)}}destroy(){this.handlers.clear()}}const w="https://api.widgetic.com",E="https://cdn.widgetic.com/modules",M={NODE_ENV:"production",API_URL:w,API_VERSION:"/v1",CLIENT_URL:"https://widgetic.com",PRODUCTION_URL:w,CDN_URL:"https://cdn.widgetic.com",EMBED_SDK_URL:"/sdks/browser/embed-sdk.js"};class S{constructor(){this.config={...M}}static getInstance(){return S.instance||(S.instance=new S),S.instance}initialize(e){this.config={...M,...e}}getApiUrl(){return(this.isProduction?this.config.PRODUCTION_URL:this.config.API_URL)+this.config.API_VERSION}getCdnUrl(){return this.config.CDN_URL}get isProduction(){return"production"===this.config.NODE_ENV}validateConfig(){if(!this.config.API_URL)throw new Error("API_URL is required");if(!this.config.API_VERSION)throw new Error("API_VERSION is required");if(!this.config.CLIENT_URL)throw new Error("CLIENT_URL is required")}}const v=S.getInstance();class I extends Error{constructor(e,t,s){super(t),this.name="ModuleLoadError",this.code=e,this.moduleName=s.moduleName,this.url=s.url,this.cause=s.cause,Object.setPrototypeOf(this,I.prototype)}}const T=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,L=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?$/,b=[300,900],_=e=>import(e);class N{constructor(e={}){this.loads=new Map,this.baseUrl=function(e){const t="undefined"!=typeof document?document.baseURI:"http://localhost/";let s;try{s=new URL(e,t)}catch(t){throw new I("INVALID_MODULE_BASE_URL",`moduleBaseUrl is not an address: ${e}`,{moduleName:"",cause:t})}if("https:"!==s.protocol&&"http:"!==s.protocol)throw new I("INVALID_MODULE_BASE_URL",`moduleBaseUrl must be an http(s) address, got ${s.protocol}`,{moduleName:""});s.pathname.endsWith("/")||(s.pathname+="/");return s}(e.moduleBaseUrl??E),this.fetchImpl=e.fetchImpl??((e,t)=>fetch(e,t)),this.importImpl=e.importImpl??_,this.retryDelaysMs=e.retryDelaysMs??b}async load(e,t={}){!function(e){if("string"!=typeof e||e.length>64||!T.test(e))throw new I("INVALID_MODULE_NAME",`"${String(e)}" is not a module name. Use lowercase letters, digits and dashes, like "file-browser".`,{moduleName:String(e)})}(e);const s=t.version;void 0!==s&&function(e,t){if("string"!=typeof t||!L.test(t))throw new I("INVALID_VERSION",`"${String(t)}" is not a version. Use an exact version like "1.2.0".`,{moduleName:e})}(e,s);const r=`${e}@${s??"latest"}`,n=this.loads.get(r);if(n)return n;const o=this.loadUncached(e,s).catch(e=>{throw this.loads.delete(r),e});return this.loads.set(r,o),o}async loadUncached(e,t){let s,r;if(void 0!==t)s=t,r=new URL(`${e}/${t}/index.js`,this.baseUrl);else{const t=await this.fetchManifest(e);s=t.version,r=this.resolveEntryUrl(e,t)}return{Module:await this.importModuleFile(e,r),name:e,version:s,url:r.href}}async fetchManifest(e){const t=new URL(`${e}/manifest.json`,this.baseUrl);try{return await this.withRetries(async()=>{const s=await this.fetchImpl(t.href,{credentials:"omit"});if(404===s.status||403===s.status)throw new I("MODULE_NOT_FOUND",`There is no "${e}" module at ${t.href} (HTTP ${s.status}).`,{moduleName:e,url:t.href});if(!s.ok)throw new Error(`HTTP ${s.status} for ${t.href}`);let r;try{r=await s.json()}catch(s){throw new I("MANIFEST_INVALID",`The manifest at ${t.href} is not JSON.`,{moduleName:e,url:t.href,cause:s})}return this.validateManifest(e,t,r)})}catch(s){if(s instanceof I)throw s;throw new I("MANIFEST_UNAVAILABLE",`Could not load the manifest of "${e}" from ${t.href}: ${O(s)}`,{moduleName:e,url:t.href,cause:s})}}validateManifest(e,t,s){const r=s=>{throw new I("MANIFEST_INVALID",`The manifest at ${t.href} ${s}.`,{moduleName:e,url:t.href})};if("object"!=typeof s||null===s)return r("is not a JSON object");const{name:n,version:o,entry:i}=s;return n!==e?r(`is for "${String(n)}", not "${e}"`):"string"==typeof o&&L.test(o)?"string"!=typeof i||0===i.length?r('has no "entry"'):{name:n,version:o,entry:i}:r(`has no valid "version" (found ${JSON.stringify(o)})`)}resolveEntryUrl(e,t){const s=new URL(`${e}/manifest.json`,this.baseUrl),r=new URL(`${e}/`,this.baseUrl);let n;try{n=new URL(t.entry,s)}catch(r){throw new I("MANIFEST_INVALID",`The manifest of "${e}" has an "entry" that is not an address: ${t.entry}`,{moduleName:e,url:s.href,cause:r})}const o=n.origin===r.origin&&n.pathname.startsWith(r.pathname),i=/\.m?js$/.test(n.pathname);if(!o||!i)throw new I("MANIFEST_INVALID",`The manifest of "${e}" points at ${n.href}, which is not a script inside ${r.href}.`,{moduleName:e,url:s.href});return n}async importModuleFile(e,t){let s;try{s=await this.withRetries(async e=>{const s=0===e?t.href:function(e,t){const s=new URL(e.href);return s.searchParams.set("retry",String(t)),s.href}(t,e);return this.importImpl(s)})}catch(s){throw new I("MODULE_LOAD_FAILED",`Could not load the "${e}" module from ${t.href}: ${O(s)}`,{moduleName:e,url:t.href,cause:s})}const r=s?.default;if("function"!=typeof r)throw new I("MODULE_INVALID",`The file at ${t.href} does not export a module class as its default export.`,{moduleName:e,url:t.href});return r}async withRetries(e){let t;for(let s=0;s<=this.retryDelaysMs.length;s++)try{return await e(s)}catch(e){if(e instanceof I)throw e;t=e;const r=this.retryDelaysMs[s];void 0!==r&&await new Promise(e=>setTimeout(e,r))}throw t}}function O(e){return e instanceof Error?e.message:String(e)}const U=new Map;class ${constructor(e={}){this.stopWatchingSystemTheme=null,function(e){o.rejectApiKey(e);const s=e?.getToken;if(void 0!==s&&"function"!=typeof s)throw t.createError("WidgeticUI: getToken must be a function that resolves an editor session token (or { token, expiresAt }) minted by your server.","INVALID_GET_TOKEN")}(e),this.events=new y,this.loader=e.moduleLoader??function(e){let t=U.get(e);return t||(t=new N({moduleBaseUrl:e}),U.set(e,t)),t}(e.moduleBaseUrl??E),this.themeMode=d(e.theme)??"light",this.themeSettings=l(e.theme),this.lifecycleManager=new g(this.events,{loader:this.loader,moduleDefaults:{apiUrl:e.apiUrl??w,getToken:e.getToken,locale:e.locale},getThemeMode:()=>u(this.themeMode),getThemeSettings:()=>this.themeSettings}),this.followSystemThemeWhenAsked()}async mount(e,t){try{return await this.lifecycleManager.mount(e,t)}catch(e){if("MOUNT_ABORTED"===e?.code)throw e;throw console.error("Error mounting component:",e),t.callbacks?.onError?.(e),e}}async mountComponent(e,t){return(await this.mount(e,t)).id}async unmountComponent(e){try{await this.lifecycleManager.unmount(e)}catch(e){throw console.error("Error unmounting component:",e),e}}getComponent(e){return this.lifecycleManager.get(e)}async preload(e,t={}){o.requireBrowser(`preloading "${e}"`),await this.loader.load(e,t)}updateTheme(e){if(!function(e){if("string"==typeof e)return h(e);if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.entries(e).filter(([,e])=>void 0!==e);if(0===t.length)return!1;if(!t.every(([e])=>i.includes(e)))return!1;const s=e.mode;return void 0===s||h(s)}(e))throw t.createError(`Unknown theme: ${JSON.stringify(e)}. Use 'light', 'dark', 'system', or an object with some of mode, preset, colors, radius, font.`,"INVALID_THEME");const s=d(e),r=l(e);s&&(this.themeMode=s),r&&(this.themeSettings=r),this.followSystemThemeWhenAsked();const n=u(this.themeMode);r?this.lifecycleManager.setDefaultTheme(r,n,void 0!==s):this.lifecycleManager.setThemeMode(n),this.events.emit("theme:update",{theme:r?{...r,mode:this.themeMode}:{mode:this.themeMode}})}getTheme(){return{mode:this.themeMode,...this.themeSettings}}on(e,t){return this.events.on(e,t)}off(e,t){this.events.off(e,t)}emit(e,t){this.events.emit(e,t)}async destroy(){this.stopWatchingSystemTheme?.(),this.stopWatchingSystemTheme=null,await this.lifecycleManager.cleanup(),this.events.destroy()}followSystemThemeWhenAsked(){this.stopWatchingSystemTheme?.(),this.stopWatchingSystemTheme=null,"system"===this.themeMode&&(this.stopWatchingSystemTheme=function(e){if("undefined"==typeof window||"function"!=typeof window.matchMedia)return()=>{};const t=window.matchMedia(c),s=t=>e(t.matches?"dark":"light");return t.addEventListener("change",s),()=>t.removeEventListener("change",s)}(e=>this.lifecycleManager.setThemeMode(e)))}}async function A(e,t){o.rejectApiKey(t);const{getToken:s,apiUrl:r,moduleBaseUrl:n,locale:i,moduleLoader:a,...c}=t,h=new $({getToken:s,apiUrl:r,moduleBaseUrl:n,locale:i,moduleLoader:a,theme:c.theme});let d;try{d=await h.mount(e,c)}catch(e){throw await h.destroy(),e}return{...d,unmount:async()=>{try{await d.unmount()}finally{await h.destroy()}}}}let D=null;function C(){if(!D)throw t.createError("Call HighLevelUIAPI.initialize({ getToken }) before mounting a component.","NOT_INITIALIZED");return D}const R={WidgeticUI:$,initialize:async e=>{const t=new $(e),s=D;return D=t,await(s?.destroy()),t},mountComponent:async(e,t,s={})=>C().mountComponent(e,{...s,container:t}),unmountComponent:async e=>{await C().unmountComponent(e)}};const P={mode:"light",colors:{primary:"#007bff",secondary:"#6c757d",background:"#ffffff",surface:"#f8f9fa",text:"#212529",border:"#dee2e6"},spacing:{unit:4,scale:[0,4,8,16,24,32,48,64]},typography:{fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',scale:[12,14,16,18,20,24,30,36,48,60]}},k={colors:{primary:"#3b82f6",secondary:"#64748b",background:"#0f172a",surface:"#1e293b",text:"#f8fafc",border:"#334155"}};class j{validateDomain(e){if(!e||"string"!=typeof e)return!1;const t=e.replace(/^https?:\/\//i,"").replace(/\/.*$/,"").toLowerCase();return!("widgetic.com"!==t&&!t.endsWith(".widgetic.com"))||(!(v.isProduction||!this.ALLOWED_DEV_ORIGINS.includes(t))||this.allowedOrigins.some(e=>{if("*"===e)return!0;const s=e.replace(/^https?:\/\//i,"").replace(/\/.*$/,"").toLowerCase();if(s.startsWith("*.")){const e=s.slice(2);return t===e||t.endsWith("."+e)}return t===s}))}constructor(e=[]){this.allowedOrigins=e,this.DEVELOPMENT_CSP={defaultSrc:["'self'","http://localhost:*"],scriptSrc:["'self'","'unsafe-eval'","http://localhost:*",M.CDN_URL,"https://*.widgetic.com"],styleSrc:["'self'","'unsafe-inline'","http://localhost:*"],imgSrc:["'self'","data:","https:","http://localhost:*"],connectSrc:["'self'","http://localhost:*","ws://localhost:*",M.API_URL,"https://*.widgetic.com"],frameAncestors:["'self'","http://localhost:*"]},this.PRODUCTION_CSP={defaultSrc:["'self'"],scriptSrc:["'self'",M.CDN_URL,"https://*.widgetic.com"],styleSrc:["'self'","'unsafe-inline'"],imgSrc:["'self'","data:","https:"],connectSrc:["'self'",M.API_URL,"https://*.widgetic.com"],frameAncestors:["'self'"]},this.ALLOWED_DEV_ORIGINS=["localhost","127.0.0.1",M.CLIENT_URL,"null"],this.setupCSP()}setupCSP(){}buildCSPString(){const e=v.isProduction?this.PRODUCTION_CSP:this.DEVELOPMENT_CSP,t=[];for(const[s,r]of Object.entries(e))if(r&&r.length){const e=s.replace(/([A-Z])/g,"-$1").toLowerCase();t.push(`${e} ${r.join(" ")}`)}return t.join("; ")}validateOrigin(e){if(!e||"string"!=typeof e)return!1;if("null"===e)return!v.isProduction;let t;try{t=new URL(e.startsWith("http")?e:`https://${e}`).hostname.toLowerCase()}catch{t=e.replace(/^https?:\/\//i,"").replace(/\/.*$/,"").toLowerCase()}return!(v.isProduction||!this.ALLOWED_DEV_ORIGINS.includes(t))||(!("widgetic.com"!==t&&!t.endsWith(".widgetic.com"))||this.allowedOrigins.some(s=>{if("*"===s)return!0;const r=s.replace(/^https?:\/\//i,"").replace(/\/.*$/,"").toLowerCase();if(r.startsWith("*.")){const e=r.slice(2);return t===e||t.endsWith("."+e)}return t===r||e.toLowerCase()===s.toLowerCase()}))}validateRequest(e){const t=e.headers.get("origin");if(!t&&!v.isProduction)return!0;if(!t)return!1;if(!this.validateOrigin(t))return console.warn(`Invalid request origin: ${t}`),!1;if(!v.isProduction)return!0;const s=e.headers.get("x-csrf-token");return!(s&&!this.validateCSRFToken(s))||(console.warn("Invalid CSRF token"),!1)}validateCSRFToken(e){return!0}validateMessage(e){if(!e.data)return console.warn("Invalid message: missing data"),!1;const{type:t,data:s}=e.data;return t&&"string"==typeof t?!s||"object"==typeof s||(console.warn("Invalid message: data must be an object"),!1):(console.warn("Invalid message: missing or invalid type"),!1)}}function x(e){return"string"!=typeof e?"":e.replace(/[<>]/g,"").replace(/javascript:/gi,"").replace(/on\w+=/gi,"").trim()}const V="0.1.14",F="@widgetic/ui-sdk";var W={SDK_VERSION:V,SDK_NAME:F,WidgeticUI:$,mountModule:A,HighLevelUIAPI:R};e.ComponentError=n,e.ConfigManager=S,e.Core=class{constructor(){}},e.DEFAULT_API_URL=w,e.DEFAULT_CONFIG=M,e.DEFAULT_MODULE_BASE_URL=E,e.EventSystem=class{constructor(e,t){this.handlers=new Map,this.hostHandlers=new Map,this.messageListener=null,this.bridge=e||("undefined"!=typeof window?window.parent:{}),this.targetOrigin=t||("undefined"!=typeof window&&window.location?.origin?window.location.origin:"*"),this.setupMessageListener()}setupMessageListener(){this.messageListener=e=>{this.handleMessage(e)},this.bridge instanceof MessagePort?this.bridge.onmessage=this.messageListener:"undefined"!=typeof window&&window.addEventListener("message",this.messageListener)}handleMessage(e){try{if(!this.validateMessage(e))return;const{type:t,data:s}=e.data,r=this.hostHandlers.get(t);r&&r.forEach(e=>{try{e(s)}catch(e){console.error(`Error in host event handler for ${t}:`,e),this.emitError("message_handler_error",e)}})}catch(e){console.error("Error processing message:",e),this.emitError("message_processing_error",e)}}validateMessage(e){if(this.bridge instanceof MessagePort)return!0;if(!e.data||"object"!=typeof e.data)return!1;const{type:t,source:s}=e.data;return!(!t||!s)&&"partner-platform"===s}on(e,t){return this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e)?.add(t),()=>this.off(e,t)}off(e,t){const s=this.handlers.get(e);s&&(s.delete(t),0===s.size&&this.handlers.delete(e))}emit(e,t){try{const s={...t,timestamp:Date.now()},r={type:e,...s},n=this.handlers.get(e);n?.forEach(t=>{try{t(r)}catch(t){console.error(`Error in event handler for ${e}:`,t),this.emitError("event_handler_error",t)}}),this.bridge&&this.sendToHost(r)}catch(e){console.error("Error emitting event:",e),this.emitError("event_emission_error",e)}}sendToHost(e){const t={...e,source:"widgetic-ui-sdk"};this.bridge instanceof MessagePort?this.bridge.postMessage(t):"undefined"!=typeof window&&this.bridge&&"postMessage"in this.bridge&&this.bridge.postMessage(t,this.targetOrigin)}emitError(e,t){const s={type:"messaging:error",error:{message:t.message,code:e,name:t.name,stack:t.stack,details:t},timestamp:Date.now()},r=this.handlers.get("error");r?.forEach(e=>{try{e(s)}catch(e){console.error("Error in error handler:",e)}})}destroy(){this.bridge instanceof MessagePort?this.bridge.close():"undefined"!=typeof window&&this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=null),this.handlers.clear(),this.hostHandlers.clear()}},e.HighLevelUIAPI=R,e.HostCommunication=class{constructor(e,t,s){this.origin=e,this.events=t,this.boundHandleMessage=e=>{this.handleMessage(e)},this.security=s,this.setupMessageHandling()}setupMessageHandling(){"undefined"!=typeof window&&window.addEventListener("message",this.boundHandleMessage)}handleMessage(e){try{if(!this.validateMessage(e))return;const{type:t,data:s}=e.data;this.events.emit(t,s)}catch(e){console.error("Error handling message:",e),this.events.emit("error",{componentId:"host-communication",error:e instanceof Error?e:new Error("Message handling failed")})}}validateMessage(e){return e.origin===this.origin&&!!this.security.validateMessage(e)}async createSecureChannel(){const e=new MessageChannel;window.parent.postMessage({type:"secure-channel-request"},this.origin,[e.port2]),this.channel=e.port1,this.channel.onmessage=this.boundHandleMessage}destroy(){"undefined"!=typeof window&&window.removeEventListener("message",this.boundHandleMessage),this.channel?.close()}},e.LifecycleManager=g,e.MessagingSystem=class{constructor(e){this.config=e,this.handlers=new Map,this.hostHandlers=new Map,this.messageListener=null;try{o.validateConfig(e,["origin"],"MessagingSystem.constructor"),this.bridge="undefined"!=typeof window?window.parent:{},this.security=e.security,this.setupMessageListener()}catch(e){throw t.handleError(e,"MessagingSystem.constructor")}}setupMessageListener(){this.messageListener=e=>{try{if(!this.validateMessage(e))return;const{type:t,data:s}=e.data,r=this.hostHandlers.get(t);r&&r.forEach(e=>{try{e(s)}catch(e){console.error(`Error in host event handler for ${t}:`,e),this.emitError("message_handler_error",e)}})}catch(e){console.error("Error processing message:",e),this.emitError("message_processing_error",e)}},this.bridge instanceof MessagePort?this.bridge.onmessage=this.messageListener:"undefined"!=typeof window&&window.addEventListener("message",this.messageListener)}validateMessage(e){if(this.bridge instanceof MessagePort)return!0;if(!e.data||"object"!=typeof e.data)return!1;const{type:t,source:s}=e.data;return!(!t||!s)&&"partner-platform"===s}on(e,t){return this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e)?.add(t),()=>this.off(e,t)}off(e,t){this.handlers.get(e)?.delete(t)}emit(e,t){try{const s={...t,timestamp:Date.now()},r={type:e,...s},n=this.handlers.get(e);n?.forEach(t=>{try{t(r)}catch(t){console.error(`Error in event handler for ${e}:`,t),this.emitError("event_handler_error",t)}}),this.bridge&&this.sendToHost(r)}catch(e){console.error("Error emitting event:",e),this.emitError("event_emission_error",e)}}sendToHost(e){const t={...e,source:"widgetic-ui-sdk"};this.bridge instanceof MessagePort?this.bridge.postMessage(t):"undefined"!=typeof window&&this.bridge&&"postMessage"in this.bridge&&this.bridge.postMessage(t,this.config.origin||window.location.origin)}emitError(e,t){const s={type:"messaging:error",error:{message:t.message,code:e,name:t.name,stack:t.stack,details:t},timestamp:Date.now()},r=this.handlers.get("error");r?.forEach(e=>{try{e(s)}catch(e){console.error("Error in error handler:",e)}})}destroy(){this.bridge instanceof MessagePort?this.bridge.close():"undefined"!=typeof window&&this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=null),this.handlers.clear(),this.hostHandlers.clear()}},e.ModuleLoadError=I,e.ModuleLoader=N,e.ModuleMountError=f,e.SDK_NAME=F,e.SDK_VERSION=V,e.SecurityError=r,e.StateManager=class{constructor(e={}){this.state=new Map,this.listeners=new Map,this.snapshots=new Map,this.maxSnapshots=e.maxSnapshots||10}setState(e,t,s,r={}){try{this.state.has(e)||this.state.set(e,new Map);const n=this.state.get(e),o=n.get(t);n.set(t,s),r.snapshot&&this.createSnapshot(e),r.silent||this.notifyStateChange(e,t,s,o)}catch(e){throw console.error("Error setting state:",e),e}}getState(e,t){return this.state.get(e)?.get(t)}getComponentState(e){return this.state.get(e)}subscribe(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){this.listeners.get(e)?.delete(t)}createSnapshot(e){this.snapshots.has(e)||this.snapshots.set(e,[]);const t={timestamp:Date.now(),state:new Map(this.state.get(e))},s=this.snapshots.get(e);s.push(t),s.length>this.maxSnapshots&&s.shift()}restoreSnapshot(e,t=-1){try{const s=this.snapshots.get(e);if(!s?.length)return!1;const r=s[t<0?s.length-1:t];return!!r&&(this.state.set(e,new Map(r.state)),this.notifyStateChange(e,"*",this.getComponentState(e)),!0)}catch(e){return console.error("Error restoring snapshot:",e),!1}}notifyStateChange(e,t,s,r){const n=this.listeners.get(e);n&&n.forEach(n=>{try{n({componentId:e,key:t,newValue:s,oldValue:r})}catch(e){console.error("Error in state change listener:",e)}})}cleanup(e){e?(this.state.delete(e),this.listeners.delete(e),this.snapshots.delete(e)):(this.state.clear(),this.listeners.clear(),this.snapshots.clear())}},e.ThemeManager=class{constructor(e,t){this.events=e,this.activePreset="default",this.currentTheme=this.createDefaultTheme(),t&&this.updateTheme(t),this.setupSystemThemeListener()}getCurrentTheme(){return{...this.currentTheme}}updateTheme(e){try{const t=this.mergeThemes(this.currentTheme,e);this.validateTheme(t),this.currentTheme=t,this.applyTheme(),this.notifyThemeUpdate()}catch(e){throw console.error("Error updating theme:",e),new Error(`Theme update failed: ${e instanceof Error?e.message:"Unknown error"}`,{cause:e})}}setMode(e){this.updateTheme({mode:e}),this.applyColorScheme(e)}setupSystemThemeListener(){window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",e=>{"system"===this.currentTheme.mode&&this.applyColorScheme(e.matches?"dark":"light")})}createDefaultTheme(){return{...P}}mergeThemes(e,t){return{mode:t.mode??e.mode,colors:t.colors?{...e.colors,...t.colors}:e.colors,spacing:t.spacing?{...e.spacing,...t.spacing}:e.spacing,typography:t.typography?{...e.typography,...t.typography}:e.typography}}validateTheme(e){if(Object.entries(e.colors).forEach(([e,t])=>{if(!this.isValidColor(t))throw new Error(`Invalid color value for ${e}: ${t}`)}),e.spacing.unit<=0)throw new Error("Spacing unit must be positive");if(!e.typography.fontFamily)throw new Error("Font family is required")}isValidColor(e){return/^(#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{8}|rgb\(.*\)|rgba\(.*\)|hsl\(.*\)|hsla\(.*\))$/.test(e)}applyColorScheme(e){const t="dark"===e?k:P;this.updateTheme({colors:t.colors})}applyTheme(){document.documentElement.style.setProperty("--theme-mode",this.currentTheme.mode),Object.entries(this.currentTheme.colors).forEach(([e,t])=>{document.documentElement.style.setProperty(`--color-${e}`,t)}),document.documentElement.style.setProperty("--spacing-unit",`${this.currentTheme.spacing.unit}px`),this.currentTheme.spacing.scale.forEach((e,t)=>{document.documentElement.style.setProperty(`--spacing-${t}`,`${e}px`)}),document.documentElement.style.setProperty("--font-family",this.currentTheme.typography.fontFamily),this.currentTheme.typography.scale.forEach((e,t)=>{document.documentElement.style.setProperty(`--font-size-${t}`,`${e}px`)})}notifyThemeUpdate(){this.events.emit("theme:update",{theme:this.currentTheme})}},e.UILoader=$,e.ValidationError=s,e.WidgeticComponent=class{constructor(e,t){this.container=e,this.config=t,this.shadow=this.initializeShadowDOM(),this.state={status:"initializing",error:null},this.events=t.events,this.id=t.id,t.theme&&this.applyTheme(t.theme),this.events&&this.events.on("theme:update",e=>{const t=e?.theme||e;t&&"object"==typeof t&&this.applyTheme(t)})}initializeShadowDOM(){try{return this.container.attachShadow({mode:"closed"})}catch(e){throw console.error("Error initializing shadow DOM:",e),new Error("Failed to initialize component shadow DOM",{cause:e})}}setState(e){this.state={...this.state,...e},this.events.emit("state:update",{componentId:this.id,state:this.state})}handleError(e){console.error(`Error in ${this.constructor.name}:`,e),this.setState({status:"error",error:e}),this.events.emit("error",{componentId:this.id,error:e})}applyTheme(e){this.container.style.setProperty("--theme-mode",e.mode);const t=`\n :host {\n --theme-mode: ${e.mode};\n ${Object.entries(e.colors).map(([e,t])=>`--color-${e}: ${t};`).join("\n")}\n --spacing-unit: ${e.spacing.unit}px;\n ${e.spacing.scale.map((e,t)=>`--spacing-${t}: ${e}px;`).join("\n")}\n --font-family: ${e.typography.fontFamily};\n ${e.typography.scale.map((e,t)=>`--font-size-${t}: ${e}px;`).join("\n")}\n }\n `;if("undefined"!=typeof CSSStyleSheet&&"replaceSync"in CSSStyleSheet.prototype&&this.shadow&&"adoptedStyleSheets"in this.shadow)try{return this.themeStyleSheet||(this.themeStyleSheet=new CSSStyleSheet,this.shadow.adoptedStyleSheets=[...this.shadow.adoptedStyleSheets,this.themeStyleSheet]),void this.themeStyleSheet.replaceSync(t)}catch{}let s=this.shadow.querySelector("style[data-widgetic-theme]");s||(s=document.createElement("style"),s.setAttribute("data-widgetic-theme","true"),this.shadow.appendChild(s)),s.textContent=t}},e.WidgeticUI=$,e.config=v,e.createSecureContext=function(e=[]){const t=new j(e);return{validateMessage:e=>t.validateMessage(e),validateOrigin:e=>t.validateOrigin(e),sanitizeInput:x}},e.createSecureRequest=function(e,t={}){const s=new Headers(t.headers);return s.set("X-Requested-With","XMLHttpRequest"),new Request(e,{...t,headers:s,credentials:"same-origin"})},e.default=W,e.mountModule=A,e.sanitizeInput=x,e.validateOrigin=function(e,t=[]){return new j(t).validateOrigin(e)},e.validateResponse=function(e){if(!e.ok)return!1;const t=e.headers.get("content-type");return t&&!t.includes("application/json")&&console.warn("Unexpected content type:",t),!0},Object.defineProperty(e,"__esModule",{value:!0})});
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).WidgeticUISDK={})}(this,function(e){"use strict";class t{static createError(e,t){const s=new Error(e);return s.code=t,s}static handleError(e,t){return e instanceof Error?e.code?e:this.createError(e.message,"UNKNOWN_ERROR"):"string"==typeof e?this.createError(e,"STRING_ERROR"):this.createError(`Unknown error in ${t}`,"UNKNOWN_ERROR")}static toSDKError(e){return{message:e.message,code:e.code||"UNKNOWN_ERROR",name:e.name,stack:e.stack,details:e}}}class s extends Error{constructor(e,t){super(e),this.field=t,this.name="ValidationError"}}class r extends Error{constructor(e,t){super(e),this.code=t,this.name="SecurityError"}}class n extends Error{constructor(e,t){super(e),this.componentId=t,this.name="ComponentError"}}class o{static validateId(e,s){if(!e||"string"!=typeof e||""===e.trim())throw t.createError(`Invalid ID provided in ${s}`,"INVALID_ID")}static validateContainer(e,s){if(o.requireBrowser(s),!e)throw t.createError(`Container is required in ${s}`,"MISSING_CONTAINER");if("string"==typeof e){const s=document.querySelector(e);if(!s)throw t.createError(`Container not found: ${e}`,"CONTAINER_NOT_FOUND");return s}if(!(e instanceof HTMLElement))throw t.createError(`Invalid container type in ${s}`,"INVALID_CONTAINER");return e}static requireBrowser(e){if("undefined"==typeof document)throw t.createError(`Widgetic modules can only be used in a browser (${e}). With server-side rendering, start them from an effect or an event handler, which only run on the client.`,"NOT_IN_BROWSER")}static rejectApiKey(e){const s=e??{},r=s.partner;if(void 0!==s.apiKey||void 0!==r?.apiKey)throw t.createError("The apiKey option is not accepted: an API key must never be in a browser. Mint an editor session on your server (POST /v1/managed-users/{id}/editor-sessions) and return its token from the getToken option.","API_KEY_NOT_ALLOWED")}static validateConfig(e,s,r){if(!e)throw t.createError(`Configuration is required in ${r}`,"MISSING_CONFIG");for(const n of s)if(!(n in e))throw t.createError(`Missing required field: ${String(n)} in ${r}`,"MISSING_REQUIRED_FIELD")}static validateEventType(e,s){if(!s.includes(e))throw t.createError(`Invalid event type: ${e}`,"INVALID_EVENT_TYPE")}static validateFileUpload(e,s,r){if(e.size>s)throw t.createError(`File size exceeds maximum allowed size of ${s} bytes`,"FILE_TOO_LARGE");if(!r.includes("*/*")&&!r.includes(e.type))throw t.createError(`File type ${e.type} is not allowed`,"INVALID_FILE_TYPE")}}const i=["mode","preset","colors","radius","font"],a=["light","dark","system"],c="(prefers-color-scheme: dark)";function h(e){return"string"==typeof e&&a.includes(e)}function d(e){const t="string"==typeof e?e:e?.mode;return h(t)?t:void 0}function l(e){if(!e||"object"!=typeof e||Array.isArray(e))return;const t=Object.fromEntries(Object.entries(e).filter(([e,t])=>"mode"!==e&&void 0!==t));return Object.keys(t).length>0?t:void 0}function u(e){return"system"===e?"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia(c).matches?"dark":"light":"dark"===e?"dark":"light"}function m(e,t){const s=d(e),r=s?u(s):t.mode,n=l(e)??t.settings;return n?{...n,mode:r}:r}class f extends Error{constructor(e,t){super(`The "${e}" module failed to start: ${t instanceof Error?t.message:String(t)}`),this.code="MOUNT_FAILED",this.name="ModuleMountError",this.moduleName=e,this.cause=t,Object.setPrototypeOf(this,f.prototype)}}class g{constructor(e,t){this.events=e,this.options=t,this.active=new Map}async mount(e,s){o.rejectApiKey(s);const r=o.validateContainer(s.container,"LifecycleManager.mount"),{version:n,theme:i,placeholder:a,loadingLabel:c,on:h,callbacks:d,signal:u,...g}=s,y=function(e){const t={...e};return delete t.container,t}(g),w=this.generateInstanceId(),E=!1===a?null:this.showPlaceholder(r,e,c);let M=null;const S=[];try{p(u,e);const t=await this.options.loader.load(e,{version:n});p(u,e);const{getToken:s,apiUrl:o,locale:a}=this.options.moduleDefaults;try{M=new t.Module(r,{apiUrl:o,locale:a,...s?{getToken:async e=>s(e)}:{},...y,theme:m(i,{mode:this.options.getThemeMode(),settings:this.options.getThemeSettings?.()})}),S.push(...this.connectEvents(w,M,{on:h,callbacks:d})),await M.mount()}catch(t){throw new f(e,t)}p(u,e);const c=this.createMountedModule(w,e,t.version,r,M);return this.active.set(w,{mounted:c,stopListening:S,hasOwnSettings:void 0!==l(i)}),c}catch(e){for(const e of S)e();throw await this.unmountQuietly(M),t.handleError(e,"LifecycleManager.mount")}finally{E?.remove()}}async unmount(e){const s=this.active.get(e);if(!s)throw t.createError(`No instance found for ID: ${e}`,"INSTANCE_NOT_FOUND");this.active.delete(e);try{await(s.mounted.module.unmount?.())}finally{for(const e of s.stopListening)e()}}get(e){return this.active.get(e)?.mounted}setThemeMode(e){for(const{mounted:t}of this.active.values())this.tellModule(t,e)}setDefaultTheme(e,t,s=!0){for(const{mounted:r,hasOwnSettings:n}of this.active.values())n?s&&this.tellModule(r,t):this.tellModule(r,{...e,mode:t})}tellModule(e,t){try{e.module.setTheme?.(t)}catch(s){console.error(`[widgetic-ui] The "${e.type}" module could not apply the theme ${JSON.stringify(t)}:`,s)}}async cleanup(){const e=await Promise.allSettled([...this.active.keys()].map(e=>this.unmount(e)));for(const t of e)"rejected"===t.status&&console.error("[widgetic-ui] A module failed to unmount during cleanup:",t.reason)}connectEvents(e,t,{on:s,callbacks:r}){const n=[];if("function"!=typeof t.on)return n;const o=(e,s)=>{n.push(t.on(e,s))};for(const[e,t]of Object.entries(s??{}))"function"==typeof t&&o(e,t);return o("ready",()=>{r?.onReady?.(),this.events.emit("ready",{componentId:e})}),o("error",t=>{const s=function(e){if(e instanceof Error)return e;const{message:t,code:s,fatal:r}=e??{},n=new Error("string"==typeof t?t:"The module reported an error");"string"==typeof s&&(n.code=s);"boolean"==typeof r&&(n.fatal=r);return n}(t);r?.onError?.(s),this.events.emit("error",{componentId:e,error:s})}),n}createMountedModule(e,t,s,r,n){return{id:e,type:t,version:s,container:r,module:n,on:(e,s)=>"function"!=typeof n.on?(console.warn(`[widgetic-ui] The "${t}" module does not report events.`),()=>{}):n.on(e,s),off:(e,t)=>n.off?.(e,t),setTheme:s=>{if("function"!=typeof n.setTheme)return void console.warn(`[widgetic-ui] The "${t}" module cannot change its look.`);n.setTheme(s);const r=this.active.get(e);r&&"object"==typeof s&&(r.hasOwnSettings=!0)},setLanguage:e=>{"function"==typeof n.setLanguage?n.setLanguage(e):console.warn(`[widgetic-ui] The "${t}" module has no words to translate yet.`)},unmount:()=>this.unmount(e)}}async unmountQuietly(e){try{await(e?.unmount?.())}catch(e){console.warn("[widgetic-ui] A module that failed to start also failed to clean up:",e)}}showPlaceholder(e,t,s){const r=document.createElement("div");r.setAttribute("data-widgetic-ui-loading",t),r.setAttribute("role","status"),r.setAttribute("aria-label","string"==typeof s&&""!==s.trim()?s:"Loading"),Object.assign(r.style,{display:"flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box",width:"100%",minHeight:this.getComponentMinHeight(t)});const n=document.createElement("div");return Object.assign(n.style,{width:"28px",height:"28px",border:"3px solid rgba(128, 128, 128, 0.25)",borderTopColor:"#3b82f6",borderRadius:"50%"}),"function"==typeof n.animate&&n.animate([{transform:"rotate(0deg)"},{transform:"rotate(360deg)"}],{duration:1e3,iterations:1/0}),r.appendChild(n),e.appendChild(r),r}getComponentMinHeight(e){switch(e){case"widget-creator":case"composition-editor":case"workflows":return"480px";case"embed-editor":case"file-browser":return"380px";default:return"280px"}}generateInstanceId(){return`widgetic-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}}function p(e,s){if(e?.aborted){const e=t.createError(`Mounting the "${s}" module was cancelled.`,"MOUNT_ABORTED");throw e.name="AbortError",e}}class y{constructor(){this.handlers=new Map}on(e,t){const s=this.handlers.get(e)??new Set;return s.add(t),this.handlers.set(e,s),()=>this.off(e,t)}off(e,t){const s=this.handlers.get(e);s&&(s.delete(t),0===s.size&&this.handlers.delete(e))}emit(e,t){const s=this.handlers.get(e);if(!s)return;const r={type:e,...t,timestamp:Date.now()};for(const t of[...s])try{t(r)}catch(t){console.error(`[widgetic-ui] A handler for "${e}" threw:`,t)}}destroy(){this.handlers.clear()}}const w="https://api.widgetic.com",E="https://cdn.widgetic.com/modules",M={NODE_ENV:"production",API_URL:w,API_VERSION:"/v1",CLIENT_URL:"https://widgetic.com",PRODUCTION_URL:w,CDN_URL:"https://cdn.widgetic.com",EMBED_SDK_URL:"/sdks/browser/embed-sdk.js"};class S{constructor(){this.config={...M}}static getInstance(){return S.instance||(S.instance=new S),S.instance}initialize(e){this.config={...M,...e}}getApiUrl(){return(this.isProduction?this.config.PRODUCTION_URL:this.config.API_URL)+this.config.API_VERSION}getCdnUrl(){return this.config.CDN_URL}get isProduction(){return"production"===this.config.NODE_ENV}validateConfig(){if(!this.config.API_URL)throw new Error("API_URL is required");if(!this.config.API_VERSION)throw new Error("API_VERSION is required");if(!this.config.CLIENT_URL)throw new Error("CLIENT_URL is required")}}const v=S.getInstance();class I extends Error{constructor(e,t,s){super(t),this.name="ModuleLoadError",this.code=e,this.moduleName=s.moduleName,this.url=s.url,this.cause=s.cause,Object.setPrototypeOf(this,I.prototype)}}const T=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,L=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?$/,b=[300,900],_=e=>import(e);class N{constructor(e={}){this.loads=new Map,this.baseUrl=function(e){const t="undefined"!=typeof document?document.baseURI:"http://localhost/";let s;try{s=new URL(e,t)}catch(t){throw new I("INVALID_MODULE_BASE_URL",`moduleBaseUrl is not an address: ${e}`,{moduleName:"",cause:t})}if("https:"!==s.protocol&&"http:"!==s.protocol)throw new I("INVALID_MODULE_BASE_URL",`moduleBaseUrl must be an http(s) address, got ${s.protocol}`,{moduleName:""});s.pathname.endsWith("/")||(s.pathname+="/");return s}(e.moduleBaseUrl??E),this.fetchImpl=e.fetchImpl??((e,t)=>fetch(e,t)),this.importImpl=e.importImpl??_,this.retryDelaysMs=e.retryDelaysMs??b}async load(e,t={}){!function(e){if("string"!=typeof e||e.length>64||!T.test(e))throw new I("INVALID_MODULE_NAME",`"${String(e)}" is not a module name. Use lowercase letters, digits and dashes, like "file-browser".`,{moduleName:String(e)})}(e);const s=t.version;void 0!==s&&function(e,t){if("string"!=typeof t||!L.test(t))throw new I("INVALID_VERSION",`"${String(t)}" is not a version. Use an exact version like "1.2.0".`,{moduleName:e})}(e,s);const r=`${e}@${s??"latest"}`,n=this.loads.get(r);if(n)return n;const o=this.loadUncached(e,s).catch(e=>{throw this.loads.delete(r),e});return this.loads.set(r,o),o}async loadUncached(e,t){let s,r;if(void 0!==t)s=t,r=new URL(`${e}/${t}/index.js`,this.baseUrl);else{const t=await this.fetchManifest(e);s=t.version,r=this.resolveEntryUrl(e,t)}return{Module:await this.importModuleFile(e,r),name:e,version:s,url:r.href}}async fetchManifest(e){const t=new URL(`${e}/manifest.json`,this.baseUrl);try{return await this.withRetries(async()=>{const s=await this.fetchImpl(t.href,{credentials:"omit"});if(404===s.status||403===s.status)throw new I("MODULE_NOT_FOUND",`There is no "${e}" module at ${t.href} (HTTP ${s.status}).`,{moduleName:e,url:t.href});if(!s.ok)throw new Error(`HTTP ${s.status} for ${t.href}`);let r;try{r=await s.json()}catch(s){throw new I("MANIFEST_INVALID",`The manifest at ${t.href} is not JSON.`,{moduleName:e,url:t.href,cause:s})}return this.validateManifest(e,t,r)})}catch(s){if(s instanceof I)throw s;throw new I("MANIFEST_UNAVAILABLE",`Could not load the manifest of "${e}" from ${t.href}: ${O(s)}`,{moduleName:e,url:t.href,cause:s})}}validateManifest(e,t,s){const r=s=>{throw new I("MANIFEST_INVALID",`The manifest at ${t.href} ${s}.`,{moduleName:e,url:t.href})};if("object"!=typeof s||null===s)return r("is not a JSON object");const{name:n,version:o,entry:i}=s;return n!==e?r(`is for "${String(n)}", not "${e}"`):"string"==typeof o&&L.test(o)?"string"!=typeof i||0===i.length?r('has no "entry"'):{name:n,version:o,entry:i}:r(`has no valid "version" (found ${JSON.stringify(o)})`)}resolveEntryUrl(e,t){const s=new URL(`${e}/manifest.json`,this.baseUrl),r=new URL(`${e}/`,this.baseUrl);let n;try{n=new URL(t.entry,s)}catch(r){throw new I("MANIFEST_INVALID",`The manifest of "${e}" has an "entry" that is not an address: ${t.entry}`,{moduleName:e,url:s.href,cause:r})}const o=n.origin===r.origin&&n.pathname.startsWith(r.pathname),i=/\.m?js$/.test(n.pathname);if(!o||!i)throw new I("MANIFEST_INVALID",`The manifest of "${e}" points at ${n.href}, which is not a script inside ${r.href}.`,{moduleName:e,url:s.href});return n}async importModuleFile(e,t){let s;try{s=await this.withRetries(async e=>{const s=0===e?t.href:function(e,t){const s=new URL(e.href);return s.searchParams.set("retry",String(t)),s.href}(t,e);return this.importImpl(s)})}catch(s){throw new I("MODULE_LOAD_FAILED",`Could not load the "${e}" module from ${t.href}: ${O(s)}`,{moduleName:e,url:t.href,cause:s})}const r=s?.default;if("function"!=typeof r)throw new I("MODULE_INVALID",`The file at ${t.href} does not export a module class as its default export.`,{moduleName:e,url:t.href});return r}async withRetries(e){let t;for(let s=0;s<=this.retryDelaysMs.length;s++)try{return await e(s)}catch(e){if(e instanceof I)throw e;t=e;const r=this.retryDelaysMs[s];void 0!==r&&await new Promise(e=>setTimeout(e,r))}throw t}}function O(e){return e instanceof Error?e.message:String(e)}const U=new Map;class ${constructor(e={}){this.stopWatchingSystemTheme=null,function(e){o.rejectApiKey(e);const s=e?.getToken;if(void 0!==s&&"function"!=typeof s)throw t.createError("WidgeticUI: getToken must be a function that resolves an editor session token (or { token, expiresAt }) minted by your server.","INVALID_GET_TOKEN")}(e),this.events=new y,this.loader=e.moduleLoader??function(e){let t=U.get(e);return t||(t=new N({moduleBaseUrl:e}),U.set(e,t)),t}(e.moduleBaseUrl??E),this.themeMode=d(e.theme)??"light",this.themeSettings=l(e.theme),this.lifecycleManager=new g(this.events,{loader:this.loader,moduleDefaults:{apiUrl:e.apiUrl??w,getToken:e.getToken,locale:e.locale},getThemeMode:()=>u(this.themeMode),getThemeSettings:()=>this.themeSettings}),this.followSystemThemeWhenAsked()}async mount(e,t){try{return await this.lifecycleManager.mount(e,t)}catch(e){if("MOUNT_ABORTED"===e?.code)throw e;throw console.error("Error mounting component:",e),t.callbacks?.onError?.(e),e}}async mountComponent(e,t){return(await this.mount(e,t)).id}async unmountComponent(e){try{await this.lifecycleManager.unmount(e)}catch(e){throw console.error("Error unmounting component:",e),e}}getComponent(e){return this.lifecycleManager.get(e)}async preload(e,t={}){o.requireBrowser(`preloading "${e}"`),await this.loader.load(e,t)}updateTheme(e){if(!function(e){if("string"==typeof e)return h(e);if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.entries(e).filter(([,e])=>void 0!==e);if(0===t.length)return!1;if(!t.every(([e])=>i.includes(e)))return!1;const s=e.mode;return void 0===s||h(s)}(e))throw t.createError(`Unknown theme: ${JSON.stringify(e)}. Use 'light', 'dark', 'system', or an object with some of mode, preset, colors, radius, font.`,"INVALID_THEME");const s=d(e),r=l(e);s&&(this.themeMode=s),r&&(this.themeSettings=r),this.followSystemThemeWhenAsked();const n=u(this.themeMode);r?this.lifecycleManager.setDefaultTheme(r,n,void 0!==s):this.lifecycleManager.setThemeMode(n),this.events.emit("theme:update",{theme:r?{...r,mode:this.themeMode}:{mode:this.themeMode}})}getTheme(){return{mode:this.themeMode,...this.themeSettings}}on(e,t){return this.events.on(e,t)}off(e,t){this.events.off(e,t)}emit(e,t){this.events.emit(e,t)}async destroy(){this.stopWatchingSystemTheme?.(),this.stopWatchingSystemTheme=null,await this.lifecycleManager.cleanup(),this.events.destroy()}followSystemThemeWhenAsked(){this.stopWatchingSystemTheme?.(),this.stopWatchingSystemTheme=null,"system"===this.themeMode&&(this.stopWatchingSystemTheme=function(e){if("undefined"==typeof window||"function"!=typeof window.matchMedia)return()=>{};const t=window.matchMedia(c),s=t=>e(t.matches?"dark":"light");return t.addEventListener("change",s),()=>t.removeEventListener("change",s)}(e=>this.lifecycleManager.setThemeMode(e)))}}async function A(e,t){o.rejectApiKey(t);const{getToken:s,apiUrl:r,moduleBaseUrl:n,locale:i,moduleLoader:a,...c}=t,h=new $({getToken:s,apiUrl:r,moduleBaseUrl:n,locale:i,moduleLoader:a,theme:c.theme});let d;try{d=await h.mount(e,c)}catch(e){throw await h.destroy(),e}return{...d,unmount:async()=>{try{await d.unmount()}finally{await h.destroy()}}}}let D=null;function C(){if(!D)throw t.createError("Call HighLevelUIAPI.initialize({ getToken }) before mounting a component.","NOT_INITIALIZED");return D}const R={WidgeticUI:$,initialize:async e=>{const t=new $(e),s=D;return D=t,await(s?.destroy()),t},mountComponent:async(e,t,s={})=>C().mountComponent(e,{...s,container:t}),unmountComponent:async e=>{await C().unmountComponent(e)}};const P={mode:"light",colors:{primary:"#007bff",secondary:"#6c757d",background:"#ffffff",surface:"#f8f9fa",text:"#212529",border:"#dee2e6"},spacing:{unit:4,scale:[0,4,8,16,24,32,48,64]},typography:{fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',scale:[12,14,16,18,20,24,30,36,48,60]}},k={colors:{primary:"#3b82f6",secondary:"#64748b",background:"#0f172a",surface:"#1e293b",text:"#f8fafc",border:"#334155"}};class j{validateDomain(e){if(!e||"string"!=typeof e)return!1;const t=e.replace(/^https?:\/\//i,"").replace(/\/.*$/,"").toLowerCase();return!("widgetic.com"!==t&&!t.endsWith(".widgetic.com"))||(!(v.isProduction||!this.ALLOWED_DEV_ORIGINS.includes(t))||this.allowedOrigins.some(e=>{if("*"===e)return!0;const s=e.replace(/^https?:\/\//i,"").replace(/\/.*$/,"").toLowerCase();if(s.startsWith("*.")){const e=s.slice(2);return t===e||t.endsWith("."+e)}return t===s}))}constructor(e=[]){this.allowedOrigins=e,this.DEVELOPMENT_CSP={defaultSrc:["'self'","http://localhost:*"],scriptSrc:["'self'","'unsafe-eval'","http://localhost:*",M.CDN_URL,"https://*.widgetic.com"],styleSrc:["'self'","'unsafe-inline'","http://localhost:*"],imgSrc:["'self'","data:","https:","http://localhost:*"],connectSrc:["'self'","http://localhost:*","ws://localhost:*",M.API_URL,"https://*.widgetic.com"],frameAncestors:["'self'","http://localhost:*"]},this.PRODUCTION_CSP={defaultSrc:["'self'"],scriptSrc:["'self'",M.CDN_URL,"https://*.widgetic.com"],styleSrc:["'self'","'unsafe-inline'"],imgSrc:["'self'","data:","https:"],connectSrc:["'self'",M.API_URL,"https://*.widgetic.com"],frameAncestors:["'self'"]},this.ALLOWED_DEV_ORIGINS=["localhost","127.0.0.1",M.CLIENT_URL,"null"],this.setupCSP()}setupCSP(){}buildCSPString(){const e=v.isProduction?this.PRODUCTION_CSP:this.DEVELOPMENT_CSP,t=[];for(const[s,r]of Object.entries(e))if(r&&r.length){const e=s.replace(/([A-Z])/g,"-$1").toLowerCase();t.push(`${e} ${r.join(" ")}`)}return t.join("; ")}validateOrigin(e){if(!e||"string"!=typeof e)return!1;if("null"===e)return!v.isProduction;let t;try{t=new URL(e.startsWith("http")?e:`https://${e}`).hostname.toLowerCase()}catch{t=e.replace(/^https?:\/\//i,"").replace(/\/.*$/,"").toLowerCase()}return!(v.isProduction||!this.ALLOWED_DEV_ORIGINS.includes(t))||(!("widgetic.com"!==t&&!t.endsWith(".widgetic.com"))||this.allowedOrigins.some(s=>{if("*"===s)return!0;const r=s.replace(/^https?:\/\//i,"").replace(/\/.*$/,"").toLowerCase();if(r.startsWith("*.")){const e=r.slice(2);return t===e||t.endsWith("."+e)}return t===r||e.toLowerCase()===s.toLowerCase()}))}validateRequest(e){const t=e.headers.get("origin");if(!t&&!v.isProduction)return!0;if(!t)return!1;if(!this.validateOrigin(t))return console.warn(`Invalid request origin: ${t}`),!1;if(!v.isProduction)return!0;const s=e.headers.get("x-csrf-token");return!(s&&!this.validateCSRFToken(s))||(console.warn("Invalid CSRF token"),!1)}validateCSRFToken(e){return!0}validateMessage(e){if(!e.data)return console.warn("Invalid message: missing data"),!1;const{type:t,data:s}=e.data;return t&&"string"==typeof t?!s||"object"==typeof s||(console.warn("Invalid message: data must be an object"),!1):(console.warn("Invalid message: missing or invalid type"),!1)}}function x(e){return"string"!=typeof e?"":e.replace(/[<>]/g,"").replace(/javascript:/gi,"").replace(/on\w+=/gi,"").trim()}const V="0.1.16",F="@widgetic/ui-sdk";var W={SDK_VERSION:V,SDK_NAME:F,WidgeticUI:$,mountModule:A,HighLevelUIAPI:R};e.ComponentError=n,e.ConfigManager=S,e.Core=class{constructor(){}},e.DEFAULT_API_URL=w,e.DEFAULT_CONFIG=M,e.DEFAULT_MODULE_BASE_URL=E,e.EventSystem=class{constructor(e,t){this.handlers=new Map,this.hostHandlers=new Map,this.messageListener=null,this.bridge=e||("undefined"!=typeof window?window.parent:{}),this.targetOrigin=t||("undefined"!=typeof window&&window.location?.origin?window.location.origin:"*"),this.setupMessageListener()}setupMessageListener(){this.messageListener=e=>{this.handleMessage(e)},this.bridge instanceof MessagePort?this.bridge.onmessage=this.messageListener:"undefined"!=typeof window&&window.addEventListener("message",this.messageListener)}handleMessage(e){try{if(!this.validateMessage(e))return;const{type:t,data:s}=e.data,r=this.hostHandlers.get(t);r&&r.forEach(e=>{try{e(s)}catch(e){console.error(`Error in host event handler for ${t}:`,e),this.emitError("message_handler_error",e)}})}catch(e){console.error("Error processing message:",e),this.emitError("message_processing_error",e)}}validateMessage(e){if(this.bridge instanceof MessagePort)return!0;if(!e.data||"object"!=typeof e.data)return!1;const{type:t,source:s}=e.data;return!(!t||!s)&&"partner-platform"===s}on(e,t){return this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e)?.add(t),()=>this.off(e,t)}off(e,t){const s=this.handlers.get(e);s&&(s.delete(t),0===s.size&&this.handlers.delete(e))}emit(e,t){try{const s={...t,timestamp:Date.now()},r={type:e,...s},n=this.handlers.get(e);n?.forEach(t=>{try{t(r)}catch(t){console.error(`Error in event handler for ${e}:`,t),this.emitError("event_handler_error",t)}}),this.bridge&&this.sendToHost(r)}catch(e){console.error("Error emitting event:",e),this.emitError("event_emission_error",e)}}sendToHost(e){const t={...e,source:"widgetic-ui-sdk"};this.bridge instanceof MessagePort?this.bridge.postMessage(t):"undefined"!=typeof window&&this.bridge&&"postMessage"in this.bridge&&this.bridge.postMessage(t,this.targetOrigin)}emitError(e,t){const s={type:"messaging:error",error:{message:t.message,code:e,name:t.name,stack:t.stack,details:t},timestamp:Date.now()},r=this.handlers.get("error");r?.forEach(e=>{try{e(s)}catch(e){console.error("Error in error handler:",e)}})}destroy(){this.bridge instanceof MessagePort?this.bridge.close():"undefined"!=typeof window&&this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=null),this.handlers.clear(),this.hostHandlers.clear()}},e.HighLevelUIAPI=R,e.HostCommunication=class{constructor(e,t,s){this.origin=e,this.events=t,this.boundHandleMessage=e=>{this.handleMessage(e)},this.security=s,this.setupMessageHandling()}setupMessageHandling(){"undefined"!=typeof window&&window.addEventListener("message",this.boundHandleMessage)}handleMessage(e){try{if(!this.validateMessage(e))return;const{type:t,data:s}=e.data;this.events.emit(t,s)}catch(e){console.error("Error handling message:",e),this.events.emit("error",{componentId:"host-communication",error:e instanceof Error?e:new Error("Message handling failed")})}}validateMessage(e){return e.origin===this.origin&&!!this.security.validateMessage(e)}async createSecureChannel(){const e=new MessageChannel;window.parent.postMessage({type:"secure-channel-request"},this.origin,[e.port2]),this.channel=e.port1,this.channel.onmessage=this.boundHandleMessage}destroy(){"undefined"!=typeof window&&window.removeEventListener("message",this.boundHandleMessage),this.channel?.close()}},e.LifecycleManager=g,e.MessagingSystem=class{constructor(e){this.config=e,this.handlers=new Map,this.hostHandlers=new Map,this.messageListener=null;try{o.validateConfig(e,["origin"],"MessagingSystem.constructor"),this.bridge="undefined"!=typeof window?window.parent:{},this.security=e.security,this.setupMessageListener()}catch(e){throw t.handleError(e,"MessagingSystem.constructor")}}setupMessageListener(){this.messageListener=e=>{try{if(!this.validateMessage(e))return;const{type:t,data:s}=e.data,r=this.hostHandlers.get(t);r&&r.forEach(e=>{try{e(s)}catch(e){console.error(`Error in host event handler for ${t}:`,e),this.emitError("message_handler_error",e)}})}catch(e){console.error("Error processing message:",e),this.emitError("message_processing_error",e)}},this.bridge instanceof MessagePort?this.bridge.onmessage=this.messageListener:"undefined"!=typeof window&&window.addEventListener("message",this.messageListener)}validateMessage(e){if(this.bridge instanceof MessagePort)return!0;if(!e.data||"object"!=typeof e.data)return!1;const{type:t,source:s}=e.data;return!(!t||!s)&&"partner-platform"===s}on(e,t){return this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e)?.add(t),()=>this.off(e,t)}off(e,t){this.handlers.get(e)?.delete(t)}emit(e,t){try{const s={...t,timestamp:Date.now()},r={type:e,...s},n=this.handlers.get(e);n?.forEach(t=>{try{t(r)}catch(t){console.error(`Error in event handler for ${e}:`,t),this.emitError("event_handler_error",t)}}),this.bridge&&this.sendToHost(r)}catch(e){console.error("Error emitting event:",e),this.emitError("event_emission_error",e)}}sendToHost(e){const t={...e,source:"widgetic-ui-sdk"};this.bridge instanceof MessagePort?this.bridge.postMessage(t):"undefined"!=typeof window&&this.bridge&&"postMessage"in this.bridge&&this.bridge.postMessage(t,this.config.origin||window.location.origin)}emitError(e,t){const s={type:"messaging:error",error:{message:t.message,code:e,name:t.name,stack:t.stack,details:t},timestamp:Date.now()},r=this.handlers.get("error");r?.forEach(e=>{try{e(s)}catch(e){console.error("Error in error handler:",e)}})}destroy(){this.bridge instanceof MessagePort?this.bridge.close():"undefined"!=typeof window&&this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=null),this.handlers.clear(),this.hostHandlers.clear()}},e.ModuleLoadError=I,e.ModuleLoader=N,e.ModuleMountError=f,e.SDK_NAME=F,e.SDK_VERSION=V,e.SecurityError=r,e.StateManager=class{constructor(e={}){this.state=new Map,this.listeners=new Map,this.snapshots=new Map,this.maxSnapshots=e.maxSnapshots||10}setState(e,t,s,r={}){try{this.state.has(e)||this.state.set(e,new Map);const n=this.state.get(e),o=n.get(t);n.set(t,s),r.snapshot&&this.createSnapshot(e),r.silent||this.notifyStateChange(e,t,s,o)}catch(e){throw console.error("Error setting state:",e),e}}getState(e,t){return this.state.get(e)?.get(t)}getComponentState(e){return this.state.get(e)}subscribe(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){this.listeners.get(e)?.delete(t)}createSnapshot(e){this.snapshots.has(e)||this.snapshots.set(e,[]);const t={timestamp:Date.now(),state:new Map(this.state.get(e))},s=this.snapshots.get(e);s.push(t),s.length>this.maxSnapshots&&s.shift()}restoreSnapshot(e,t=-1){try{const s=this.snapshots.get(e);if(!s?.length)return!1;const r=s[t<0?s.length-1:t];return!!r&&(this.state.set(e,new Map(r.state)),this.notifyStateChange(e,"*",this.getComponentState(e)),!0)}catch(e){return console.error("Error restoring snapshot:",e),!1}}notifyStateChange(e,t,s,r){const n=this.listeners.get(e);n&&n.forEach(n=>{try{n({componentId:e,key:t,newValue:s,oldValue:r})}catch(e){console.error("Error in state change listener:",e)}})}cleanup(e){e?(this.state.delete(e),this.listeners.delete(e),this.snapshots.delete(e)):(this.state.clear(),this.listeners.clear(),this.snapshots.clear())}},e.ThemeManager=class{constructor(e,t){this.events=e,this.activePreset="default",this.currentTheme=this.createDefaultTheme(),t&&this.updateTheme(t),this.setupSystemThemeListener()}getCurrentTheme(){return{...this.currentTheme}}updateTheme(e){try{const t=this.mergeThemes(this.currentTheme,e);this.validateTheme(t),this.currentTheme=t,this.applyTheme(),this.notifyThemeUpdate()}catch(e){throw console.error("Error updating theme:",e),new Error(`Theme update failed: ${e instanceof Error?e.message:"Unknown error"}`,{cause:e})}}setMode(e){this.updateTheme({mode:e}),this.applyColorScheme(e)}setupSystemThemeListener(){window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",e=>{"system"===this.currentTheme.mode&&this.applyColorScheme(e.matches?"dark":"light")})}createDefaultTheme(){return{...P}}mergeThemes(e,t){return{mode:t.mode??e.mode,colors:t.colors?{...e.colors,...t.colors}:e.colors,spacing:t.spacing?{...e.spacing,...t.spacing}:e.spacing,typography:t.typography?{...e.typography,...t.typography}:e.typography}}validateTheme(e){if(Object.entries(e.colors).forEach(([e,t])=>{if(!this.isValidColor(t))throw new Error(`Invalid color value for ${e}: ${t}`)}),e.spacing.unit<=0)throw new Error("Spacing unit must be positive");if(!e.typography.fontFamily)throw new Error("Font family is required")}isValidColor(e){return/^(#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{8}|rgb\(.*\)|rgba\(.*\)|hsl\(.*\)|hsla\(.*\))$/.test(e)}applyColorScheme(e){const t="dark"===e?k:P;this.updateTheme({colors:t.colors})}applyTheme(){document.documentElement.style.setProperty("--theme-mode",this.currentTheme.mode),Object.entries(this.currentTheme.colors).forEach(([e,t])=>{document.documentElement.style.setProperty(`--color-${e}`,t)}),document.documentElement.style.setProperty("--spacing-unit",`${this.currentTheme.spacing.unit}px`),this.currentTheme.spacing.scale.forEach((e,t)=>{document.documentElement.style.setProperty(`--spacing-${t}`,`${e}px`)}),document.documentElement.style.setProperty("--font-family",this.currentTheme.typography.fontFamily),this.currentTheme.typography.scale.forEach((e,t)=>{document.documentElement.style.setProperty(`--font-size-${t}`,`${e}px`)})}notifyThemeUpdate(){this.events.emit("theme:update",{theme:this.currentTheme})}},e.UILoader=$,e.ValidationError=s,e.WidgeticComponent=class{constructor(e,t){this.container=e,this.config=t,this.shadow=this.initializeShadowDOM(),this.state={status:"initializing",error:null},this.events=t.events,this.id=t.id,t.theme&&this.applyTheme(t.theme),this.events&&this.events.on("theme:update",e=>{const t=e?.theme||e;t&&"object"==typeof t&&this.applyTheme(t)})}initializeShadowDOM(){try{return this.container.attachShadow({mode:"closed"})}catch(e){throw console.error("Error initializing shadow DOM:",e),new Error("Failed to initialize component shadow DOM",{cause:e})}}setState(e){this.state={...this.state,...e},this.events.emit("state:update",{componentId:this.id,state:this.state})}handleError(e){console.error(`Error in ${this.constructor.name}:`,e),this.setState({status:"error",error:e}),this.events.emit("error",{componentId:this.id,error:e})}applyTheme(e){this.container.style.setProperty("--theme-mode",e.mode);const t=`\n :host {\n --theme-mode: ${e.mode};\n ${Object.entries(e.colors).map(([e,t])=>`--color-${e}: ${t};`).join("\n")}\n --spacing-unit: ${e.spacing.unit}px;\n ${e.spacing.scale.map((e,t)=>`--spacing-${t}: ${e}px;`).join("\n")}\n --font-family: ${e.typography.fontFamily};\n ${e.typography.scale.map((e,t)=>`--font-size-${t}: ${e}px;`).join("\n")}\n }\n `;if("undefined"!=typeof CSSStyleSheet&&"replaceSync"in CSSStyleSheet.prototype&&this.shadow&&"adoptedStyleSheets"in this.shadow)try{return this.themeStyleSheet||(this.themeStyleSheet=new CSSStyleSheet,this.shadow.adoptedStyleSheets=[...this.shadow.adoptedStyleSheets,this.themeStyleSheet]),void this.themeStyleSheet.replaceSync(t)}catch{}let s=this.shadow.querySelector("style[data-widgetic-theme]");s||(s=document.createElement("style"),s.setAttribute("data-widgetic-theme","true"),this.shadow.appendChild(s)),s.textContent=t}},e.WidgeticUI=$,e.config=v,e.createSecureContext=function(e=[]){const t=new j(e);return{validateMessage:e=>t.validateMessage(e),validateOrigin:e=>t.validateOrigin(e),sanitizeInput:x}},e.createSecureRequest=function(e,t={}){const s=new Headers(t.headers);return s.set("X-Requested-With","XMLHttpRequest"),new Request(e,{...t,headers:s,credentials:"same-origin"})},e.default=W,e.mountModule=A,e.sanitizeInput=x,e.validateOrigin=function(e,t=[]){return new j(t).validateOrigin(e)},e.validateResponse=function(e){if(!e.ok)return!1;const t=e.headers.get("content-type");return t&&!t.includes("application/json")&&console.warn("Unexpected content type:",t),!0},Object.defineProperty(e,"__esModule",{value:!0})});
|
|
2
2
|
//# sourceMappingURL=ui-sdk.js.map
|
package/modules/README.md
CHANGED
|
@@ -56,6 +56,11 @@ shows the API's message with "Try again" and the module emits a non-fatal `error
|
|
|
56
56
|
Only **one File Browser can be mounted per page** for now (see "Known gaps"). Its words can be your visitors' own: pass
|
|
57
57
|
`locale` and `messages` (see "Speaking your visitors' language").
|
|
58
58
|
|
|
59
|
+
The File Browser is a picker unless the page says otherwise: the visitor ticks files, and the confirm button hands them to
|
|
60
|
+
your page (`select`). A page that only manages files, such as a media library of its own, passes `allowSelecting: false`
|
|
61
|
+
(default `true`): nothing can be ticked, there is no confirm button, and the header that only says "Uploads" is left out.
|
|
62
|
+
The visitor still adds and edits files.
|
|
63
|
+
|
|
59
64
|
## Showing your own media library
|
|
60
65
|
|
|
61
66
|
A platform that keeps its files itself (a CMS, an S3 bucket, a DAM) passes `mediaLibrary` instead of `getToken`: an object
|
|
@@ -322,6 +327,14 @@ mount()`, `await unmount()`), imported from `https://cdn.widgetic.com/modules/wi
|
|
|
322
327
|
| `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`. |
|
|
323
328
|
| `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. |
|
|
324
329
|
| `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. |
|
|
330
|
+
| `toolbarPosition` | Where the drawing toolbar (and the element selector) stands along the bottom edge of the canvas: `'BL'` bottom left, `'BC'` bottom centre (the default) or `'BR'` bottom right. For a page that puts something of its own over the middle of the bottom edge (an assistant, a chat bubble). Anything else throws a `TypeError` that names the option. See "A header of your own around the creator". |
|
|
331
|
+
| `showSaveButton` | `false` takes away the canvas's Save button and the dot that says the board has changes the server does not have. Default `true`. The creator saves by itself either way (five seconds after the last change, at the latest fifteen seconds into continuous work, and when the page is hidden or closed). A value that is not `true` or `false` is ignored, with one warning in the console. |
|
|
332
|
+
| `showZoomControls` | `false` takes away the canvas's zoom buttons (zoom out, the zoom level that puts the board back to 100%, zoom in, fit to view). Default `true`. The board still zooms with the wheel, a pinch and the keyboard: only the buttons are gone. For a page that has no room for them, or that lets people move around the board some other way. A value that is not `true` or `false` is ignored, with one warning in the console. A creator that does not have the option yet (older than the release that added it) ignores it. |
|
|
333
|
+
| `showCanvasFileBrowser` | `true` adds a "Files" entry to the canvas's Shapes menu (the "More shapes" button), right before "Image". It opens the File Browser in the state of choosing, over YOUR `mediaLibrary` (or the user's Widgetic uploads when you gave none), and the files the user ticks go on the sketch. Only pictures and SVG files are listed, found by the search and taken by an upload there; the user can tick several. A page that gave `pickFile` is asked for them instead (`accept: ['image/*', 'image/svg+xml', '.svg']`, `multiple: true`, as for the files of a widget's fields). Default `false`. A value that is not `true` or `false` is ignored, with one warning in the console. A creator that does not have the option yet (older than the release that added it) ignores it. See "Your files on the canvas". |
|
|
334
|
+
| `showSketchBar` | `false` takes away the creator's own bar above the board (title, Live, Publish). Default `true`. For a page that already draws that chrome around the creator. Publish still runs through `publish()` and `publishStateChanged`. A value that is not `true` or `false` is ignored, with one warning in the console. |
|
|
335
|
+
| `limitNotices` | `'all'` (the default) or `'chat'`. When a limit refuses the user (credits used up), `'all'` tells them in a toast and in the chat; `'chat'` in the chat alone, for a page that draws its own notice (see `limitReached`). Other failures keep their toast. Anything else throws a `TypeError` that names the option. |
|
|
336
|
+
| `mascot` | `false` draws the chat's assistant as a plain round avatar instead of Widgetic's animated mascot (a scribble that thinks, writes and ends in its success or error look), and keeps the chat silent: the mascot's small sounds go with it. Default `true`. Nothing else about the chat changes. A value that is not `true` or `false` is ignored, with one warning in the console. A creator that has no mascot yet ignores it. |
|
|
337
|
+
| `initialMessage` | Words for the chat of a new widget, and the pictures that go with them: `{ text: 'Replicate this design: https://…', send: true }`, or `{ text: 'Replicate this photo', send: true, attachments: [file] }`. `text` is words, not empty, at most 4000 characters. `attachments` is a list of at most 5 `File`s of your page's own (a photo the user chose on your page, not a link: the builder looks at a picture that is attached, not at an address in the text), each a PNG, JPEG, WebP or GIF of at most 10 MB. With `send: true` the creator sends it as the first message when the chat is ready, exactly as if the user had typed it, attached the pictures and pressed Enter; without `send` the words and the pictures wait in the chat's input. Used once, for a new widget (`startWithNewWidget: true`); a widget that already has a draft keeps its own. A wrong shape throws a `TypeError` that names the option (and the picture, by its place in the list). |
|
|
325
338
|
| `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. |
|
|
326
339
|
| `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. |
|
|
327
340
|
| `pickFile` | Your own file picker for file fields (see "Partner file picker (`pickFile`)"). Without it the built-in File Browser is used. |
|
|
@@ -336,6 +349,8 @@ shown the picker it comes after they chose), `presetChosen` `{ key, canvasId, wi
|
|
|
336
349
|
`{ canvasId }` (the creator opened a canvas or made one: keep the id and give it back next time), `widgetRenamed`
|
|
337
350
|
`{ widgetId, name }` (the main widget has this name: said when the canvas opens and each time the user renames it, never
|
|
338
351
|
twice in a row for the same name, so you can keep a title for the user's work), `widgetPublished` `{ widgetId, version? }`,
|
|
352
|
+
`publishStateChanged` `{ widgetId, canPublish, publishing, label, unpublished }` (what Publish would do now, for a page that
|
|
353
|
+
draws its own Publish button: see "A header of your own around the creator"),
|
|
339
354
|
`limitReached` `{ message, code? }` (the visitor ran into a limit; the creator tells them in plain words, this is for your
|
|
340
355
|
page: see "When a limit is reached"), `reloadRequested` (the creator would have reloaded the page to recover: unmount it and mount a new one),
|
|
341
356
|
and `error` `{ message, code?, fatal, during?, sessionEnded? }`. `fatal: false` with `during: 'presets'` is the starting points
|
|
@@ -346,7 +361,88 @@ again without it). Either way, no `ready` comes, and the creator stops asking th
|
|
|
346
361
|
|
|
347
362
|
Methods: `getCanvasId()` (the canvas that is open now, or `null`), `setTheme(theme)` (see "Looking like your product"),
|
|
348
363
|
`setLanguage({ locale?, messages? })` and, to hand to a translator, `defaultMessages` and `checkMessages(messages)` (see
|
|
349
|
-
"Speaking your visitors' language"), `
|
|
364
|
+
"Speaking your visitors' language"), `getPublishState()`, `publish()`, `flush()` and `setWidgetName(name, widgetId?)` (see
|
|
365
|
+
"A header of your own around the creator"), `unmount()`.
|
|
366
|
+
|
|
367
|
+
**A header of your own around the creator.** A page that draws its own bar above the creator (a Back arrow, the name of the
|
|
368
|
+
widget the user is on, a Publish button) is given what it needs, and the creator's own controls for the same things can
|
|
369
|
+
be put aside:
|
|
370
|
+
|
|
371
|
+
```js
|
|
372
|
+
creator.on('publishStateChanged', ({ canPublish, publishing, label }) => drawPublishButton({ enabled: canPublish && !publishing, label }));
|
|
373
|
+
publishButton.onclick = async () => {
|
|
374
|
+
try {
|
|
375
|
+
await creator.publish(); // resolves after `widgetPublished`
|
|
376
|
+
goBackToMyDashboard();
|
|
377
|
+
} catch (error) {
|
|
378
|
+
// the creator has told the user why it could not (nothing to publish yet, a limit, a failed publish); this is for you
|
|
379
|
+
}
|
|
380
|
+
};
|
|
381
|
+
backButton.onclick = async () => {
|
|
382
|
+
await creator.flush(); // the last change is on the server before the page leaves
|
|
383
|
+
goBackToMyDashboard();
|
|
384
|
+
};
|
|
385
|
+
nameField.onchange = () => creator.setWidgetName(nameField.value); // the widget the user is on; pass a widgetId for another one
|
|
386
|
+
```
|
|
387
|
+
|
|
388
|
+
- **`publishStateChanged`** `{ widgetId, canPublish, publishing, label, unpublished }`: `widgetId` is the widget `publish()`
|
|
389
|
+
would publish (the one the user is on, the main widget of the canvas while no other is open; `null` while there is none);
|
|
390
|
+
`canPublish` is `true` when nothing is running and the creator's own Publish button can be pressed. That includes a widget
|
|
391
|
+
the creator has made nothing for yet: the creator's button then nudges the chat's Send button and publishes nothing, and
|
|
392
|
+
`publish()` does the same (it resolves, and says neither `widgetPublished` nor `error`), so take the user away on
|
|
393
|
+
`widgetPublished` and not when `publish()` resolves. (Modules 0.2.23 and earlier said `false` for such a widget.) `publishing`
|
|
394
|
+
is `true` while a publish of it runs; `label` is the creator's own button's words ("Publish" or "Publish changes", in your page's language);
|
|
395
|
+
`unpublished` is `true` when the widget has changes no published version has. It is said when the creator first knows,
|
|
396
|
+
then at every change and never twice with the same state. `getPublishState()` gives the last one (a copy, `null` before the
|
|
397
|
+
creator said any) to a page that draws its button after the creator reported.
|
|
398
|
+
- **`publish()`** does what the creator's own Publish button does and resolves when it is done, after `widgetPublished`
|
|
399
|
+
(the creator now says `widgetPublished` for a session too). It rejects, and does nothing, when the creator is not on
|
|
400
|
+
screen (call it after `mount()` has finished and before `unmount()`), when the creator is one that cannot be told to
|
|
401
|
+
publish, or with the creator's own reason when it cannot publish now; the creator shows that reason to the user as it
|
|
402
|
+
does when its own button is pressed.
|
|
403
|
+
- **`flush()`** puts what the user changed in the canvas on the server now and resolves when that is done. Wait for it
|
|
404
|
+
before your page takes the user away from the creator. In the first three seconds after the creator has opened a canvas
|
|
405
|
+
it keeps a change back (opening a canvas redraws its shapes, and a redraw looks like a change), so a `flush()` called then
|
|
406
|
+
waits for those seconds to be over: up to three seconds, never more than six. Called later it is quick, and with nothing
|
|
407
|
+
waiting it resolves at once. (Modules 0.2.15 and 0.2.16 could resolve in that first moment, before the save was sent.) It
|
|
408
|
+
never rejects: with nothing on screen nothing is unsaved, and a save that fails is the creator's to say (the problem is
|
|
409
|
+
written to the console, once).
|
|
410
|
+
- **`setWidgetName(name, widgetId?)`** renames the widget the page names, or the one the user is on without a `widgetId`.
|
|
411
|
+
The creator shows the new name at once and saves it, and says `widgetRenamed` (your page sees its own change come back, so
|
|
412
|
+
ignore an old name while your own rename is on its way). It rejects, and renames nothing, for a name that is not text or
|
|
413
|
+
is empty, when the creator is not on screen, or when the creator is one that cannot be renamed from the page.
|
|
414
|
+
- **`showSaveButton: false`** removes the canvas's Save button and the dot next to it; **`showZoomControls: false`** removes
|
|
415
|
+
the canvas's zoom buttons (the wheel, a pinch and the keyboard still zoom); **`showSketchBar: false`** removes
|
|
416
|
+
the creator's own title/Live/Publish bar when the page already draws one; **`toolbarPosition`** moves the
|
|
417
|
+
drawing toolbar out of the way of something of your own along the bottom edge; **`limitNotices: 'chat'`** keeps the
|
|
418
|
+
refusal because of a limit to the line in the chat; **`initialMessage`** starts a new widget with words in the chat
|
|
419
|
+
(a link and an instruction, say, or a photo the user chose on your page, as `attachments`) and, with `send: true`, sends
|
|
420
|
+
them for the user, which makes the widget and starts the build.
|
|
421
|
+
- **Your files on the canvas (`showCanvasFileBrowser: true`).** The canvas's Shapes menu (the "More shapes" button) gets a
|
|
422
|
+
**Files** entry right before **Image**. It opens the File Browser in a dialog, in the state of choosing, and the pictures and
|
|
423
|
+
SVG files the user ticks are put on the sketch (several at once). Off by default: a page that wants it passes `true`.
|
|
424
|
+
- *Which files it shows.* Your `mediaLibrary` when you gave one: the flat list your `list` returns (the browser keeps the
|
|
425
|
+
pictures and the SVG files itself, so `list` does not have to filter; the search, the type filter and an upload there
|
|
426
|
+
are limited to the same kinds). The user's own Widgetic uploads, of the workspace they are in, when you gave none. A
|
|
427
|
+
`pickFile` of yours takes the place of the browser and is called with `{ accept: ['image/*', 'image/svg+xml', '.svg'],
|
|
428
|
+
multiple: true, signal }`; return the files as your library describes them (`{ id, name, url, mimeType }`), or an empty
|
|
429
|
+
list when the user closed your picker.
|
|
430
|
+
- *What the board does with your library.* It only ever adds from it: taking a picture off the sketch never deletes the file
|
|
431
|
+
from the library. A picture the sketch has that the library lacks (a photo the user dropped on the board, a drawing) is
|
|
432
|
+
saved to the library in the background, once per picture, through `mediaLibrary.upload({ file, purpose: 'canvas' })`: when
|
|
433
|
+
the user sends the first message and when the sketch is turned into the widget; a library with no `upload` is read and
|
|
434
|
+
left as it is. The builder is told the board's library files by name and address, so it uses those very files in the
|
|
435
|
+
widget it makes.
|
|
436
|
+
- *What the assistant that sketches may use.* When the user asks it to sketch, it is told the first page of your library
|
|
437
|
+
(the creator calls `list({ limit: 60, signal })` and keeps the answer for a minute, so list the newest, or the most useful,
|
|
438
|
+
files first) and may place its pictures and SVG icons on the sketch. It places only files of that list: it never invents
|
|
439
|
+
an address.
|
|
440
|
+
- *A creator older than the option* ignores it (there is no entry), and so does a module older than the option (it never
|
|
441
|
+
passes it on): release the creator, then the modules.
|
|
442
|
+
- **A creator older than these.** A module that is newer than the creator it carries ignores the options the creator does not
|
|
443
|
+
know, `publish()` and `setWidgetName()` reject with a message that says so, and `flush()` resolves at once with one
|
|
444
|
+
warning in the console. A page that wants to know checks `typeof creator.publish === 'function'` on the module it
|
|
445
|
+
loaded from the CDN: an older module lacks the methods altogether.
|
|
350
446
|
|
|
351
447
|
**What it keeps.** It does not touch your page's `localStorage`, `sessionStorage`, cookies or address bar, and never
|
|
352
448
|
opens a window, reloads or navigates your page: what it remembers (the user's settings, colour presets, the canvas that
|
|
@@ -355,7 +451,8 @@ it follows a generation over the API's event stream.
|
|
|
355
451
|
|
|
356
452
|
**When a limit is reached.** Your credits, your plan and your storage are yours: a visitor is never told what they hold.
|
|
357
453
|
The API refuses a session with one plain sentence ("This is not available right now. Please try again later.") and the
|
|
358
|
-
creator shows exactly that, in the chat with a *Retry* button and in a toast
|
|
454
|
+
creator shows exactly that, in the chat with a *Retry* button and in a toast (`limitNotices: 'chat'` leaves the toast out,
|
|
455
|
+
for a page that draws its own notice), and keeps working: the canvas, the chat and
|
|
359
456
|
the other widgets are still there. It also tells *your page*, with
|
|
360
457
|
`limitReached` `{ message: 'The visitor reached a limit.', code }`, where `code` is what the API answered:
|
|
361
458
|
|
|
@@ -440,7 +537,9 @@ module gives it a shadow root, a theme, a language, a session and a way to tell
|
|
|
440
537
|
name, date created, last published or visitors, new workflow, duplicate, delete) and, when one is opened, the editor: a
|
|
441
538
|
canvas of Composition, Trigger and Condition blocks that go forward only (up to 25), a side panel for the selected block,
|
|
442
539
|
a draft that is saved while you work, publish and discard, a history of versions that never change, a Test run that plays a
|
|
443
|
-
visitor through the draft, a Runs tab
|
|
540
|
+
visitor through the draft, a Runs tab that draws how far visitors came as a funnel (a Sankey diagram: a bar for each
|
|
541
|
+
composition, a band for each way between two of them, as wide as the visitors who went that way, and a red part under a bar for the
|
|
542
|
+
times that composition could not be shown), and a Settings tab (time zone, embed
|
|
444
543
|
code, pause, archive, duplicate, delete). A trigger is enabled for a composition only when its widget can supply it (values a
|
|
445
544
|
visitor adds need a Pro widget that keeps data); the reason is told next to the choice. *New workflow* asks for a name and for
|
|
446
545
|
where to start: a blank workflow, or a starting point (a preset) the workspace is offered, which is Widgetic's for a person with a
|
|
@@ -477,7 +576,7 @@ window.addEventListener('popstate', () => workflows.module.setWorkflow(workflowO
|
|
|
477
576
|
| `getToken` | **Required**, and the same as for the other modules: `getToken({ reason })` resolves with a token the API accepts for the workspace's workflows, bare or as `{ token, expiresAt }`. Two kinds work: the token of a **signed-in person who may work in that workspace** (a member of the team, or the partner's own account), the way the Widgetic site calls the API, or an **editor session** your server minted for one of your customers with `surfaces: ['workflows']` ("Showing it to your customers"). It is called once before the screen 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). |
|
|
478
577
|
| `apiUrl` | The API origin (`https://api.widgetic.com` unless you run your own). |
|
|
479
578
|
| `workflowId` | The workflow to open first. Leave it out for the list. After mounting the screen moves by itself (and says so with `openWorkflow`); `setWorkflow` moves it from the page. |
|
|
480
|
-
| `presence` | `true` tells the people of a team who else has the workflow open: "Anna is editing", with a choice to take over or to only look (default `false`, read once when the module mounts). It is for an organization's workspace and a person who may change the workflow; for `personal`, or for a token the edit-lease routes refuse (an editor session), the screen carries on as if it were off, without asking again. It is presence, never a lock: nobody is shut out, and a save that finds the draft changed by somebody else asks the person what to do (*Keep my changes as a copy* first, if they like, then *Load the latest version*) whether `presence` is on or not. A value that is not `true` or `false` is ignored, with one warning in the console. |
|
|
579
|
+
| `presence` | `true` tells the people of a team who else has the workflow open: "Anna is editing", with a choice to take over or to only look (default `false`, read once when the module mounts). The list says it too: a row shows "Anna is editing" under the name of a workflow a teammate has open ("Someone is editing" when the API gives no name). The list asks the API once for the whole page of rows, again every twenty seconds or so while the tab can be seen (never while it is hidden), and a look takes and renews nothing, so a person who only looks at the list does not become an editor of anything. It is for an organization's workspace and a person who may change the workflow; for `personal`, or for a token the edit-lease routes refuse (an editor session), the screen carries on as if it were off, without asking again. It is presence, never a lock: nobody is shut out, and a save that finds the draft changed by somebody else asks the person what to do (*Keep my changes as a copy* first, if they like, then *Load the latest version*) whether `presence` is on or not. A value that is not `true` or `false` is ignored, with one warning in the console. |
|
|
481
580
|
| `theme`, `themeFromHost` | The colours, the corners and the typeface ("Looking like your product"). |
|
|
482
581
|
| `locale`, `messages` | The language ("Speaking your visitors' language"). |
|
|
483
582
|
|
|
@@ -719,7 +818,7 @@ files.setLanguage({ locale: 'de', messages: germanMessages }); // later, while i
|
|
|
719
818
|
| `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. |
|
|
720
819
|
| `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. |
|
|
721
820
|
|
|
722
|
-
**Translation packs (shipped languages).** Each pack is one lazy file next to `index.js` (gzip budget per pack: File Browser **5 kB**, composition editor **
|
|
821
|
+
**Translation packs (shipped languages).** Each pack is one lazy file next to `index.js` (gzip budget per pack: File Browser **5 kB**, composition editor **10 kB**, widget creator **28 kB**, Workflows **10 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, with the 439 of Workflows); 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 (Workflows waits for the token and the pack both before it draws anything, so its first paint is always in the language). 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.
|
|
723
822
|
|
|
724
823
|
**`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).
|
|
725
824
|
|
|
@@ -783,8 +882,7 @@ await mountModule('file-browser', { container: '#media', getToken, locale: 'ar'
|
|
|
783
882
|
Browser above, turned around with it.
|
|
784
883
|
- **The widget creator:** the tools of the toolbar run from the start of the line, the properties panel is docked at the
|
|
785
884
|
end of it, the context menu, the list of shapes, the publish history and the starting-point picker are laid out from the
|
|
786
|
-
start, the title of a widget in its panel keeps the room it needs
|
|
787
|
-
start edge of its button. The composition editor and the File Browser inside the creator are turned around the same
|
|
885
|
+
start, and the title of a widget in its panel keeps the room it needs. The composition editor and the File Browser inside the creator are turned around the same
|
|
788
886
|
way.
|
|
789
887
|
- **Workflows:** everything is placed by the start and the end of the line (the package's `tests/workflows-direction.test.mjs`
|
|
790
888
|
fails on a physical side), so the list, the top bar of the editor, the tabs, the side panel, the menus and the dialogs
|
|
@@ -887,8 +985,8 @@ editor.setLanguage({ locale: 'pl', messages: polishMessages }); // labels and bu
|
|
|
887
985
|
takes **one flat `messages` object for all of it**. The creator is made of parts that each have their own words, and it
|
|
888
986
|
splits what you give between them, so you never need to know which part says a word:
|
|
889
987
|
|
|
890
|
-
- the creator's own words, the `creator.` keys: the widget's panel, publishing and versions,
|
|
891
|
-
|
|
988
|
+
- the creator's own words, the `creator.` keys: the widget's panel, publishing and versions, chat generation options
|
|
989
|
+
(language and custom libraries in debug), the limits it explains, the lines of its status bar; the preset **Libraries** toggle and its
|
|
892
990
|
add-library control are drawn only in creator debug mode (`showPresetLibraries`), which the widget creator module does
|
|
893
991
|
not turn on, but their messages stay in the catalog for hosts that do;
|
|
894
992
|
- the chat's words (`chat.` keys) and the canvas's (`canvas.` keys: the toolbar, the zoom controls, the context menu, the
|
|
@@ -942,14 +1040,14 @@ creator.setLanguage({ locale: 'de', messages: germanMessages }); // every screen
|
|
|
942
1040
|
code stay left to right.
|
|
943
1041
|
|
|
944
1042
|
**Workflows.** It takes the same `locale`, `messages`, `setLanguage`, `defaultMessages` and `checkMessages`, with **one**
|
|
945
|
-
`messages` object for all of it: its
|
|
1043
|
+
`messages` object for all of it: its 439 `workflows.` keys (the list, the editor and its panels, the names of blocks,
|
|
946
1044
|
operators and units, what the engine finds wrong with a workflow, what a failed request means, and the words of the screen
|
|
947
|
-
that says a part could not be drawn). The words of a block are made of parts the screen puts together (`{field} {value}`,
|
|
1045
|
+
that says a part could not be drawn and why). The words of a block are made of parts the screen puts together (`{field} {value}`,
|
|
948
1046
|
`{count, plural, ...}`), so a language that puts them in another order can say so in its own message.
|
|
949
1047
|
|
|
950
1048
|
- **It speaks the twelve languages of the other modules.** `Workflows.supportedLocales` lists them (`fr`, `de`, `es`,
|
|
951
1049
|
`pt-BR`, `nl`, `da`, `sv`, `zh-CN`, `ar`, `he`, `fa`, `ur`) and `Workflows.localePackStatus(tag)` is `'provisional'` for
|
|
952
|
-
each: a `locale` that has a pack fetches one lazy file of
|
|
1050
|
+
each: a `locale` that has a pack fetches one lazy file of 439 messages (30 to 44 kB, 8.0 to 9.3 kB gzipped; the budget is
|
|
953
1051
|
10 kB gzipped), and `mount()` waits for it, so the first paint is already in that language. A `locale` with no pack
|
|
954
1052
|
(English, `zh-TW`, an unknown tag) downloads nothing and says nothing in the console: the words stay English, while the
|
|
955
1053
|
plural rules and the direction follow `locale` either way. Your `messages` win over the pack, key by key. The packs are
|
|
@@ -981,6 +1079,7 @@ itself, which no `messages` could ever translate. The same trick works on your o
|
|
|
981
1079
|
| `npm test` | Unit tests (vitest): token source, session token provider, emitter, picked files, shadow mount, the composition editor, widget creator and Workflows 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 |
|
|
982
1080
|
| `npm run harness` | Serves `harness/hostile.html`, `harness/composition-editor.html`, `harness/widget-creator.html`, `harness/workflows.html` and a mock Widgetic API on http://localhost:5290 |
|
|
983
1081
|
| `npm run test:e2e` | Playwright against the harness (`PLAYWRIGHT_CHANNEL=chrome` uses the installed Google Chrome instead of Playwright's download) |
|
|
1082
|
+
| `npm run e2e:compare -- <log of the new build> <log of the live files>` | Sets two runs of the browser tests against each other, test by test (see "Comparing two runs of the browser tests", below). Exit code 1 when a test is green on the live files and is red, or was not run, on the new build; 2 when a log cannot be compared |
|
|
984
1083
|
| `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") |
|
|
985
1084
|
| `npm run publish:cdn -- <module> [options]` | Releases a module to the CDN: see "Publishing". `--help` lists every option |
|
|
986
1085
|
| `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 |
|
|
@@ -991,6 +1090,28 @@ itself, which no `messages` could ever translate. The same trick works on your o
|
|
|
991
1090
|
Run `npm run build` (or the `build:<module>` of the one you test) before `npm run harness` / `npm run test:e2e`: the
|
|
992
1091
|
harness serves `dist/`.
|
|
993
1092
|
|
|
1093
|
+
### Comparing two runs of the browser tests
|
|
1094
|
+
|
|
1095
|
+
Many of the browser tests are red on any machine, on the new build and on the build that is live alike, so how many are red
|
|
1096
|
+
says nothing about a release. What holds a release back is a test that is green on the live files and is not green on the
|
|
1097
|
+
new build. The release pipeline does not run these tests (see "Releasing from a tag"), so this is the check you make before
|
|
1098
|
+
you tag:
|
|
1099
|
+
|
|
1100
|
+
1. Run the tests on the new build: `PLAYWRIGHT_CHANNEL=chrome PORT=<a free port> npm run test:e2e -- --reporter=list > /tmp/e2e-new.log 2>&1`.
|
|
1101
|
+
2. Put the build that is live in `dist/` (build its tag again, or download its files from the CDN) and run the same command
|
|
1102
|
+
into `/tmp/e2e-live.log`.
|
|
1103
|
+
3. `npm run e2e:compare -- /tmp/e2e-new.log /tmp/e2e-live.log`.
|
|
1104
|
+
|
|
1105
|
+
The report names, by file and chain of titles (never by line number, which moves), the tests that went from green to red,
|
|
1106
|
+
the tests that were green and were not run (in a serial group the tests after a red one are not run), the tests that went
|
|
1107
|
+
from red to green, and the tests that are in only one of the two runs. The tests that are red on both, and green on both,
|
|
1108
|
+
are counted, and listed with `--all`; `--files '<regular expression>'` keeps the tests of the files that match.
|
|
1109
|
+
|
|
1110
|
+
Exit code 0: nothing that was green on the live files is lost. 1: something is, and each test is named: explain or fix each
|
|
1111
|
+
one before the manifests move. 2: a log cannot be compared (it is not found, it is empty, it was cut short, or its counts
|
|
1112
|
+
are not those of its own summary), which is never a pass. The logic is in `scripts/lib/e2eRunComparison.mjs`, and
|
|
1113
|
+
`tests/e2eRunComparison.test.mjs` holds it.
|
|
1114
|
+
|
|
994
1115
|
### Size budget
|
|
995
1116
|
|
|
996
1117
|
A partner's page downloads, parses and runs `index.js` before the module appears, and fetches the lazy files only when a
|
|
@@ -1085,8 +1206,7 @@ a wrong shape.
|
|
|
1085
1206
|
every message of `WidgetCreatorModule.defaultMessages` wrapped in marks). It walks the canvas with a widget's shape selected
|
|
1086
1207
|
(the toolbar, the zoom controls, the properties panel and the pop-up region), the details of the widget (the chat, what it
|
|
1087
1208
|
sends, the version menu with its dates), the canvas's context menu with a shape selected and with nothing selected, More
|
|
1088
|
-
Shapes, the question before a shape is removed (a sentence made of three pieces), the
|
|
1089
|
-
(not the preset **Libraries** section, which debug mode alone draws), a refusal and the pop-up it brings with its close
|
|
1209
|
+
Shapes, the question before a shape is removed (a sentence made of three pieces), a refusal and the pop-up it brings with its close
|
|
1090
1210
|
button, the moment before the picker, the picker and
|
|
1091
1211
|
a copy that fails, and fails on any text, label, hint or picture description a visitor can read or hear and that has no
|
|
1092
1212
|
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
|
|
@@ -1150,6 +1270,14 @@ button is pressed (and that ordinary rate limiting is not reported as a limit).
|
|
|
1150
1270
|
one for each managed user, to check that the two work at once on their own canvases without refusing, telling or showing
|
|
1151
1271
|
each other anything.
|
|
1152
1272
|
|
|
1273
|
+
A test that needs a build to last long enough to be looked at says so the same way: `POST /mock/_config` with `{ generation:
|
|
1274
|
+
{ durationMs?, codeStartsMs?, thinkingTail?, streamTail?, plan? } }` sets how a code generation runs from then on: how long it
|
|
1275
|
+
lasts, when the thinking ends and the code starts, the text each one shows (an empty `thinkingTail` shows neither), and a build
|
|
1276
|
+
plan `{ title?, tasks: [{ id, label, kind? }], decisions? }` that the operation reports with its tasks done one after the other
|
|
1277
|
+
over the run (`plan: null` takes it away). Until a test says otherwise a generation lasts 700 ms, with the code from 220 ms
|
|
1278
|
+
and no plan, and `/mock/_reset` puts that back. `e2e/widgetCreatorShopifyFeedback.spec.ts` uses it to look at the generation
|
|
1279
|
+
card (the thinking, then the code, in one card) and at the plan card above it.
|
|
1280
|
+
|
|
1153
1281
|
Two rules of the gateway decide whether a call reaches these mocks at all, and `harness/gatewayRequestRules.mjs` holds both.
|
|
1154
1282
|
The first is the request headers a page on another origin may send (the gateway's `ALLOWED_REQUEST_HEADERS`, in its
|
|
1155
1283
|
`src/middleware/editorSessionCors.ts`, plus the File Browser's upload headers): the browser enforces it at the preflight, so a
|
|
@@ -1195,18 +1323,44 @@ src/shared/ what every module uses
|
|
|
1195
1323
|
src/file-browser/ the module: index.ts (public API), FileBrowserHost.svelte, pickedFile.ts, module.css
|
|
1196
1324
|
src/composition-editor/ the module: index.ts (public API), CompositionEditorHost.svelte, module.css, tiptapBase.css
|
|
1197
1325
|
src/widget-creator/ the module: index.ts (public API), WidgetCreatorHost.svelte, module.css
|
|
1198
|
-
scripts/build-module.mjs the Vite build; scripts/plugins/* the CSS and package fixes below
|
|
1326
|
+
scripts/build-module.mjs the Vite build for a release; scripts/plugins/* the CSS and package fixes below
|
|
1327
|
+
scripts/module-dev-server.mjs the Vite dev server the Shopify admin uses; it compiles a module when the page asks
|
|
1199
1328
|
```
|
|
1200
1329
|
|
|
1201
1330
|
`module.css` is compiled once by Tailwind and the build exports it as two strings: `shadowCss` (goes into the shadow
|
|
1202
1331
|
root) and `documentCss` (the few rules that must live in the page: `@font-face`).
|
|
1203
1332
|
|
|
1333
|
+
### Building from the checkout
|
|
1334
|
+
|
|
1335
|
+
`node scripts/build-module.mjs <name> --from-source` compiles that module from the sibling packages' `src`
|
|
1336
|
+
(file-browser, design-system, editor, canvas, chat, creator, workflows, and the rest) instead of from the copies in
|
|
1337
|
+
`node_modules`. `--watch` rebuilds when one of those files is saved. The Shopify dev app does not use that watch; it compiles on request, in the next section. A package that is not cloned stays the
|
|
1338
|
+
installed copy, and a bare import that the clone has not installed (`kaykay`, for example) is taken from this
|
|
1339
|
+
workspace. A SvelteKit `tsconfig` that extends a generated file is not read. `npm run build` and `publish:cdn`
|
|
1340
|
+
do not pass `--from-source`, so a published module is still built from the registry packages.
|
|
1341
|
+
|
|
1342
|
+
The Tailwind entry stays the installed `@widgetic/design-system` stylesheet. Pointing that import at the
|
|
1343
|
+
checkout's `global.css` pulls in that package's own Tailwind config and the module loses its layout. The
|
|
1344
|
+
`@source` lines in `module.css` are rewritten to the sibling `src` for the build, so the classes in the
|
|
1345
|
+
checkout are the ones that end up in the script.
|
|
1346
|
+
|
|
1347
|
+
### The Shopify dev app compiles source on request
|
|
1348
|
+
|
|
1349
|
+
`npm run dev:admin` in `Integrations/shopify` does not run `build-module.mjs --watch`. `dev-modules.mjs` walks up to this checkout and starts `scripts/module-dev-server.mjs`. The admin page still loads `/dev-modules/<name>/index.js`. That file re-exports `src/<name>/index.ts`, and this server compiles it when the browser asks, with the same aliases, shadow stylesheet, and package patches as the release build. A save of one file is ready on the next request. The first open of a screen compiles the files that screen uses. A package that is not cloned stays the installed copy.
|
|
1350
|
+
|
|
1351
|
+
The tunnel host (`https://<name>.trycloudflare.com`) is the local React app. It changes every time `npm run dev:admin` starts. `https://canvas.widgetic.com` is the production app. `https://cdn.widgetic.com` is a released module. This server writes neither.
|
|
1352
|
+
|
|
1353
|
+
`npm run build` and `publish:cdn` do not start this server. A release is still the minified file from the registry packages, described under "Publishing". The dev server is not a second way to publish. The admin setup is in `Integrations/shopify/__docs/dev-app-and-tunnel.md`.
|
|
1354
|
+
|
|
1204
1355
|
### One file, and the parts that are not in it
|
|
1205
1356
|
|
|
1206
1357
|
A module is `index.js`, which has everything the module needs to appear and to work, and the **lazy files** in `chunks/`:
|
|
1207
1358
|
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
|
|
1208
|
-
visitor who previews a PDF
|
|
1209
|
-
|
|
1359
|
+
visitor who previews a PDF, and, in the widget creator, Three.js (0.75 MB) and the mascot's sound engine, which the creator
|
|
1360
|
+
fetches as soon as it is open so that the mascot is ready for the first answer (`mascot: false` never asks for them), and
|
|
1361
|
+
Prettier (0.76 MB, in three files), for the chat's code card when it first lays out a script. `index.js` fetches one when it
|
|
1362
|
+
is needed, from the folder it was itself loaded from (`import.meta.url`), so the files of a version work wherever that
|
|
1363
|
+
folder is: the CDN, a mirror, a partner's own copy.
|
|
1210
1364
|
|
|
1211
1365
|
```
|
|
1212
1366
|
dist/file-browser/index.js 1.50 MB everything the File Browser needs to open
|
|
@@ -1407,8 +1561,8 @@ What is left:
|
|
|
1407
1561
|
- **The fixes are released.** They were in branches of those packages (`feat/embed-in-shadow-root` of the canvas and the
|
|
1408
1562
|
chat, `feat/partner-host-mode` of the creator); `package.json` now asks for `@widgetic/canvas` ^0.5.19,
|
|
1409
1563
|
`@widgetic/chat` ^0.1.18 and `@widgetic/creator` ^0.4.0, which are on npm, and the lockfile pins them.
|
|
1410
|
-
- **Size.** 6.
|
|
1411
|
-
the creator itself (
|
|
1564
|
+
- **Size.** 6.3 MB (1.5 MB gzip) to open, which is 98% of its 6.45 MB budget, and 9.3 MB (2.3 MB gzip) in all, with the PDF viewer
|
|
1565
|
+
and the twelve language packs (a page downloads the one of its own language): the creator itself (573 kB), the whole canvas with fabric (370 kB), the chat, the editor's controls and their libraries. The canvas and the details panel
|
|
1412
1566
|
stay in `index.js` on purpose: the creator asks for the canvas as soon as it starts, and they share the Svelte runtime
|
|
1413
1567
|
and most of the creator, which a lazy file cannot (see "One file, and the parts that are not in it").
|
|
1414
1568
|
- **Stop only stops the creator waiting.** The Stop button ends the creator's wait for a generation. The gateway's cancel
|
|
@@ -1497,7 +1651,9 @@ A tag whose name is not `modules-v<version>` makes no pipeline, so if a tag star
|
|
|
1497
1651
|
- **`verify`** holds no key. It refuses a tag that is not protected, a commit that is not on the default branch, a tag
|
|
1498
1652
|
whose version is not the one in `package.json`, a lockfile the pipeline cannot install, and a module whose changelog
|
|
1499
1653
|
has no entry for the version. Then it runs the typecheck, the unit tests and the build with its size budgets. It does
|
|
1500
|
-
not run the browser tests (`npm run test:e2e`, which need browsers): run them before you tag
|
|
1654
|
+
not run the browser tests (`npm run test:e2e`, which need browsers): run them before you tag, on the new build and on the
|
|
1655
|
+
build that is live, and set the two logs against each other with `npm run e2e:compare` (see "Comparing two runs of the
|
|
1656
|
+
browser tests").
|
|
1501
1657
|
- **`publish`** is the only job that sees the keys. It releases **every module in `dist/`** in three passes
|
|
1502
1658
|
(`scripts/release-modules.mjs`, which runs the commands of "By hand" for each module):
|
|
1503
1659
|
1. *ask*: `--dry-run --skip-build`. It reads the CDN and refuses, before anything is written, a version that is already
|
|
@@ -1584,6 +1740,9 @@ By a person who can change the project's settings in GitLab.
|
|
|
1584
1740
|
commit the lockfile. `npm run release:check` says what is missing, and `verify` stops at its first step when the
|
|
1585
1741
|
lockfile cannot be installed, which is where it should. (Done on 2026-10-09: every package is released, the ranges
|
|
1586
1742
|
in `package.json` ask for them and `npm run release:check -- --tag modules-v0.1.0` passes.)
|
|
1743
|
+
`@widgetic/api-sdk` is private. Every job that runs `npm ci` writes the group variable `NPM_TOKEN` into npm's
|
|
1744
|
+
config first, including the loader build. The variable is protected and masked, so only a protected branch or tag
|
|
1745
|
+
receives it.
|
|
1587
1746
|
6. **The first release of every module is made by hand,** with `--allow-create` (below).
|
|
1588
1747
|
|
|
1589
1748
|
### The first release, in order
|