@widgetic/ui-sdk 0.1.13 → 0.1.14

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 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`, `messages`. Widget creator: `canvasId`, `widgetId`, `startWithNewWidget`, `presets`, `startFromPreset`, `presetLabels`, `messages`, `mediaLibrary`, `pickFile`, `widgetBuilderUrl`. 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)). |
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`. 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
 
@@ -286,8 +286,17 @@ await editor.unmount();
286
286
  for an editor session `lastEditedBy` and `lastEditedAt` are `null`) and, once somebody chose, as `conflictResolved`
287
287
  (`{ resolution: 'keepMine' | 'loadLatest' }`). It is not an `error`. A page with buttons of its own can call
288
288
  `editor.module.keepMyChanges()` (resolves `true` when nothing is left unsaved) or `editor.module.loadLatestVersion()`
289
- instead of leaving the choice to the card. The "Anna is editing" notice of Widgetic's own site is not part of the module:
290
- it needs a signed-in member of a team, which an editor session is not.
289
+ instead of leaving the choice to the card.
290
+ - **Who else is editing.** A version check tells two people about each other only when the second one saves. Pass
291
+ `presence: true` for a token that signs a person in as themselves (a Shopify store's, the Widgetic site's) and the
292
+ editor tells them earlier: a second person who opens the composition sees a card, "Anna is editing", with *Take over
293
+ editing* (the other person's editor pauses and says so; what they saved stays) and *Look only*. It is presence, never a
294
+ lock: nobody is shut out, no save is refused because of it, a claim that is not renewed runs out by itself after a
295
+ minute, and the version check above still guards every save. Your page hears `presence`
296
+ (`{ phase, holder, editsBlocked }`) when who is editing changes, and holds its own screens that save still while
297
+ `editsBlocked` is `true`, or asks `editor.module.isEditsBlocked()` before it opens one. It is off unless you ask, read
298
+ once when the module mounts. For an editor session, a personal composition or a person who may not change the
299
+ composition, the editor carries on as if it were off, and your page hears nothing.
291
300
  - **Your own files.** Pass `mediaLibrary` (above) and the editor's file pickers show your files instead of the user's
292
301
  Widgetic uploads, or pass [`pickFile`](#your-own-file-picker-for-file-fields-pickfile) to open your own picker.
293
302
  - **Fonts.** `googleFontsApiKey` is a Google Fonts Web Fonts API key for the font picker's list; without one the picker
@@ -608,6 +617,7 @@ files.setLanguage({ locale: '', messages: {} }); // back to Englis
608
617
  | `saved` | `{ composition, savedAt }` | Composition editor: a save went through. |
609
618
  | `conflict` | `{ currentVersion, lastEditedBy, lastEditedAt, correlationId? }` | Composition editor: a save was refused because somebody else saved the composition after the editor loaded it. Nothing is lost: the editor keeps the visitor's edits and asks which version stays. Not an `error`. `lastEditedBy` and `lastEditedAt` are `null` for an editor session. |
610
619
  | `conflictResolved` | `{ resolution }` | Composition editor: the visitor (or your page, with `editor.module.keepMyChanges()` or `editor.module.loadLatestVersion()`) chose: `'keepMine'` (the edits are saved on top of the newer version) or `'loadLatest'` (the edits are gone). |
620
+ | `presence` | `{ phase, holder, editsBlocked }` | Composition editor, with the `presence` option: who is editing the composition changed. `phase` is `'editing'` (this window holds the claim), `'blocked'` (somebody else does, and the editor asks the visitor to take over or to only look), `'readOnly'` (the visitor chose to only look) or `'off'` (presence has stopped). `holder` is `{ id, name, isYou, since }` or `null` (`name` is `null` when the API gave none; `isYou` is `true` for the visitor's own account in another window). `editsBlocked` is `true` in `'blocked'` and `'readOnly'`: hold your own screens that save still. Never said for an editor session or a personal composition, and never an `error`. |
611
621
  | `canvasChanged` | `{ canvasId }` | Widget creator: it opened a canvas or made one. Keep the id and give it back as `canvasId` next time. |
612
622
  | `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. |
613
623
  | `widgetRenamed` | `{ widgetId, name }` | Widget creator: the main widget has this name (said when the canvas opens and each time the user renames it). |
@@ -644,7 +654,8 @@ The types are exported: `FileBrowserEvents`, `CompositionEditorEvents`, `WidgetC
644
654
  `PickedFile` and `LibraryAction` (what `select` and the File Browser's `error` carry); `ModuleErrorEvent` (what every
645
655
  `error` carries), with `FileBrowserErrorEvent`, `CompositionEditorErrorEvent` and `WidgetCreatorErrorEvent` for what each
646
656
  module adds, and `CompositionEditorErrorDuring` and `WidgetCreatorErrorDuring` for the values of `during`;
647
- `CompositionEditorConflictEvent` (what `conflict` carries); and, for code
657
+ `CompositionEditorConflictEvent` (what `conflict` carries); `CompositionEditorPresenceEvent` and
658
+ `CompositionEditorPresenceHolder` (what `presence` carries); and, for code
648
659
  that handles any module, `ModuleEventMap`, `KnownModuleName`, `ModuleEvents`, `ModuleEventHandlers`, `ModuleEventName`
649
660
  and `ModuleEventPayload`.
650
661
 
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.13';
2485
+ const SDK_VERSION = '0.1.14';
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.13';
2481
+ const SDK_VERSION = '0.1.14';
2482
2482
  const SDK_NAME = '@widgetic/ui-sdk';
2483
2483
 
2484
2484
  /**
@@ -134,6 +134,15 @@ export interface MountConfig<Name extends ModuleName = ModuleName> {
134
134
  * the widget's `embedSettings.width` and `embedSettings.height` when it is saved. Default: `false`.
135
135
  */
136
136
  lockPreviewSize?: boolean;
137
+ /**
138
+ * The composition editor and Workflows: when `true`, the editor tells the people of a team who else has the composition
139
+ * (or the workflow) open ("Anna is editing"), with a choice to take over or to only look. The composition editor also
140
+ * tells your page, with the `presence` event (`CompositionEditorEvents`) and `editor.module.isEditsBlocked()`. It is
141
+ * presence, never a lock: nobody is shut out and no save is refused because of it. It is for a token that signs a person
142
+ * in as themselves; an editor session is refused the routes it runs on, and the editor then carries on as if it were
143
+ * off. Read once, when the module is mounted. Default: `false`.
144
+ */
145
+ presence?: boolean;
137
146
  [moduleOption: string]: unknown;
138
147
  }
139
148
  /**
@@ -134,6 +134,15 @@ export interface MountConfig<Name extends ModuleName = ModuleName> {
134
134
  * the widget's `embedSettings.width` and `embedSettings.height` when it is saved. Default: `false`.
135
135
  */
136
136
  lockPreviewSize?: boolean;
137
+ /**
138
+ * The composition editor and Workflows: when `true`, the editor tells the people of a team who else has the composition
139
+ * (or the workflow) open ("Anna is editing"), with a choice to take over or to only look. The composition editor also
140
+ * tells your page, with the `presence` event (`CompositionEditorEvents`) and `editor.module.isEditsBlocked()`. It is
141
+ * presence, never a lock: nobody is shut out and no save is refused because of it. It is for a token that signs a person
142
+ * in as themselves; an editor session is refused the routes it runs on, and the editor then carries on as if it were
143
+ * off. Read once, when the module is mounted. Default: `false`.
144
+ */
145
+ presence?: boolean;
137
146
  [moduleOption: string]: unknown;
138
147
  }
139
148
  /**
@@ -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,MAAM,GAAG,MAAM,GAAG,IAAI,CAAA;CAAE,CAAC;AAE5D;;;;GAIG;AACH,MAAM,MAAM,QAAQ,GAAG,CAAC,OAAO,EAAE,mBAAmB,KAAK,OAAO,CAAC,WA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Aa,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"}
@@ -108,6 +108,35 @@ export interface CompositionEditorConflictEvent {
108
108
  /** Quote it to Widgetic's support: it finds the request in the logs. */
109
109
  correlationId?: string;
110
110
  }
