@widgetic/ui-sdk 0.1.15 → 0.1.17

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`, `allowSelecting` (`false` for a library page: no ticking, no confirm button), `allowResumableUploads`. Composition editor: `compositionId`, `mediaLibrary`, `pickFile`, `lockPreviewSize`, `googleFontsApiKey`, `autosaveDelayMs`, `presence`, `messages`. Widget creator: `canvasId`, `widgetId`, `startWithNewWidget`, `presets`, `startFromPreset`, `presetLabels`, `messages`, `mediaLibrary`, `pickFile`, `widgetBuilderUrl`, and for a page that draws its own header around it `toolbarPosition`, `showSaveButton`, `limitNotices`, `initialMessage` (see [The widget creator](#the-widget-creator)). Workflows: `workspaceId` (required), `workflowId`, `presence`, `messages`. The types of your library, your picker and the files they handle are exported (see [Your own files, typed](#your-own-files-typed)). |
111
+ | *anything else* | | Handed to the module. Every module: `themeFromHost` (see [Looking like your product](#looking-like-your-product)). File Browser: `maxSelections`, `initialFilter`, `selectLabel`, `messages`, `mediaLibrary`, `allowSelecting` (`false` for a library page: no ticking, no confirm button), `allowResumableUploads`. Composition editor: `compositionId`, `mediaLibrary`, `pickFile`, `lockPreviewSize`, `googleFontsApiKey`, `autosaveDelayMs`, `presence`, `messages`. Widget creator: `canvasId`, `widgetId`, `startWithNewWidget`, `presets`, `startFromPreset`, `presetLabels`, `messages`, `mediaLibrary`, `pickFile`, `widgetBuilderUrl`, `mascot`, `showCanvasFileBrowser` (a "Files" entry on the canvas that opens your `mediaLibrary`), and for a page that draws its own header around it `toolbarPosition`, `showSaveButton`, `showZoomControls`, `limitNotices`, `initialMessage` (see [The widget creator](#the-widget-creator)). Workflows: `workspaceId` (required), `workflowId`, `presence`, `messages`. The types of your library, your picker and the files they handle are exported (see [Your own files, typed](#your-own-files-typed)). |
112
112
 
113
113
  The handle:
114
114
 
@@ -360,11 +360,25 @@ await creator.unmount();
360
360
  `toolbarPosition: 'BL' | 'BC' | 'BR'` puts the drawing toolbar bottom left, bottom centre (the default) or bottom right,
361
361
  for a page that has something of its own over the middle of the bottom edge; `showSaveButton: false` takes away the
362
362
  canvas's Save button and its dot (the creator saves by itself, five seconds after the last change, at the latest fifteen
363
- seconds into continuous work, and when the page is hidden or closed); `limitNotices: 'chat'` tells a refusal because of a
363
+ seconds into continuous work, and when the page is hidden or closed); `showZoomControls: false` takes away the canvas's
364
+ zoom buttons (the wheel, a pinch and the keyboard still zoom); `limitNotices: 'chat'` tells a refusal because of a
364
365
  limit in the chat only, not also in a toast; `initialMessage: { text, send: true, attachments? }` puts words in the chat
365
366
  of a new widget, with the photos you give it as `File`s, and sends them as the first message. A creator older than these ignores the options, and `publish()` and
366
367
  `setWidgetName()` reject while `flush()` resolves at once. Details: `modules/README.md`, "A header of your own around
367
368
  the creator".
369
+ - **Your files on the canvas.** `showCanvasFileBrowser: true` adds a "Files" entry to the canvas's Shapes menu (right before
370
+ "Image") that opens the File Browser in the state of choosing, so the user puts the pictures and SVG files they already
371
+ have on the sketch: it lists pictures and vector files only, and takes several at once. It lists YOUR `mediaLibrary` (the
372
+ one the chat and canvas uploads use; pass one whose `list` is implemented) and the user's own Widgetic uploads when you did
373
+ not pass one; with `pickFile` your own picker opens instead (asked for `image/*`, `image/svg+xml` and `.svg`, `multiple: true`). Default
374
+ `false`. Pictures on the sketch that are not in your library yet (a photo the user dropped, a drawing) are saved to it, in
375
+ the background, through your `mediaLibrary.upload` (`purpose: 'canvas'`) when the user sends their first message and when
376
+ the sketch is turned into the widget; taking a picture off the sketch never deletes the file from the library. The
377
+ assistant that sketches for the user can place SVG icons and pictures from that library. Details: `modules/README.md`,
378
+ option table of the widget creator.
379
+ - **The assistant's look.** The chat draws its assistant as Widgetic's animated mascot, a scribble that thinks, writes and
380
+ ends in its success or error look, with small sounds. `mascot: false` draws it as a plain round avatar and keeps the
381
+ chat silent; nothing else about the chat changes. Details: the option table of the widget creator in `modules/README.md`.
368
382
  - **Credits and limits are yours.** The AI is paid for by your account, as your own calls are. When your credits run out
369
383
  (or a plan limit or the storage limit is reached), the creator tells the user in plain words ("This is not available
370
384
  right now. Please try again later.") and keeps working; it never shows what your account holds. Your page hears
@@ -405,7 +419,7 @@ customers.
405
419
  ```js
406
420
  const workflows = await mountModule('workflows', {
407
421
  container: '#workflows', // give it a height: it fills its container, and scrolls inside it when that is short
408
- workspaceId: 'personal', // or the id of an organization
422
+ workspaceId: workspaceIdOfYourTeam, // the id of the workspace whose workflows are shown (with an editor session: your partner workspace)
409
423
  getToken: async ({ reason }) => (await fetch(`/my-server/widgetic-token?reason=${reason}`)).text(),
410
424
  workflowId: workflowOfTheAddress(), // optional: the workflow to open first; leave it out for the list
411
425
  on: {
@@ -433,9 +447,10 @@ await workflows.unmount();
433
447
  handed to every module alike). It is called once before the screen appears (a `getToken` that fails fails the mount) and
434
448
  again when the token runs out. See [Tokens](#tokens).
435
449
  - **For your customers.** Mint the session with `surfaces: ['workflows']` (step 1 above; the other surfaces are not needed)
436
- and mount with `workspaceId: 'personal'`: a session may call only the workflow routes of that workspace, and any other
437
- value is refused (`EDITOR_SESSION_ROUTE_NOT_ALLOWED`), which the screen shows with a "Try again" button instead of an
438
- empty list. The customer sees and edits **their own workflows only** (another customer's workflow answers "not found",
450
+ and mount with `workspaceId` set to the id of your partner workspace (the `workspaceId` that every editor session answers
451
+ with): a session may call only the workflow routes of that workspace, and any other is refused (the id of another workspace
452
+ with `404 RESOURCE_WORKSPACE_NOT_FOUND`, a word that is not an id, `personal` for one, with `403
453
+ EDITOR_SESSION_ROUTE_NOT_ALLOWED`), which the screen shows with a "Try again" button instead of an empty list. The customer sees and edits **their own workflows only** (another customer's workflow answers "not found",
439
454
  the same as one that does not exist), picks only among **their own compositions**, and can hold up to 50 workflows. Your
440
455
  account owns, bills and serves what they make, so it runs under your plan and your standing; names of the people who
441
456
  published are not shown to a customer, and your own staff, signed in as the partner, see every customer's workflows in the
@@ -444,7 +459,7 @@ await workflows.unmount();
444
459
  and offers *Keep my changes as a copy* (a new workflow that holds what the person did) before *Load the latest
445
460
  version*. Pass `presence: true` for an organization's workspace and the screen also tells who has the workflow open
446
461
  ("Anna is editing"), with a choice to take over or to only look. It is presence, never a lock, it is off unless you ask,
447
- and for `personal`, or a token the API refuses the edit-lease routes, the screen carries on as if it were off.
462
+ and for a workspace with no presence, or a token the API refuses the edit-lease routes, the screen carries on as if it were off.
448
463
  - **Opening and closing a workflow** belong to your page: the screen tells it (`openWorkflow`, with `workflowId: null` for
449
464
  the list) so it can keep its address in step, and `workflows.module.setWorkflow(id)` moves the screen when your page
450
465
  moves. The embed code is shown by your page too: the screen has its button only when something listens for
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.15';
2485
+ const SDK_VERSION = '0.1.17';
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.15';
2481
+ const SDK_VERSION = '0.1.17';
2482
2482
  const SDK_NAME = '@widgetic/ui-sdk';
2483
2483
 
2484
2484
  /**
@@ -121,12 +121,14 @@ export interface MountConfig<Name extends ModuleName = ModuleName> {
121
121
  /**
122
122
  * The File Browser, the composition editor and the widget creator: your own media library, so that their pickers
123
123
  * show your files and not the user's Widgetic uploads. Only `list` is required; `urlResolver` turns a listed
124
- * address into the one that is saved.
124
+ * address into the one that is saved. The widget creator also lists it in the canvas's "Files" entry when you turn
125
+ * on `showCanvasFileBrowser: true` (an option of the widget creator), limited to pictures and SVG files.
125
126
  */