111
+ /** Whoever holds the editing of a composition, as the API names them: a person's name, never an email. */
112
+ export interface CompositionEditorPresenceHolder {
113
+ id: string;
114
+ /** The holder's name, or `null` when the API had none to give (say "Someone"). */
115
+ name: string | null;
116
+ /** The holder is the signed-in person's own account, in another window. */
117
+ isYou: boolean;
118
+ /** When the holder began editing (an ISO date), when the API said; `null` otherwise. */
119
+ since: string | null;
120
+ }
121
+ /**
122
+ * The `presence` event of the composition editor (only with `presence: true`): who is editing the composition. It is
123
+ * presence, never a lock: no save is refused because of it.
124
+ */
125
+ export interface CompositionEditorPresenceEvent {
126
+ /**
127
+ * Where this window stands. `off`: nothing to show (presence is not running, or the API says it does not apply to this
128
+ * composition or this token). `editing`: this window holds the editing. `blocked`: somebody else holds it and the visitor
129
+ * has not chosen yet (the editor shows a card: "Take over editing" or "Look only"). `readOnly`: the visitor chose to look.
130
+ */
131
+ phase: 'off' | 'editing' | 'blocked' | 'readOnly';
132
+ /** Who holds the editing, in `blocked` and `readOnly`; `null` when nobody does or the API did not say. */
133
+ holder: CompositionEditorPresenceHolder | null;
134
+ /**
135
+ * The editor takes no new edit now (`blocked` or `readOnly`). A page with screens of its own that save the composition
136
+ * should hold them still too. What was edited before is saved as usual.
137
+ */
138
+ editsBlocked: boolean;
139
+ }
111
140
  /** What the widget creator was doing when something went wrong. `presets` is the lookup and copy of starting points. */
112
141
  export type WidgetCreatorErrorDuring = 'start' | 'token' | 'session' | 'canvas' | 'presets';
113
142
  /**
@@ -161,6 +190,14 @@ export interface CompositionEditorEvents {
161
190
  conflictResolved: {
162
191
  resolution: 'keepMine' | 'loadLatest';
163
192
  };
193
+ /**
194
+ * Who is editing this composition changed (only with `presence: true`): this window holds the editing, somebody else
195
+ * does and the editor asks the visitor what to do, or the visitor chose to only look. Said when something a person can
196
+ * see changes, never on every renewal, and not at all when presence does not apply (an editor session, a personal
197
+ * composition). While `editsBlocked`, hold your own screens that save the composition still too
198
+ * (`editor.module.isEditsBlocked()` asks the same).
199
+ */
200
+ presence: CompositionEditorPresenceEvent;
164
201
  error: CompositionEditorErrorEvent;
165
202
  }
166
203
  /** The events of the widget creator (`'widget-creator'`): what `on` and `mounted.on` take, and the payload of each. */
@@ -108,6 +108,35 @@ export interface CompositionEditorConflictEvent {
108
108
  /** Quote it to Widgetic's support: it finds the request in the logs. */
109
109
  correlationId?: string;
110
110
  }
111
+ /** Whoever holds the editing of a composition, as the API names them: a person's name, never an email. */
112
+ export interface CompositionEditorPresenceHolder {
113
+ id: string;
114
+ /** The holder's name, or `null` when the API had none to give (say "Someone"). */
115
+ name: string | null;
116
+ /** The holder is the signed-in person's own account, in another window. */
117
+ isYou: boolean;
118
+ /** When the holder began editing (an ISO date), when the API said; `null` otherwise. */
119
+ since: string | null;
120
+ }
121
+ /**
122
+ * The `presence` event of the composition editor (only with `presence: true`): who is editing the composition. It is
123
+ * presence, never a lock: no save is refused because of it.
124
+ */
125
+ export interface CompositionEditorPresenceEvent {
126
+ /**
127
+ * Where this window stands. `off`: nothing to show (presence is not running, or the API says it does not apply to this
128
+ * composition or this token). `editing`: this window holds the editing. `blocked`: somebody else holds it and the visitor
129
+ * has not chosen yet (the editor shows a card: "Take over editing" or "Look only"). `readOnly`: the visitor chose to look.
130
+ */
131
+ phase: 'off' | 'editing' | 'blocked' | 'readOnly';
132
+ /** Who holds the editing, in `blocked` and `readOnly`; `null` when nobody does or the API did not say. */
133
+ holder: CompositionEditorPresenceHolder | null;
134
+ /**
135
+ * The editor takes no new edit now (`blocked` or `readOnly`). A page with screens of its own that save the composition
136
+ * should hold them still too. What was edited before is saved as usual.
137
+ */
138
+ editsBlocked: boolean;
139
+ }
111
140
  /** What the widget creator was doing when something went wrong. `presets` is the lookup and copy of starting points. */