126
127
  mediaLibrary?: PartnerMediaLibrary;
127
128
  /**
128
129
  * The composition editor and the widget creator: your own picker for file fields, instead of the File Browser.
129
- * Resolve the files chosen, or `[]` when the visitor cancelled.
130
+ * Resolve the files chosen, or `[]` when the visitor cancelled. The widget creator also calls it for the canvas's
131
+ * "Files" entry (`showCanvasFileBrowser: true`), asking for pictures and SVG files, several at once.
130
132
  */
131
133
  pickFile?: PickFileFn;
132
134
  /**
@@ -121,12 +121,14 @@ export interface MountConfig<Name extends ModuleName = ModuleName> {
121
121
  /**
122
122
  * The File Browser, the composition editor and the widget creator: your own media library, so that their pickers
123
123
  * show your files and not the user's Widgetic uploads. Only `list` is required; `urlResolver` turns a listed
124
- * address into the one that is saved.
124
+ * address into the one that is saved. The widget creator also lists it in the canvas's "Files" entry when you turn
125
+ * on `showCanvasFileBrowser: true` (an option of the widget creator), limited to pictures and SVG files.
125
126
  */
126
127
  mediaLibrary?: PartnerMediaLibrary;
127
128
  /**
128
129
  * The composition editor and the widget creator: your own picker for file fields, instead of the File Browser.
129
- * Resolve the files chosen, or `[]` when the visitor cancelled.
130
+ * Resolve the files chosen, or `[]` when the visitor cancelled. The widget creator also calls it for the canvas's
131
+ * "Files" entry (`showCanvasFileBrowser: true`), asking for pictures and SVG files, several at once.
130
132
  */
131
133
  pickFile?: PickFileFn;
132
134
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"component.d.ts","sourceRoot":"","sources":["../../../src/sdk/types/component.ts"],"names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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.15";
9
+ export declare const SDK_VERSION = "0.1.17";
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.15";
9
+ export declare const SDK_VERSION = "0.1.17";
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.15",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.17",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
@@ -329,12 +329,16 @@ mount()`, `await unmount()`), imported from `https://cdn.widgetic.com/modules/wi
329
329
  | `presetLabels` | The words of the picker, for a tone of your own: `{ heading, intro, startFromScratch, startFromScratchHint, copying, copyFailed, presetGone, checking }`. A shortcut for the eight `presetPicker.` messages (see "Speaking your visitors' language"): a word that `messages` also says is `messages`'s. Any word neither says stays English. |
330
330
  | `toolbarPosition` | Where the drawing toolbar (and the element selector) stands along the bottom edge of the canvas: `'BL'` bottom left, `'BC'` bottom centre (the default) or `'BR'` bottom right. For a page that puts something of its own over the middle of the bottom edge (an assistant, a chat bubble). Anything else throws a `TypeError` that names the option. See "A header of your own around the creator". |
331
331
  | `showSaveButton` | `false` takes away the canvas's Save button and the dot that says the board has changes the server does not have. Default `true`. The creator saves by itself either way (five seconds after the last change, at the latest fifteen seconds into continuous work, and when the page is hidden or closed). A value that is not `true` or `false` is ignored, with one warning in the console. |
332
+ | `showZoomControls` | `false` takes away the canvas's zoom buttons (zoom out, the zoom level that puts the board back to 100%, zoom in, fit to view). Default `true`. The board still zooms with the wheel, a pinch and the keyboard: only the buttons are gone. For a page that has no room for them, or that lets people move around the board some other way. A value that is not `true` or `false` is ignored, with one warning in the console. A creator that does not have the option yet (older than the release that added it) ignores it. |
333
+ | `showCanvasFileBrowser` | `true` adds a "Files" entry to the canvas's Shapes menu (the "More shapes" button), right before "Image". It opens the File Browser in the state of choosing, over YOUR `mediaLibrary` (or the user's Widgetic uploads when you gave none), and the files the user ticks go on the sketch. Only pictures and SVG files are listed, found by the search and taken by an upload there; the user can tick several. A page that gave `pickFile` is asked for them instead (`accept: ['image/*', 'image/svg+xml', '.svg']`, `multiple: true`, as for the files of a widget's fields). Default `false`. A value that is not `true` or `false` is ignored, with one warning in the console. A creator that does not have the option yet (older than the release that added it) ignores it. See "Your files on the canvas". |
334
+ | `showSketchBar` | `false` takes away the creator's own bar above the board (title, Live, Publish). Default `true`. For a page that already draws that chrome around the creator. Publish still runs through `publish()` and `publishStateChanged`. A value that is not `true` or `false` is ignored, with one warning in the console. |
332
335
  | `limitNotices` | `'all'` (the default) or `'chat'`. When a limit refuses the user (credits used up), `'all'` tells them in a toast and in the chat; `'chat'` in the chat alone, for a page that draws its own notice (see `limitReached`). Other failures keep their toast. Anything else throws a `TypeError` that names the option. |
336
+ | `mascot` | `false` draws the chat's assistant as a plain round avatar instead of Widgetic's animated mascot (a scribble that thinks, writes and ends in its success or error look), and keeps the chat silent: the mascot's small sounds go with it. Default `true`. Nothing else about the chat changes. A value that is not `true` or `false` is ignored, with one warning in the console. A creator that has no mascot yet ignores it. |
333
337
  | `initialMessage` | Words for the chat of a new widget, and the pictures that go with them: `{ text: 'Replicate this design: https://…', send: true }`, or `{ text: 'Replicate this photo', send: true, attachments: [file] }`. `text` is words, not empty, at most 4000 characters. `attachments` is a list of at most 5 `File`s of your page's own (a photo the user chose on your page, not a link: the builder looks at a picture that is attached, not at an address in the text), each a PNG, JPEG, WebP or GIF of at most 10 MB. With `send: true` the creator sends it as the first message when the chat is ready, exactly as if the user had typed it, attached the pictures and pressed Enter; without `send` the words and the pictures wait in the chat's input. Used once, for a new widget (`startWithNewWidget: true`); a widget that already has a draft keeps its own. A wrong shape throws a `TypeError` that names the option (and the picture, by its place in the list). |
334
338
  | `locale`, `messages` | The creator's language: the plural rules, numbers and dates, and the words as ONE flat object of message keys and texts for the whole creator (its own words, the chat's, the canvas's, the picker's). See "Speaking your visitors' language"; `setLanguage({ locale?, messages? })` changes them while it is on screen. |