112
141
  export type WidgetCreatorErrorDuring = 'start' | 'token' | 'session' | 'canvas' | 'presets';
113
142
  /**
@@ -161,6 +190,14 @@ export interface CompositionEditorEvents {
161
190
  conflictResolved: {
162
191
  resolution: 'keepMine' | 'loadLatest';
163
192
  };
193
+ /**
194
+ * Who is editing this composition changed (only with `presence: true`): this window holds the editing, somebody else
195
+ * does and the editor asks the visitor what to do, or the visitor chose to only look. Said when something a person can
196
+ * see changes, never on every renewal, and not at all when presence does not apply (an editor session, a personal
197
+ * composition). While `editsBlocked`, hold your own screens that save the composition still too
198
+ * (`editor.module.isEditsBlocked()` asks the same).
199
+ */
200
+ presence: CompositionEditorPresenceEvent;
164
201
  error: CompositionEditorErrorEvent;
165
202
  }
166
203
  /** The events of the widget creator (`'widget-creator'`): what `on` and `mounted.on` take, and the payload of each. */
@@ -1 +1 @@
1
- {"version":3,"file":"module-events.d.ts","sourceRoot":"","sources":["../../../src/sdk/types/module-events.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,uDAAuD;AACvD,MAAM,WAAW,UAAU;IACvB,gGAAgG;IAChG,EAAE,EAAE,MAAM,CAAC;IACX,oCAAoC;IACpC,IAAI,EAAE,MAAM,CAAC;IACb,0CAA0C;IAC1C,GAAG,EAAE,MAAM,CAAC;IACZ,2DAA2D;IAC3D,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,iCAAiC;IACjC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,wDAAwD;I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AAS,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"}
@@ -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.13";
9
+ export declare const SDK_VERSION = "0.1.14";
10
10
  export declare const SDK_NAME = "@widgetic/ui-sdk";
@@ -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.13";
9
+ export declare const SDK_VERSION = "0.1.14";
10
10
  export declare const SDK_NAME = "@widgetic/ui-sdk";
11
11
  //# sourceMappingURL=version.d.ts.map
@@ -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.13",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.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})});
2
2
  //# sourceMappingURL=ui-sdk.js.map
package/modules/README.md CHANGED
@@ -199,6 +199,7 @@ Without the SDK it is the same class as the File Browser's (`new CompositionEdit
199
199
  | `googleFontsApiKey` | A Google Fonts Web Fonts API key for the font picker's list. Without one the picker lists a short set of popular families. |
200
200
  | `autosaveDelayMs` | Save this many milliseconds after the last change. Default 2500; `0` saves only when you call `save()`. |
201
201
  | `lockPreviewSize` | When `true`, resizing the preview changes how it looks in the editor but does not update `embedSettings.width` and `embedSettings.height` on save (you control embed size elsewhere). Default: `false`. |
202
+ | `presence` | `true` tells the people of a team who else has the composition open: "Anna is editing", with a choice to take over or to only look (default `false`, read once when the module mounts; see "Who else is editing"). It is for a token that signs a person in as themselves (a Shopify store's, the Widgetic site's); for an editor session minted for one of your customers, the API refuses the routes it runs on and the editor 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 composition changed by somebody else asks the visitor what to do (see "When somebody else saved first") whether `presence` is on or not. A value that is not `true` or `false` is ignored, with one warning in the console. |
202
203
  | `theme` | As for every module: a mode, or a look of your own (see "Looking like your product"). |
203
204
  | `locale` | A BCP 47 language tag (`de`, `pt-BR`): plural rules and how numbers and dates are written (including month and weekday names in calendars). When a translation pack exists for the tag, the module loads it as a lazy file; otherwise words stay English while formatting and direction still follow `locale`. See "Speaking your visitors' language". |
204
205
  | `messages` | The editor's words in your language, `{ 'editor.props.save': 'Speichern', ... }`: **one** object for the whole editor, the file picker and the rich text editor. A key you leave out stays English. See "Speaking your visitors' language". |
@@ -207,7 +208,8 @@ Without the SDK it is the same class as the File Browser's (`new CompositionEdit
207
208
  Events: `ready` `{ name, widgetId }` (the composition has loaded and is on screen), `dirty` `{ dirty }` (there is, or is
208
209
  no longer, work that is not saved), `saved` `{ composition, savedAt }` (a save went through), `conflict`
209
210
  `{ currentVersion, lastEditedBy, lastEditedAt, correlationId? }` and `conflictResolved` `{ resolution }` (see "When somebody
210
- else saved first" below), and `error`
211
+ else saved first" below), `presence` `{ phase, holder, editsBlocked }` (with the `presence` option: who is editing changed;
212
+ see "Who else is editing" below), and `error`
211
213
  `{ message, code?, fatal, during?, status?, retryable?, sessionEnded?, correlationId? }`. The editor shows a problem to the
212
214
  visitor itself (with "Try again" where that helps); `error` is for your page. `fatal: true` means the editor cannot go on
213
215
  by itself: the composition cannot be opened, or the session is over (`sessionEnded`), so give it a new session or take it
@@ -222,10 +224,34 @@ a deliberate overwrite; when somebody saved a third time meanwhile it asks again
222
224
  *Use the latest version* (the composition is read again and the edits are dropped). Your page hears `conflict` when the
223
225
  save is refused and `conflictResolved` (`{ resolution: 'keepMine' | 'loadLatest' }`) once somebody chose. It is not an
224
226
  `error`, so `error` is not sent for it. A page that wants its own buttons calls `keepMyChanges()` or `loadLatestVersion()`
225
- on the module. The API names who saved only to a member of a team (it never tells an editor session), so `lastEditedBy`
226
- and `lastEditedAt` are `null` here; `currentVersion` is the version the API holds now, when the refusal said so. The
227
- editor's *presence* notice ("Anna is editing", take over, read only) is not offered by the module: it runs on routes an
228
- editor session may not call, and the module keeps the `presence` option of the editor off.
227
+ on the module. The API names who saved only to a member of a team (it never tells an editor session), so for an editor
228
+ session `lastEditedBy` and `lastEditedAt` are `null`; for a person signed in as themselves they say who saved last (a name,
229
+ never an email) and when. `currentVersion` is the version the API holds now, when the refusal said so. Telling two people
230
+ about each other *before* either saves is the `presence` option's job (next).
231
+
232
+ **Who else is editing.** A version check tells two people about each other only when the second one saves. With
233
+ `presence: true` the editor tells them earlier: while a person has the composition open the editor keeps a claim with the
234
+ API (renewed about every 20 seconds while the window is on screen, given back when the editor closes or the page goes, and
235
+ it runs out by itself a minute after the last renewal), and a second person who opens the composition sees a card, "Anna is
236
+ editing", with two choices: *Take over editing* (the other person's editor pauses and says so; what they saved stays) and
237
+ *Look only* (this window stays read-only, with a note that says who is editing, or that nobody is any more, and a button to
238
+ start). The same person in two windows is two editors, and the second window says "You are editing this composition in
239
+ another window". It is presence, never a lock: nobody is shut out (taking over is always one click away), no save is
240
+ refused because of it, and the version check above still guards every save. The API names the person only to a member of a
241
+ team, and never by email; without a name the card says "Someone".
242
+
243
+ Your page hears `presence` `{ phase, holder, editsBlocked }` when something a person can see changes (never on every
244
+ renewal): `phase` is `'editing'` (this window holds the claim), `'blocked'` (somebody else does and the card asks),
245
+ `'readOnly'` (the visitor chose to only look) or `'off'` (presence was on and has stopped, so a page that held its screens
246
+ still can let them save again); `holder` is `{ id, name, isYou, since }` or `null` (`name` is `null` when the API gave
247
+ none, `isYou` is `true` for the visitor's own account in another window, `since` is when the holder began, an ISO date, when
248
+ the API said); `editsBlocked` is `true` in `'blocked'` and `'readOnly'`. A page that has screens of its own which save the
249
+ composition holds them still while `editsBlocked` is `true`, or asks `editor.module.isEditsBlocked()` before it opens one;
250
+ what was edited before is saved as usual. Every doubt means "edit freely": for an editor session, a personal composition, a
251
+ person who may not change it, an API that cannot be reached or an answer the editor cannot read, the editor carries on as
252
+ if the option were off (it asks again later when the network was the cause, never when the API refused for good), and your
253
+ page hears nothing. The words follow the page's language like the rest of the editor's (see "Speaking your visitors'
254
+ language").
229
255
 
230
256
  Methods (on `editor.module` when you mounted it with the SDK): `save()` saves what is unsaved now, `flush()` saves
231
257
  everything and waits, both resolving `true` when nothing is left unsaved; `isDirty()`; `reload()` loads the composition
@@ -233,7 +259,9 @@ again (unsaved edits are lost); `adoptEmbedSettings(settings)` for a page that s
233
259
  (call it after `await flush()`, with the settings the API now holds, so a later save of the editor does not put the old ones
234
260
  back; nothing becomes unsaved); `adoptName(name)` for a page that renames the composition itself (same use); `keepMyChanges()`
235
261
  (resolves `true` when nothing is left unsaved) and `loadLatestVersion()`, the two answers to a `conflict` for a page with buttons of its own (both do nothing, and
236
- `keepMyChanges()` resolves `false`, when there is no conflict); `setTheme(theme)` (see "Looking like your product"); `setLanguage({ locale?, messages? })`, and
262
+ `keepMyChanges()` resolves `false`, when there is no conflict); `isEditsBlocked()` (`true` while the editor takes no new edit
263
+ because somebody else is editing, the same as `editsBlocked` of the last `presence`; always `false` without the `presence`
264
+ option, before the editor is on screen and after it is gone); `setTheme(theme)` (see "Looking like your product"); `setLanguage({ locale?, messages? })`, and
237
265
  `CompositionEditorModule.defaultMessages` and `checkMessages(messages)`, which are also on the instance (see "Speaking your
238
266
  visitors' language").
239
267
 
@@ -813,10 +841,9 @@ and it splits what you give between them, so you never need to know which part s
813
841
  - the rich text editor of its text fields, the `shadEditor.` keys. The editor draws its own text toolbar (`editor.` keys),
814
842
  so these words are not on screen today, and a translation can leave them out.
815
843
 
816
- Among the `editor.` keys, the nineteen `editor.presence.` ones ("Anna is editing", take over, look only) are on no screen
817
- either: the module keeps the editor's `presence` off, because it runs on routes an editor session may not use. The language
818
- packs leave them out (`npm run locales:coverage` counts them as missing for that reason); the nine `editor.conflict.` ones,
819
- which the card of a refused save shows, are translated.
844
+ Among the `editor.` keys, the nineteen `editor.presence.` ones ("Anna is editing", take over, look only) are on screen only
845
+ with the `presence` option, and the nine `editor.conflict.` ones only when a save is refused because somebody else saved
846
+ first; the language packs carry both, so a page that sets `locale` has them translated either way.
820
847
 
821
848
  `CompositionEditorModule.defaultMessages` lists all of them, with their English text: more than 500. A key that is in none
822
849
  of the three parts is said once in the console as `[Editor] ...`, with the nearest real key, and ignored.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@widgetic/ui-sdk",
3
- "version": "0.1.13",
3
+ "version": "0.1.14",
4
4
  "description": "Framework-agnostic UI components for building Widgetic integrations",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "main": "dist/index.cjs",