335
339
  | `mediaLibrary` | Your own media library for the settings panel file pickers (see "Showing your own media library"). When `upload` is given, chat attachments and canvas/prompt images use it too (`purpose`: `chat`, `canvas`, or `field` for pickers), with Widgetic upload as fallback. |
336
340
  | `pickFile` | Your own file picker for file fields (see "Partner file picker (`pickFile`)"). Without it the built-in File Browser is used. |
337
- | `widgetBuilderUrl` | The origin the live previews of widgets are served from. Default: Widgetic's. |
341
+ | `widgetBuilderUrl` | The origin the live previews of widgets are served from. Default: Widgetic's. An empty text (`''`) says that your page has no widget builder to name: no preview is loaded from one and no address is guessed in its place (creator 0.4.60 and later). |
338
342
  | `theme` | As for every module: a mode, or a look of your own (see "Looking like your product"). |
339
343
  | `themeFromHost` | As for every module (see "Looking like your product"). |
340
344
  | `apiUrl` | As for the File Browser. |
@@ -383,8 +387,11 @@ nameField.onchange = () => creator.setWidgetName(nameField.value); // the widget
383
387
 
384
388
  - **`publishStateChanged`** `{ widgetId, canPublish, publishing, label, unpublished }`: `widgetId` is the widget `publish()`
385
389
  would publish (the one the user is on, the main widget of the canvas while no other is open; `null` while there is none);
386
- `canPublish` is `true` when it has something to publish and nothing is running; `publishing` is `true` while a publish
387
- of it runs; `label` is the creator's own button's words ("Publish" or "Publish changes", in your page's language);
390
+ `canPublish` is `true` when nothing is running and the creator's own Publish button can be pressed. That includes a widget
391
+ the creator has made nothing for yet: the creator's button then nudges the chat's Send button and publishes nothing, and
392
+ `publish()` does the same (it resolves, and says neither `widgetPublished` nor `error`), so take the user away on
393
+ `widgetPublished` and not when `publish()` resolves. (Modules 0.2.23 and earlier said `false` for such a widget.) `publishing`
394
+ is `true` while a publish of it runs; `label` is the creator's own button's words ("Publish" or "Publish changes", in your page's language);
388
395
  `unpublished` is `true` when the widget has changes no published version has. It is said when the creator first knows,
389
396
  then at every change and never twice with the same state. `getPublishState()` gives the last one (a copy, `null` before the
390
397
  creator said any) to a page that draws its button after the creator reported.
@@ -394,17 +401,44 @@ nameField.onchange = () => creator.setWidgetName(nameField.value); // the widget
394
401
  publish, or with the creator's own reason when it cannot publish now; the creator shows that reason to the user as it
395
402
  does when its own button is pressed.
396
403
  - **`flush()`** puts what the user changed in the canvas on the server now and resolves when that is done. Wait for it
397
- before your page takes the user away from the creator. It never rejects: with nothing on screen nothing is unsaved, and
398
- a save that fails is the creator's to say (the problem is written to the console, once).
404
+ before your page takes the user away from the creator. In the first three seconds after the creator has opened a canvas
405
+ it keeps a change back (opening a canvas redraws its shapes, and a redraw looks like a change), so a `flush()` called then
406
+ waits for those seconds to be over: up to three seconds, never more than six. Called later it is quick, and with nothing
407
+ waiting it resolves at once. (Modules 0.2.15 and 0.2.16 could resolve in that first moment, before the save was sent.) It
408
+ never rejects: with nothing on screen nothing is unsaved, and a save that fails is the creator's to say (the problem is
409
+ written to the console, once).
399
410
  - **`setWidgetName(name, widgetId?)`** renames the widget the page names, or the one the user is on without a `widgetId`.
400
411
  The creator shows the new name at once and saves it, and says `widgetRenamed` (your page sees its own change come back, so
401
412
  ignore an old name while your own rename is on its way). It rejects, and renames nothing, for a name that is not text or
402
413
  is empty, when the creator is not on screen, or when the creator is one that cannot be renamed from the page.
403
- - **`showSaveButton: false`** removes the canvas's Save button and the dot next to it; **`toolbarPosition`** moves the
414
+ - **`showSaveButton: false`** removes the canvas's Save button and the dot next to it; **`showZoomControls: false`** removes
415
+ the canvas's zoom buttons (the wheel, a pinch and the keyboard still zoom); **`showSketchBar: false`** removes
416
+ the creator's own title/Live/Publish bar when the page already draws one; **`toolbarPosition`** moves the
404
417
  drawing toolbar out of the way of something of your own along the bottom edge; **`limitNotices: 'chat'`** keeps the
405
418
  refusal because of a limit to the line in the chat; **`initialMessage`** starts a new widget with words in the chat
406
419
  (a link and an instruction, say, or a photo the user chose on your page, as `attachments`) and, with `send: true`, sends
407
420
  them for the user, which makes the widget and starts the build.
421
+ - **Your files on the canvas (`showCanvasFileBrowser: true`).** The canvas's Shapes menu (the "More shapes" button) gets a
422
+ **Files** entry right before **Image**. It opens the File Browser in a dialog, in the state of choosing, and the pictures and
423
+ SVG files the user ticks are put on the sketch (several at once). Off by default: a page that wants it passes `true`.
424
+ - *Which files it shows.* Your `mediaLibrary` when you gave one: the flat list your `list` returns (the browser keeps the
425
+ pictures and the SVG files itself, so `list` does not have to filter; the search, the type filter and an upload there
426
+ are limited to the same kinds). The user's own Widgetic uploads, of the workspace they are in, when you gave none. A
427
+ `pickFile` of yours takes the place of the browser and is called with `{ accept: ['image/*', 'image/svg+xml', '.svg'],
428
+ multiple: true, signal }`; return the files as your library describes them (`{ id, name, url, mimeType }`), or an empty
429
+ list when the user closed your picker.
430
+ - *What the board does with your library.* It only ever adds from it: taking a picture off the sketch never deletes the file
431
+ from the library. A picture the sketch has that the library lacks (a photo the user dropped on the board, a drawing) is
432
+ saved to the library in the background, once per picture, through `mediaLibrary.upload({ file, purpose: 'canvas' })`: when
433
+ the user sends the first message and when the sketch is turned into the widget; a library with no `upload` is read and
434
+ left as it is. The builder is told the board's library files by name and address, so it uses those very files in the
435
+ widget it makes.
436
+ - *What the assistant that sketches may use.* When the user asks it to sketch, it is told the first page of your library
437
+ (the creator calls `list({ limit: 60, signal })` and keeps the answer for a minute, so list the newest, or the most useful,
438
+ files first) and may place its pictures and SVG icons on the sketch. It places only files of that list: it never invents
439
+ an address.
440
+ - *A creator older than the option* ignores it (there is no entry), and so does a module older than the option (it never
441
+ passes it on): release the creator, then the modules.
408
442
  - **A creator older than these.** A module that is newer than the creator it carries ignores the options the creator does not
409
443
  know, `publish()` and `setWidgetName()` reject with a message that says so, and `flush()` resolves at once with one
410
444
  warning in the console. A page that wants to know checks `typeof creator.publish === 'function'` on the module it
@@ -519,7 +553,7 @@ import { mountModule } from '@widgetic/ui-sdk';
519
553
 
520
554
  const workflows = await mountModule('workflows', {
521
555
  container: '#workflows', // give it a height: it fills its container, and scrolls inside it when that is short
522
- workspaceId: 'personal', // or the id of an organization
556
+ workspaceId: workspaceIdOfYourTeam, // the id of the workspace whose workflows are shown (with an editor session: your partner workspace)
523
557
  getToken: async ({ reason }) => (await fetch(`/my-server/widgetic-token?reason=${reason}`)).text(),
524
558
  workflowId: workflowOfTheAddress(), // optional: the workflow to open first; leave it out for the list
525
559
  theme: 'light',
@@ -538,7 +572,7 @@ window.addEventListener('popstate', () => workflows.module.setWorkflow(workflowO
538
572
  | Option | What it does |
539
573
  | --- | --- |
540
574
  | `container` | The element the screen fills (it needs a height). |
541
- | `workspaceId` | **Required.** `personal`, or the id of the organization whose workflows are shown and edited. With an editor session (below) it is `personal`: a session may call only `/workspaces/personal/workflows…`. |
575
+ | `workspaceId` | **Required.** The id of the workspace (the organization, in the API) whose workflows are shown and edited. With an editor session (below) it is the id of your partner workspace, the `workspaceId` the session answers with: a session may call only `/workspaces/{workspaceId}/workflows…` of that workspace. |
542
576
  | `getToken` | **Required**, and the same as for the other modules: `getToken({ reason })` resolves with a token the API accepts for the workspace's workflows, bare or as `{ token, expiresAt }`. Two kinds work: the token of a **signed-in person who may work in that workspace** (a member of the team, or the partner's own account), the way the Widgetic site calls the API, or an **editor session** your server minted for one of your customers with `surfaces: ['workflows']` ("Showing it to your customers"). It is called once before the screen appears (a `getToken` that fails fails the mount), and again when the token is about to run out or the API refuses it (`reason: 'expired'`, once per refusal). |
543
577
  | `apiUrl` | The API origin (`https://api.widgetic.com` unless you run your own). |
544
578
  | `workflowId` | The workflow to open first. Leave it out for the list. After mounting the screen moves by itself (and says so with `openWorkflow`); `setWorkflow` moves it from the page. |
@@ -548,9 +582,11 @@ window.addEventListener('popstate', () => workflows.module.setWorkflow(workflowO
548
582
 
549
583
  **Showing it to your customers.** A partner that has a Widgetic account for each of its customers (managed users) mounts the
550
584
  screen with an *editor session*: its server mints one for the customer exactly as for the other modules (`POST
551
- /v1/managed-users/{id}/editor-sessions`) with `surfaces: ['workflows']`, and `getToken` returns it. Pass `workspaceId:
552
- 'personal'`. A session may call only the workflow routes of that workspace, so any other value is refused with
553
- `EDITOR_SESSION_ROUTE_NOT_ALLOWED` and the screen **shows** the refusal with a "Try again" button instead of an empty list.
585
+ /v1/managed-users/{id}/editor-sessions`) with `surfaces: ['workflows']`, and `getToken` returns it. Pass `workspaceId`
586
+ as the id of your partner workspace (the `workspaceId` that every editor session answers with). A session may call only the
587
+ workflow routes of that workspace, so any other is refused (the id of another workspace with `404
588
+ RESOURCE_WORKSPACE_NOT_FOUND`, a word that is not an id, `personal` for one, with `403 EDITOR_SESSION_ROUTE_NOT_ALLOWED`) and
589
+ the screen **shows** the refusal with a "Try again" button instead of an empty list.
554
590
  The customer sees and edits **their own workflows only**: another customer's workflow answers "not found", the same as one
555
591
  that does not exist. A block that runs a composition offers **their own compositions** and nobody else's, and a workflow
556
592
  cannot name a foreign one. Each customer can hold up to 50 workflows (archived ones count; a 51st is refused with a message
@@ -1045,6 +1081,7 @@ itself, which no `messages` could ever translate. The same trick works on your o
1045
1081
  | `npm test` | Unit tests (vitest): token source, session token provider, emitter, picked files, shadow mount, the composition editor, widget creator and Workflows modules, the creator's route list, CSS transforms, fonts, the publishing rules, the R2 store, the release plan and the two scripts of the release pipeline |
1046
1082
  | `npm run harness` | Serves `harness/hostile.html`, `harness/composition-editor.html`, `harness/widget-creator.html`, `harness/workflows.html` and a mock Widgetic API on http://localhost:5290 |
1047
1083
  | `npm run test:e2e` | Playwright against the harness (`PLAYWRIGHT_CHANNEL=chrome` uses the installed Google Chrome instead of Playwright's download) |
1084
+ | `npm run e2e:compare -- <log of the new build> <log of the live files>` | Sets two runs of the browser tests against each other, test by test (see "Comparing two runs of the browser tests", below). Exit code 1 when a test is green on the live files and is red, or was not run, on the new build; 2 when a log cannot be compared |
1048
1085
  | `npm run check:creator-routes` | Reads the packages the creator is made of and checks that every route they can call is on the gateway's list for a creator session, or is listed with the reason a visitor can never reach it (`-- --inventory` prints it as JSON, see "What the end-to-end tests check") |
1049
1086
  | `npm run publish:cdn -- <module> [options]` | Releases a module to the CDN: see "Publishing". `--help` lists every option |
1050
1087
  | `npm run release:check -- --tag modules-v<x.y.z>` | The checks a release starts with (the tag against `package.json`, a lockfile the pipeline can install), on your machine: no keys, nothing written, no package needed |
@@ -1055,6 +1092,28 @@ itself, which no `messages` could ever translate. The same trick works on your o
1055
1092
  Run `npm run build` (or the `build:<module>` of the one you test) before `npm run harness` / `npm run test:e2e`: the
1056
1093
  harness serves `dist/`.
1057
1094
 
1095
+ ### Comparing two runs of the browser tests
1096
+
1097
+ Many of the browser tests are red on any machine, on the new build and on the build that is live alike, so how many are red
1098
+ says nothing about a release. What holds a release back is a test that is green on the live files and is not green on the
1099
+ new build. The release pipeline does not run these tests (see "Releasing from a tag"), so this is the check you make before
1100
+ you tag:
1101
+
1102
+ 1. Run the tests on the new build: `PLAYWRIGHT_CHANNEL=chrome PORT=<a free port> npm run test:e2e -- --reporter=list > /tmp/e2e-new.log 2>&1`.
1103
+ 2. Put the build that is live in `dist/` (build its tag again, or download its files from the CDN) and run the same command
1104
+ into `/tmp/e2e-live.log`.
1105
+ 3. `npm run e2e:compare -- /tmp/e2e-new.log /tmp/e2e-live.log`.
1106
+
1107
+ The report names, by file and chain of titles (never by line number, which moves), the tests that went from green to red,
1108
+ the tests that were green and were not run (in a serial group the tests after a red one are not run), the tests that went
1109
+ from red to green, and the tests that are in only one of the two runs. The tests that are red on both, and green on both,
1110
+ are counted, and listed with `--all`; `--files '<regular expression>'` keeps the tests of the files that match.
1111
+
1112
+ Exit code 0: nothing that was green on the live files is lost. 1: something is, and each test is named: explain or fix each
1113
+ one before the manifests move. 2: a log cannot be compared (it is not found, it is empty, it was cut short, or its counts
1114
+ are not those of its own summary), which is never a pass. The logic is in `scripts/lib/e2eRunComparison.mjs`, and
1115
+ `tests/e2eRunComparison.test.mjs` holds it.
1116
+
1058
1117
  ### Size budget
1059
1118
 
1060
1119
  A partner's page downloads, parses and runs `index.js` before the module appears, and fetches the lazy files only when a
@@ -1213,6 +1272,14 @@ button is pressed (and that ordinary rate limiting is not reported as a limit).
1213
1272
  one for each managed user, to check that the two work at once on their own canvases without refusing, telling or showing
1214
1273
  each other anything.
1215
1274
 
1275
+ A test that needs a build to last long enough to be looked at says so the same way: `POST /mock/_config` with `{ generation:
1276
+ { durationMs?, codeStartsMs?, thinkingTail?, streamTail?, plan? } }` sets how a code generation runs from then on: how long it
1277
+ lasts, when the thinking ends and the code starts, the text each one shows (an empty `thinkingTail` shows neither), and a build
1278
+ plan `{ title?, tasks: [{ id, label, kind? }], decisions? }` that the operation reports with its tasks done one after the other
1279
+ over the run (`plan: null` takes it away). Until a test says otherwise a generation lasts 700 ms, with the code from 220 ms
1280
+ and no plan, and `/mock/_reset` puts that back. `e2e/widgetCreatorShopifyFeedback.spec.ts` uses it to look at the generation
1281
+ card (the thinking, then the code, in one card) and at the plan card above it.
1282
+
1216
1283
  Two rules of the gateway decide whether a call reaches these mocks at all, and `harness/gatewayRequestRules.mjs` holds both.
1217
1284
  The first is the request headers a page on another origin may send (the gateway's `ALLOWED_REQUEST_HEADERS`, in its
1218
1285
  `src/middleware/editorSessionCors.ts`, plus the File Browser's upload headers): the browser enforces it at the preflight, so a
@@ -1258,7 +1325,8 @@ src/shared/ what every module uses
1258
1325
  src/file-browser/ the module: index.ts (public API), FileBrowserHost.svelte, pickedFile.ts, module.css
1259
1326
  src/composition-editor/ the module: index.ts (public API), CompositionEditorHost.svelte, module.css, tiptapBase.css
1260
1327
  src/widget-creator/ the module: index.ts (public API), WidgetCreatorHost.svelte, module.css
1261
- scripts/build-module.mjs the Vite build; scripts/plugins/* the CSS and package fixes below
1328
+ scripts/build-module.mjs the Vite build for a release; scripts/plugins/* the CSS and package fixes below
1329
+ scripts/module-dev-server.mjs the Vite dev server the Shopify admin uses; it compiles a module when the page asks
1262
1330
  ```
1263
1331
 
1264
1332
  `module.css` is compiled once by Tailwind and the build exports it as two strings: `shadowCss` (goes into the shadow
@@ -1268,7 +1336,7 @@ root) and `documentCss` (the few rules that must live in the page: `@font-face`)
1268
1336
 
1269
1337
  `node scripts/build-module.mjs <name> --from-source` compiles that module from the sibling packages' `src`
1270
1338
  (file-browser, design-system, editor, canvas, chat, creator, workflows, and the rest) instead of from the copies in
1271
- `node_modules`. `--watch` rebuilds when one of those files is saved. A package that is not cloned stays the
1339
+ `node_modules`. `--watch` rebuilds when one of those files is saved. The Shopify dev app does not use that watch; it compiles on request, in the next section. A package that is not cloned stays the
1272
1340
  installed copy, and a bare import that the clone has not installed (`kaykay`, for example) is taken from this
1273
1341
  workspace. A SvelteKit `tsconfig` that extends a generated file is not read. `npm run build` and `publish:cdn`
1274
1342
  do not pass `--from-source`, so a published module is still built from the registry packages.
@@ -1278,14 +1346,23 @@ checkout's `global.css` pulls in that package's own Tailwind config and the modu
1278
1346
  `@source` lines in `module.css` are rewritten to the sibling `src` for the build, so the classes in the
1279
1347
  checkout are the ones that end up in the script.
1280
1348
 
1281
- The Shopify dev app is the one that serves the result. It is not a second way to publish.
1349
+ ### The Shopify dev app compiles source on request
1350
+
1351
+ `npm run dev:admin` in `Integrations/shopify` does not run `build-module.mjs --watch`. `dev-modules.mjs` walks up to this checkout and starts `scripts/module-dev-server.mjs`. The admin page still loads `/dev-modules/<name>/index.js`. That file re-exports `src/<name>/index.ts`, and this server compiles it when the browser asks, with the same aliases, shadow stylesheet, and package patches as the release build. A save of one file is ready on the next request. The first open of a screen compiles the files that screen uses. A package that is not cloned stays the installed copy.
1352
+
1353
+ The tunnel host (`https://<name>.trycloudflare.com`) is the local React app. It changes every time `npm run dev:admin` starts. `https://canvas.widgetic.com` is the production app. `https://cdn.widgetic.com` is a released module. This server writes neither.
1354
+
1355
+ `npm run build` and `publish:cdn` do not start this server. A release is still the minified file from the registry packages, described under "Publishing". The dev server is not a second way to publish. The admin setup is in `Integrations/shopify/__docs/dev-app-and-tunnel.md`.
1282
1356
 
1283
1357
  ### One file, and the parts that are not in it
1284
1358
 
1285
1359
  A module is `index.js`, which has everything the module needs to appear and to work, and the **lazy files** in `chunks/`:
1286
1360
  parts that are heavy and that most visitors never need. Today that is pdf.js (0.46 MB) and its web worker (1.4 MB), for a
1287
- visitor who previews a PDF. `index.js` fetches one the first time it is needed, from the folder it was itself loaded
1288
- from (`import.meta.url`), so the files of a version work wherever that folder is: the CDN, a mirror, a partner's own copy.
1361
+ visitor who previews a PDF, and, in the widget creator, Three.js (0.75 MB) and the mascot's sound engine, which the creator
1362
+ fetches as soon as it is open so that the mascot is ready for the first answer (`mascot: false` never asks for them), and
1363
+ Prettier (0.76 MB, in three files), for the chat's code card when it first lays out a script. `index.js` fetches one when it
1364
+ is needed, from the folder it was itself loaded from (`import.meta.url`), so the files of a version work wherever that
1365
+ folder is: the CDN, a mirror, a partner's own copy.
1289
1366
 
1290
1367
  ```
1291
1368
  dist/file-browser/index.js 1.50 MB everything the File Browser needs to open
@@ -1576,7 +1653,9 @@ A tag whose name is not `modules-v<version>` makes no pipeline, so if a tag star
1576
1653
  - **`verify`** holds no key. It refuses a tag that is not protected, a commit that is not on the default branch, a tag
1577
1654
  whose version is not the one in `package.json`, a lockfile the pipeline cannot install, and a module whose changelog
1578
1655
  has no entry for the version. Then it runs the typecheck, the unit tests and the build with its size budgets. It does
1579
- not run the browser tests (`npm run test:e2e`, which need browsers): run them before you tag.
1656
+ not run the browser tests (`npm run test:e2e`, which need browsers): run them before you tag, on the new build and on the
1657
+ build that is live, and set the two logs against each other with `npm run e2e:compare` (see "Comparing two runs of the
1658
+ browser tests").
1580
1659
  - **`publish`** is the only job that sees the keys. It releases **every module in `dist/`** in three passes
1581
1660
  (`scripts/release-modules.mjs`, which runs the commands of "By hand" for each module):
1582
1661
  1. *ask*: `--dry-run --skip-build`. It reads the CDN and refuses, before anything is written, a version that is already
@@ -1663,6 +1742,9 @@ By a person who can change the project's settings in GitLab.
1663
1742
  commit the lockfile. `npm run release:check` says what is missing, and `verify` stops at its first step when the
1664
1743
  lockfile cannot be installed, which is where it should. (Done on 2026-10-09: every package is released, the ranges
1665
1744
  in `package.json` ask for them and `npm run release:check -- --tag modules-v0.1.0` passes.)
1745
+ `@widgetic/api-sdk` is private. Every job that runs `npm ci` writes the group variable `NPM_TOKEN` into npm's
1746
+ config first, including the loader build. The variable is protected and masked, so only a protected branch or tag
1747
+ receives it.
1666
1748
  6. **The first release of every module is made by hand,** with `--allow-create` (below).
1667
1749
 
1668
1750
  ### The first release, in order
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@widgetic/ui-sdk",
3
- "version": "0.1.15",
3
+ "version": "0.1.17",
4
4
  "description": "Framework-agnostic UI components for building Widgetic integrations",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "main": "dist/index.cjs",