@widgetic/ui-sdk 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +725 -2
  2. package/dist/index.d.ts +53 -0
  3. package/dist/index.d.ts.map +1 -0
  4. package/dist/index.esm.js +2525 -0
  5. package/dist/index.esm.js.map +1 -0
  6. package/dist/index.js +2559 -0
  7. package/dist/index.js.map +1 -0
  8. package/dist/sdk/core/component.d.ts +47 -0
  9. package/dist/sdk/core/component.d.ts.map +1 -0
  10. package/dist/sdk/core/events.d.ts +26 -0
  11. package/dist/sdk/core/events.d.ts.map +1 -0
  12. package/dist/sdk/core/index.d.ts +33 -0
  13. package/dist/sdk/core/index.d.ts.map +1 -0
  14. package/dist/sdk/core/lifecycle.d.ts +97 -0
  15. package/dist/sdk/core/lifecycle.d.ts.map +1 -0
  16. package/dist/sdk/core/local-events.d.ts +25 -0
  17. package/dist/sdk/core/local-events.d.ts.map +1 -0
  18. package/dist/sdk/core/messaging.d.ts +58 -0
  19. package/dist/sdk/core/messaging.d.ts.map +1 -0
  20. package/dist/sdk/core/state.d.ts +58 -0
  21. package/dist/sdk/core/state.d.ts.map +1 -0
  22. package/dist/sdk/core/theme-mode.d.ts +44 -0
  23. package/dist/sdk/core/theme-mode.d.ts.map +1 -0
  24. package/dist/sdk/core/theme.d.ts +58 -0
  25. package/dist/sdk/core/theme.d.ts.map +1 -0
  26. package/dist/sdk/index.d.ts +4 -0
  27. package/dist/sdk/index.d.ts.map +1 -0
  28. package/dist/sdk/integration/host.d.ts +54 -0
  29. package/dist/sdk/integration/host.d.ts.map +1 -0
  30. package/dist/sdk/integration/index.d.ts +19 -0
  31. package/dist/sdk/integration/index.d.ts.map +1 -0
  32. package/dist/sdk/layers/index.d.ts +36 -0
  33. package/dist/sdk/layers/index.d.ts.map +1 -0
  34. package/dist/sdk/loader/ui.d.ts +165 -0
  35. package/dist/sdk/loader/ui.d.ts.map +1 -0
  36. package/dist/sdk/modules/index.d.ts +9 -0
  37. package/dist/sdk/modules/index.d.ts.map +1 -0
  38. package/dist/sdk/modules/loader.d.ts +84 -0
  39. package/dist/sdk/modules/loader.d.ts.map +1 -0
  40. package/dist/sdk/types/component.d.ts +177 -0
  41. package/dist/sdk/types/component.d.ts.map +1 -0
  42. package/dist/sdk/types/events.d.ts +112 -0
  43. package/dist/sdk/types/events.d.ts.map +1 -0
  44. package/dist/sdk/types/index.d.ts +42 -0
  45. package/dist/sdk/types/index.d.ts.map +1 -0
  46. package/dist/sdk/types/messaging.d.ts +41 -0
  47. package/dist/sdk/types/messaging.d.ts.map +1 -0
  48. package/dist/sdk/types/module-language.d.ts +45 -0
  49. package/dist/sdk/types/module-language.d.ts.map +1 -0
  50. package/dist/sdk/types/module-theme.d.ts +93 -0
  51. package/dist/sdk/types/module-theme.d.ts.map +1 -0
  52. package/dist/sdk/types/state.d.ts +38 -0
  53. package/dist/sdk/types/state.d.ts.map +1 -0
  54. package/dist/sdk/types/theme.d.ts +76 -0
  55. package/dist/sdk/types/theme.d.ts.map +1 -0
  56. package/dist/sdk/utils/config.d.ts +70 -0
  57. package/dist/sdk/utils/config.d.ts.map +1 -0
  58. package/dist/sdk/utils/errors.d.ts +56 -0
  59. package/dist/sdk/utils/errors.d.ts.map +1 -0
  60. package/dist/sdk/utils/http.d.ts +21 -0
  61. package/dist/sdk/utils/http.d.ts.map +1 -0
  62. package/dist/sdk/utils/security.d.ts +95 -0
  63. package/dist/sdk/utils/security.d.ts.map +1 -0
  64. package/dist/sdk/utils/validation.d.ts +64 -0
  65. package/dist/sdk/utils/validation.d.ts.map +1 -0
  66. package/dist/sdk/version.d.ts +8 -0
  67. package/dist/sdk/version.d.ts.map +1 -0
  68. package/dist/services/dataService.d.ts +10 -0
  69. package/dist/services/dataService.d.ts.map +1 -0
  70. package/dist/umd/ui-sdk.js +2 -0
  71. package/dist/umd/ui-sdk.js.map +1 -0
  72. package/dist/utils/caseConversion.d.ts +3 -0
  73. package/dist/utils/caseConversion.d.ts.map +1 -0
  74. package/package.json +91 -4
package/dist/index.js ADDED
@@ -0,0 +1,2559 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ class SDKErrorHandler {
6
+ /**
7
+ * Create standardized error object
8
+ * Formats error with message and code for consistent handling
9
+ * @param message - Human readable error message
10
+ * @param code - Error code for programmatic handling
11
+ * @returns Formatted error object
12
+ */
13
+ static createError(message, code) {
14
+ const error = new Error(message);
15
+ error.code = code;
16
+ return error;
17
+ }
18
+ /**
19
+ * Handle and transform errors
20
+ * Converts various error types to standardized SDK errors
21
+ * @param error - Original error object
22
+ * @param context - Error context for tracking
23
+ * @returns Standardized error object
24
+ */
25
+ static handleError(error, context) {
26
+ // Already standardized error
27
+ if (error instanceof Error) {
28
+ if (error.code) {
29
+ return error;
30
+ }
31
+ return this.createError(error.message, 'UNKNOWN_ERROR');
32
+ }
33
+ // String error
34
+ if (typeof error === 'string') {
35
+ return this.createError(error, 'STRING_ERROR');
36
+ }
37
+ // Unknown error type
38
+ return this.createError(`Unknown error in ${context}`, 'UNKNOWN_ERROR');
39
+ }
40
+ /**
41
+ * Convert error to SDK error format
42
+ * Ensures error object matches SDK error interface
43
+ * @param error - Error to convert
44
+ * @returns SDK formatted error
45
+ */
46
+ static toSDKError(error) {
47
+ return {
48
+ message: error.message,
49
+ code: error.code || 'UNKNOWN_ERROR',
50
+ name: error.name,
51
+ stack: error.stack,
52
+ details: error
53
+ };
54
+ }
55
+ }
56
+ /**
57
+ * Validation Error
58
+ * Thrown when input validation fails
59
+ */
60
+ class ValidationError extends Error {
61
+ constructor(message, field) {
62
+ super(message);
63
+ this.field = field;
64
+ this.name = 'ValidationError';
65
+ }
66
+ }
67
+ /**
68
+ * Security Error
69
+ * Thrown when security checks fail
70
+ */
71
+ class SecurityError extends Error {
72
+ constructor(message, code) {
73
+ super(message);
74
+ this.code = code;
75
+ this.name = 'SecurityError';
76
+ }
77
+ }
78
+ /**
79
+ * Component Error
80
+ * Thrown when component operations fail
81
+ */
82
+ class ComponentError extends Error {
83
+ constructor(message, componentId) {
84
+ super(message);
85
+ this.componentId = componentId;
86
+ this.name = 'ComponentError';
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Validation Utilities
92
+ * Provides centralized validation functions for:
93
+ * - Component IDs and references
94
+ * - DOM containers
95
+ * - Configuration objects
96
+ * - File uploads
97
+ * - Event types
98
+ */
99
+ class ValidationUtils {
100
+ /**
101
+ * Validate component or resource ID
102
+ * Ensures ID is non-empty string and properly formatted
103
+ * @param id - ID to validate
104
+ * @param context - Context for error messages
105
+ * @throws Error if ID is invalid
106
+ */
107
+ static validateId(id, context) {
108
+ if (!id || typeof id !== 'string' || id.trim() === '') {
109
+ throw SDKErrorHandler.createError(`Invalid ID provided in ${context}`, 'INVALID_ID');
110
+ }
111
+ }
112
+ /**
113
+ * Validate DOM container element
114
+ * Checks container existence and type, handles both selectors and elements
115
+ * @param container - Container element or selector
116
+ * @param context - Context for error messages
117
+ * @returns Validated HTMLElement
118
+ * @throws Error if container is invalid
119
+ */
120
+ static validateContainer(container, context) {
121
+ ValidationUtils.requireBrowser(context);
122
+ if (!container) {
123
+ throw SDKErrorHandler.createError(`Container is required in ${context}`, 'MISSING_CONTAINER');
124
+ }
125
+ if (typeof container === 'string') {
126
+ const element = document.querySelector(container);
127
+ if (!element) {
128
+ throw SDKErrorHandler.createError(`Container not found: ${container}`, 'CONTAINER_NOT_FOUND');
129
+ }
130
+ return element;
131
+ }
132
+ if (!(container instanceof HTMLElement)) {
133
+ throw SDKErrorHandler.createError(`Invalid container type in ${context}`, 'INVALID_CONTAINER');
134
+ }
135
+ return container;
136
+ }
137
+ /**
138
+ * Refuse to run where there is no page
139
+ * Importing and constructing the SDK is safe on a server (it touches nothing), but a module can only be shown in a
140
+ * browser. Mounting during server-side rendering is a mistake worth a clear message, not "document is not defined".
141
+ * @param context - What was being attempted, for the message
142
+ * @throws Error with code NOT_IN_BROWSER when there is no `document`
143
+ */
144
+ static requireBrowser(context) {
145
+ if (typeof document === 'undefined') {
146
+ throw SDKErrorHandler.createError(`Widgetic modules can only be used in a browser (${context}). With server-side rendering, ` +
147
+ 'start them from an effect or an event handler, which only run on the client.', 'NOT_IN_BROWSER');
148
+ }
149
+ }
150
+ /**
151
+ * Refuse an API key in SDK options
152
+ * An API key must never be in a browser: whoever opens the page's developer tools could read it. The partner's
153
+ * server keeps the key, mints an editor session token with it, and the page's `getToken` returns that token.
154
+ * Both the current spelling (`apiKey`) and the old one (`partner: { apiKey }`) are refused, with a message that
155
+ * says what to do instead. The key itself is never put into the message.
156
+ * @param options - SDK or mount options to check
157
+ * @throws Error with code API_KEY_NOT_ALLOWED if an API key is present
158
+ */
159
+ static rejectApiKey(options) {
160
+ const loose = (options ?? {});
161
+ const partner = loose.partner;
162
+ if (loose.apiKey !== undefined || partner?.apiKey !== undefined) {
163
+ throw SDKErrorHandler.createError('The apiKey option is not accepted: an API key must never be in a browser. ' +
164
+ 'Mint an editor session on your server (POST /v1/managed-users/{id}/editor-sessions) and ' +
165
+ 'return its token from the getToken option.', 'API_KEY_NOT_ALLOWED');
166
+ }
167
+ }
168
+ /**
169
+ * Validate configuration object
170
+ * Checks for required fields in configuration objects
171
+ * @param config - Configuration object to validate
172
+ * @param requiredFields - Array of required field names
173
+ * @param context - Context for error messages
174
+ * @throws Error if required fields are missing
175
+ */
176
+ static validateConfig(config, requiredFields, context) {
177
+ if (!config) {
178
+ throw SDKErrorHandler.createError(`Configuration is required in ${context}`, 'MISSING_CONFIG');
179
+ }
180
+ for (const field of requiredFields) {
181
+ if (!(field in config)) {
182
+ throw SDKErrorHandler.createError(`Missing required field: ${String(field)} in ${context}`, 'MISSING_REQUIRED_FIELD');
183
+ }
184
+ }
185
+ }
186
+ /**
187
+ * Validate event type
188
+ * Ensures event type is in list of valid types
189
+ * @param type - Event type to validate
190
+ * @param validTypes - Array of valid event types
191
+ * @throws Error if event type is invalid
192
+ */
193
+ static validateEventType(type, validTypes) {
194
+ if (!validTypes.includes(type)) {
195
+ throw SDKErrorHandler.createError(`Invalid event type: ${type}`, 'INVALID_EVENT_TYPE');
196
+ }
197
+ }
198
+ /**
199
+ * Validate file upload
200
+ * Checks file size and type against allowed values
201
+ * @param file - File to validate
202
+ * @param maxSize - Maximum allowed file size
203
+ * @param allowedTypes - Array of allowed MIME types
204
+ * @throws Error if file is invalid
205
+ */
206
+ static validateFileUpload(file, maxSize, allowedTypes) {
207
+ if (file.size > maxSize) {
208
+ throw SDKErrorHandler.createError(`File size exceeds maximum allowed size of ${maxSize} bytes`, 'FILE_TOO_LARGE');
209
+ }
210
+ if (!allowedTypes.includes('*/*') && !allowedTypes.includes(file.type)) {
211
+ throw SDKErrorHandler.createError(`File type ${file.type} is not allowed`, 'INVALID_FILE_TYPE');
212
+ }
213
+ }
214
+ }
215
+
216
+ /** The keys the SDK recognises in an object theme. */
217
+ const THEME_KEYS = ['mode', 'preset', 'colors', 'radius', 'font'];
218
+ const MODES = ['light', 'dark', 'system'];
219
+ const DARK_SCHEME_QUERY = '(prefers-color-scheme: dark)';
220
+ function isMode(value) {
221
+ return typeof value === 'string' && MODES.includes(value);
222
+ }
223
+ /** True when the visitor's system asks for dark colours. False where that cannot be known (server, old browser). */
224
+ function systemPrefersDark() {
225
+ return typeof window !== 'undefined'
226
+ && typeof window.matchMedia === 'function'
227
+ && window.matchMedia(DARK_SCHEME_QUERY).matches;
228
+ }
229
+ /**
230
+ * True for something `updateTheme` can use: `'light'`, `'dark'`, `'system'`, or an object with at least one of `mode`,
231
+ * `preset`, `colors`, `radius`, `font` and nothing else. Only the shape is checked here; the modules check the values.
232
+ */
233
+ function isThemeOption(value) {
234
+ if (typeof value === 'string') {
235
+ return isMode(value);
236
+ }
237
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
238
+ return false;
239
+ }
240
+ const given = Object.entries(value).filter(([, entry]) => entry !== undefined);
241
+ if (given.length === 0) {
242
+ return false;
243
+ }
244
+ if (!given.every(([key]) => THEME_KEYS.includes(key))) {
245
+ return false;
246
+ }
247
+ const mode = value.mode;
248
+ return mode === undefined || isMode(mode);
249
+ }
250
+ /** The mode a theme option asks for, or `undefined` when it asks for none. */
251
+ function modeOfThemeOption(theme) {
252
+ const mode = typeof theme === 'string' ? theme : theme?.mode;
253
+ return isMode(mode) ? mode : undefined;
254
+ }
255
+ /**
256
+ * What an object theme sets besides its mode, or `undefined` for a bare mode, for nothing, and for an object with a mode
257
+ * only. A key the SDK does not know is kept, so that the module it reaches can say it is a mistake.
258
+ */
259
+ function settingsOfThemeOption(theme) {
260
+ if (!theme || typeof theme !== 'object' || Array.isArray(theme)) {
261
+ return undefined;
262
+ }
263
+ const settings = Object.fromEntries(Object.entries(theme).filter(([key, entry]) => key !== 'mode' && entry !== undefined));
264
+ return Object.keys(settings).length > 0 ? settings : undefined;
265
+ }
266
+ /** `light` or `dark`, with `system` turned into whichever one the visitor's system prefers right now. */
267
+ function resolveMode(mode) {
268
+ if (mode === 'system') {
269
+ return systemPrefersDark() ? 'dark' : 'light';
270
+ }
271
+ return mode === 'dark' ? 'dark' : 'light';
272
+ }
273
+ /**
274
+ * The `theme` a module is built with: the settings of the mount call where it brought some, the page-wide settings where
275
+ * it did not; the mode of the mount call where it brought one, the page-wide mode where it did not.
276
+ * With no settings at all this is just `'light'` or `'dark'`, which is what modules have always been given.
277
+ */
278
+ function themeForModule(own, pageWide) {
279
+ const ownMode = modeOfThemeOption(own);
280
+ const mode = ownMode ? resolveMode(ownMode) : pageWide.mode;
281
+ const settings = settingsOfThemeOption(own) ?? pageWide.settings;
282
+ return settings ? { ...settings, mode } : mode;
283
+ }
284
+ /**
285
+ * Calls `onChange` whenever the visitor's system switches between light and dark.
286
+ * Returns a function that stops listening. Does nothing where the browser cannot tell.
287
+ */
288
+ function watchSystemTheme(onChange) {
289
+ if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') {
290
+ return () => { };
291
+ }
292
+ const query = window.matchMedia(DARK_SCHEME_QUERY);
293
+ const listener = (event) => onChange(event.matches ? 'dark' : 'light');
294
+ query.addEventListener('change', listener);
295
+ return () => query.removeEventListener('change', listener);
296
+ }
297
+
298
+ /** The module started loading but could not be built or mounted. `cause` has the module's own error. */
299
+ class ModuleMountError extends Error {
300
+ constructor(moduleName, cause) {
301
+ super(`The "${moduleName}" module failed to start: ${cause instanceof Error ? cause.message : String(cause)}`);
302
+ this.code = 'MOUNT_FAILED';
303
+ this.name = 'ModuleMountError';
304
+ this.moduleName = moduleName;
305
+ this.cause = cause;
306
+ Object.setPrototypeOf(this, ModuleMountError.prototype);
307
+ }
308
+ }
309
+ class LifecycleManager {
310
+ constructor(events, options) {
311
+ this.events = events;
312
+ this.options = options;
313
+ this.active = new Map();
314
+ }
315
+ /**
316
+ * Mount a module into a container.
317
+ * @param type - Which module, like `file-browser`.
318
+ * @param mountConfig - The container, SDK-level options and whatever the module itself takes.
319
+ * @returns The mounted module. `unmount()` on it takes it down again.
320
+ */
321
+ async mount(type, mountConfig) {
322
+ ValidationUtils.rejectApiKey(mountConfig);
323
+ const container = ValidationUtils.validateContainer(mountConfig.container, 'LifecycleManager.mount');
324
+ // What is for the SDK is taken out; whatever is left belongs to the module.
325
+ const { version, theme, placeholder, loadingLabel, on, callbacks, signal, ...optionsWithContainer } = mountConfig;
326
+ const moduleOptions = withoutContainer(optionsWithContainer);
327
+ const instanceId = this.generateInstanceId();
328
+ const placeholderElement = placeholder === false ? null : this.showPlaceholder(container, type, loadingLabel);
329
+ let module = null;
330
+ const stopListening = [];
331
+ try {
332
+ throwIfAborted(signal, type);
333
+ const loaded = await this.options.loader.load(type, { version });
334
+ throwIfAborted(signal, type);
335
+ const { getToken: partnerGetToken, apiUrl, locale } = this.options.moduleDefaults;
336
+ try {
337
+ module = new loaded.Module(container, {
338
+ apiUrl,
339
+ locale,
340
+ // An async wrapper: a getToken that throws before returning a promise still reaches the module
341
+ // as a rejected promise, which is the one shape the module handles. Without a getToken the
342
+ // module gets none (not a function that fails), so it can tell "no token source" from "a broken one".
343
+ ...(partnerGetToken ? { getToken: async (context) => partnerGetToken(context) } : {}),
344
+ ...moduleOptions,
345
+ theme: themeForModule(theme, { mode: this.options.getThemeMode(), settings: this.options.getThemeSettings?.() }),
346
+ });
347
+ stopListening.push(...this.connectEvents(instanceId, module, { on, callbacks }));
348
+ await module.mount();
349
+ }
350
+ catch (error) {
351
+ throw new ModuleMountError(type, error);
352
+ }
353
+ // Cancelled while the module was starting: the catch below takes the finished module down again.
354
+ throwIfAborted(signal, type);
355
+ const mounted = this.createMountedModule(instanceId, type, loaded.version, container, module);
356
+ this.active.set(instanceId, { mounted, stopListening, hasOwnSettings: settingsOfThemeOption(theme) !== undefined });
357
+ return mounted;
358
+ }
359
+ catch (error) {
360
+ // Whatever got started is taken down again, so a failed mount leaves nothing behind.
361
+ for (const stop of stopListening) {
362
+ stop();
363
+ }
364
+ await this.unmountQuietly(module);
365
+ throw SDKErrorHandler.handleError(error, 'LifecycleManager.mount');
366
+ }
367
+ finally {
368
+ placeholderElement?.remove();
369
+ }
370
+ }
371
+ /** Take one mounted module down. */
372
+ async unmount(instanceId) {
373
+ const activeModule = this.active.get(instanceId);
374
+ if (!activeModule) {
375
+ throw SDKErrorHandler.createError(`No instance found for ID: ${instanceId}`, 'INSTANCE_NOT_FOUND');
376
+ }
377
+ // Forgotten first: even if the module's own unmount throws, the instance is gone and cannot be unmounted twice.
378
+ this.active.delete(instanceId);
379
+ try {
380
+ // The partner's handlers stay connected while the module goes down: it may still have something to say on
381
+ // its way out (the composition editor saves what is unsaved first, and reports it when it cannot), and a
382
+ // page that asked to hear `error` would otherwise never learn that edits were lost.
383
+ await activeModule.mounted.module.unmount?.();
384
+ }
385
+ finally {
386
+ // Whatever the module's own unmount did, nothing it says afterwards reaches the page.
387
+ for (const stop of activeModule.stopListening) {
388
+ stop();
389
+ }
390
+ }
391
+ }
392
+ /** A module that is currently mounted, or `undefined`. */
393
+ get(instanceId) {
394
+ return this.active.get(instanceId)?.mounted;
395
+ }
396
+ /**
397
+ * Tells every mounted module to switch to the light or the dark look. A module keeps the rest of its theme (its preset,
398
+ * colours, radius and font): a bare mode only changes the mode.
399
+ */
400
+ setThemeMode(mode) {
401
+ for (const { mounted } of this.active.values()) {
402
+ this.tellModule(mounted, mode);
403
+ }
404
+ }
405
+ /**
406
+ * Gives the page's new settings to every module that has none of its own, in the mode given. A module with settings
407
+ * of its own keeps them, and is told the mode only when the call that brought the settings also chose a mode
408
+ * (`modeChanged`): a page that changes a preset does not turn a module that was mounted dark back to light.
409
+ */
410
+ setDefaultTheme(settings, mode, modeChanged = true) {
411
+ for (const { mounted, hasOwnSettings } of this.active.values()) {
412
+ if (!hasOwnSettings) {
413
+ this.tellModule(mounted, { ...settings, mode });
414
+ }
415
+ else if (modeChanged) {
416
+ this.tellModule(mounted, mode);
417
+ }
418
+ }
419
+ }
420
+ /** Hands a theme to one module. One that refuses it does not stop the others from getting theirs. */
421
+ tellModule(mounted, theme) {
422
+ try {
423
+ mounted.module.setTheme?.(theme);
424
+ }
425
+ catch (error) {
426
+ console.error(`[widgetic-ui] The "${mounted.type}" module could not apply the theme ${JSON.stringify(theme)}:`, error);
427
+ }
428
+ }
429
+ /** Take every mounted module down. One that fails to unmount does not stop the others. */
430
+ async cleanup() {
431
+ const results = await Promise.allSettled([...this.active.keys()].map((instanceId) => this.unmount(instanceId)));
432
+ for (const result of results) {
433
+ if (result.status === 'rejected') {
434
+ console.error('[widgetic-ui] A module failed to unmount during cleanup:', result.reason);
435
+ }
436
+ }
437
+ }
438
+ /**
439
+ * Subscribes to the module's events: the partner's handlers first (so they see `ready`), then the SDK's own
440
+ * bookkeeping. Returns the functions that stop every subscription.
441
+ */
442
+ connectEvents(instanceId, module, { on, callbacks }) {
443
+ const stopFunctions = [];
444
+ if (typeof module.on !== 'function') {
445
+ return stopFunctions;
446
+ }
447
+ const listen = (eventName, handler) => {
448
+ stopFunctions.push(module.on(eventName, handler));
449
+ };
450
+ for (const [eventName, handler] of Object.entries(on ?? {})) {
451
+ if (typeof handler === 'function') {
452
+ listen(eventName, handler);
453
+ }
454
+ }
455
+ listen('ready', () => {
456
+ callbacks?.onReady?.();
457
+ this.events.emit('ready', { componentId: instanceId });
458
+ });
459
+ listen('error', (payload) => {
460
+ const error = toError(payload);
461
+ callbacks?.onError?.(error);
462
+ this.events.emit('error', { componentId: instanceId, error });
463
+ });
464
+ return stopFunctions;
465
+ }
466
+ createMountedModule(instanceId, type, version, container, module) {
467
+ return {
468
+ id: instanceId,
469
+ type,
470
+ version,
471
+ container,
472
+ module,
473
+ on: (eventName, handler) => {
474
+ if (typeof module.on !== 'function') {
475
+ console.warn(`[widgetic-ui] The "${type}" module does not report events.`);
476
+ return () => { };
477
+ }
478
+ return module.on(eventName, handler);
479
+ },
480
+ off: (eventName, handler) => module.off?.(eventName, handler),
481
+ setTheme: (theme) => {
482
+ if (typeof module.setTheme !== 'function') {
483
+ console.warn(`[widgetic-ui] The "${type}" module cannot change its look.`);
484
+ return;
485
+ }
486
+ // A theme the module refuses throws from here, to the caller, and nothing changes.
487
+ module.setTheme(theme);
488
+ const activeModule = this.active.get(instanceId);
489
+ if (activeModule && typeof theme === 'object') {
490
+ activeModule.hasOwnSettings = true;
491
+ }
492
+ },
493
+ setLanguage: (language) => {
494
+ if (typeof module.setLanguage !== 'function') {
495
+ console.warn(`[widgetic-ui] The "${type}" module has no words to translate yet.`);
496
+ return;
497
+ }
498
+ // A language the module refuses throws from here, to the caller, and nothing changes.
499
+ module.setLanguage(language);
500
+ },
501
+ unmount: () => this.unmount(instanceId),
502
+ };
503
+ }
504
+ /** Takes a half-started module down without letting its own errors hide the real one. */
505
+ async unmountQuietly(module) {
506
+ try {
507
+ await module?.unmount?.();
508
+ }
509
+ catch (error) {
510
+ console.warn('[widgetic-ui] A module that failed to start also failed to clean up:', error);
511
+ }
512
+ }
513
+ /**
514
+ * Shows a spinner inside the container while the module downloads, so the page does not jump when it appears.
515
+ * It is one element, added after whatever the container already holds, and removed again by `mount`.
516
+ * A screen reader says `loadingLabel` for it ("Loading" unless the page gave its own words).
517
+ */
518
+ showPlaceholder(container, type, loadingLabel) {
519
+ const placeholder = document.createElement('div');
520
+ placeholder.setAttribute('data-widgetic-ui-loading', type);
521
+ placeholder.setAttribute('role', 'status');
522
+ placeholder.setAttribute('aria-label', typeof loadingLabel === 'string' && loadingLabel.trim() !== '' ? loadingLabel : 'Loading');
523
+ Object.assign(placeholder.style, {
524
+ display: 'flex',
525
+ alignItems: 'center',
526
+ justifyContent: 'center',
527
+ boxSizing: 'border-box',
528
+ width: '100%',
529
+ minHeight: this.getComponentMinHeight(type),
530
+ });
531
+ const spinner = document.createElement('div');
532
+ Object.assign(spinner.style, {
533
+ width: '28px',
534
+ height: '28px',
535
+ border: '3px solid rgba(128, 128, 128, 0.25)',
536
+ borderTopColor: '#3b82f6',
537
+ borderRadius: '50%',
538
+ });
539
+ // The Web Animations API instead of a @keyframes rule: nothing is added to the partner's stylesheets.
540
+ if (typeof spinner.animate === 'function') {
541
+ spinner.animate([{ transform: 'rotate(0deg)' }, { transform: 'rotate(360deg)' }], { duration: 1000, iterations: Infinity });
542
+ }
543
+ placeholder.appendChild(spinner);
544
+ container.appendChild(placeholder);
545
+ return placeholder;
546
+ }
547
+ /**
548
+ * Get recommended minimum height for component type to prevent CLS
549
+ */
550
+ getComponentMinHeight(type) {
551
+ switch (type) {
552
+ case 'widget-creator':
553
+ case 'composition-editor':
554
+ return '480px';
555
+ case 'embed-editor':
556
+ case 'file-browser':
557
+ return '380px';
558
+ default:
559
+ return '280px';
560
+ }
561
+ }
562
+ /**
563
+ * Generate unique instance ID
564
+ */
565
+ generateInstanceId() {
566
+ return `widgetic-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
567
+ }
568
+ }
569
+ /** Stops a mount the partner has cancelled. The error is an `AbortError`, the name callers of `fetch` already know. */
570
+ function throwIfAborted(signal, type) {
571
+ if (signal?.aborted) {
572
+ const error = SDKErrorHandler.createError(`Mounting the "${type}" module was cancelled.`, 'MOUNT_ABORTED');
573
+ error.name = 'AbortError';
574
+ throw error;
575
+ }
576
+ }
577
+ /** The options for the module itself: the mount config minus the container, which the module gets as its first argument. */
578
+ function withoutContainer(options) {
579
+ const moduleOptions = { ...options };
580
+ delete moduleOptions.container;
581
+ return moduleOptions;
582
+ }
583
+ /** The error behind a module's `error` event, as an `Error` the partner can inspect (`code` and `fatal` kept). */
584
+ function toError(payload) {
585
+ if (payload instanceof Error) {
586
+ return payload;
587
+ }
588
+ const { message, code, fatal } = (payload ?? {});
589
+ const error = new Error(typeof message === 'string' ? message : 'The module reported an error');
590
+ if (typeof code === 'string')
591
+ error.code = code;
592
+ if (typeof fatal === 'boolean')
593
+ error.fatal = fatal;
594
+ return error;
595
+ }
596
+
597
+ class LocalEventEmitter {
598
+ constructor() {
599
+ this.handlers = new Map();
600
+ }
601
+ /** Starts listening. Returns a function that stops listening again. */
602
+ on(event, handler) {
603
+ const handlersForEvent = this.handlers.get(event) ?? new Set();
604
+ handlersForEvent.add(handler);
605
+ this.handlers.set(event, handlersForEvent);
606
+ return () => this.off(event, handler);
607
+ }
608
+ /** Stops listening. Does nothing when the handler was not registered. */
609
+ off(event, handler) {
610
+ const handlersForEvent = this.handlers.get(event);
611
+ if (!handlersForEvent)
612
+ return;
613
+ handlersForEvent.delete(handler);
614
+ if (handlersForEvent.size === 0) {
615
+ this.handlers.delete(event);
616
+ }
617
+ }
618
+ /** Tells every listener. A listener that throws is logged and does not stop the others. */
619
+ emit(type, data) {
620
+ const handlersForEvent = this.handlers.get(type);
621
+ if (!handlersForEvent)
622
+ return;
623
+ const event = { type, ...data, timestamp: Date.now() };
624
+ for (const handler of [...handlersForEvent]) {
625
+ try {
626
+ handler(event);
627
+ }
628
+ catch (error) {
629
+ console.error(`[widgetic-ui] A handler for "${type}" threw:`, error);
630
+ }
631
+ }
632
+ }
633
+ /** Forgets every listener. */
634
+ destroy() {
635
+ this.handlers.clear();
636
+ }
637
+ }
638
+
639
+ /**
640
+ * SDK Configuration Management
641
+ *
642
+ * Holds the SDK's default addresses and the few switches the legacy security helpers read.
643
+ *
644
+ * Nothing in here handles credentials. The SDK never sees an API key: a partner's server mints a short-lived editor
645
+ * session token and the partner's `getToken` function hands it to the SDK (see `WidgeticUI`).
646
+ */
647
+ /** The Widgetic API every module talks to unless the partner points it somewhere else (staging, local gateway). */
648
+ const DEFAULT_API_URL = 'https://api.widgetic.com';
649
+ /** Where the UI modules are served from. Each module lives in a folder named after it: `<base>/<name>/…`. */
650
+ const DEFAULT_MODULE_BASE_URL = 'https://cdn.widgetic.com/modules';
651
+ /**
652
+ * Default configuration values.
653
+ *
654
+ * `NODE_ENV` defaults to production: the origin checks in the security helpers are only relaxed when a developer
655
+ * asks for development mode explicitly, never because nobody configured anything.
656
+ */
657
+ const DEFAULT_CONFIG = {
658
+ NODE_ENV: 'production',
659
+ API_URL: DEFAULT_API_URL,
660
+ API_VERSION: '/v1',
661
+ CLIENT_URL: 'https://widgetic.com',
662
+ PRODUCTION_URL: DEFAULT_API_URL,
663
+ CDN_URL: 'https://cdn.widgetic.com',
664
+ EMBED_SDK_URL: '/widgetic.js'
665
+ };
666
+ /**
667
+ * Configuration Manager
668
+ * Singleton class that handles the SDK's configuration values.
669
+ */
670
+ class ConfigManager {
671
+ constructor() {
672
+ this.config = { ...DEFAULT_CONFIG };
673
+ }
674
+ /**
675
+ * Get singleton instance
676
+ * Creates instance if it doesn't exist
677
+ */
678
+ static getInstance() {
679
+ if (!ConfigManager.instance) {
680
+ ConfigManager.instance = new ConfigManager();
681
+ }
682
+ return ConfigManager.instance;
683
+ }
684
+ /**
685
+ * Initialize configuration with custom values
686
+ * Merges provided config with defaults
687
+ * @param config - Partial configuration to apply
688
+ */
689
+ initialize(config) {
690
+ this.config = {
691
+ ...DEFAULT_CONFIG,
692
+ ...config
693
+ };
694
+ }
695
+ /**
696
+ * Get API base URL
697
+ * @returns Configured API URL
698
+ */
699
+ getApiUrl() {
700
+ return (this.isProduction ? this.config.PRODUCTION_URL : this.config.API_URL) + this.config.API_VERSION;
701
+ }
702
+ /**
703
+ * Get CDN base URL
704
+ * @returns Configured CDN URL
705
+ */
706
+ getCdnUrl() {
707
+ return this.config.CDN_URL;
708
+ }
709
+ /**
710
+ * Check if running in production mode
711
+ */
712
+ get isProduction() {
713
+ return this.config.NODE_ENV === 'production';
714
+ }
715
+ /**
716
+ * Validate required configuration
717
+ * Ensures all required values are present
718
+ * @throws Error if required config is missing
719
+ */
720
+ validateConfig() {
721
+ if (!this.config.API_URL) {
722
+ throw new Error('API_URL is required');
723
+ }
724
+ if (!this.config.API_VERSION) {
725
+ throw new Error('API_VERSION is required');
726
+ }
727
+ if (!this.config.CLIENT_URL) {
728
+ throw new Error('CLIENT_URL is required');
729
+ }
730
+ }
731
+ }
732
+ // Export singleton instance
733
+ const config = ConfigManager.getInstance();
734
+
735
+ class ModuleLoadError extends Error {
736
+ constructor(code, message, details) {
737
+ super(message);
738
+ this.name = 'ModuleLoadError';
739
+ this.code = code;
740
+ this.moduleName = details.moduleName;
741
+ this.url = details.url;
742
+ this.cause = details.cause;
743
+ // Keeps `instanceof ModuleLoadError` working when the SDK is compiled down to ES5-style classes.
744
+ Object.setPrototypeOf(this, ModuleLoadError.prototype);
745
+ }
746
+ }
747
+ const MODULE_NAME_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
748
+ const MODULE_NAME_MAX_LENGTH = 64;
749
+ const VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?$/;
750
+ const DEFAULT_RETRY_DELAYS_MS = [300, 900];
751
+ /** The browser's dynamic import. The comments tell webpack and Vite to leave this address alone (it is runtime data). */
752
+ const importFromBrowser = (specifier) => import(/* webpackIgnore: true */ /* @vite-ignore */ specifier);
753
+ class ModuleLoader {
754
+ constructor(options = {}) {
755
+ // One load per module version per page: asking twice shares the same promise, and a failed load is forgotten
756
+ // so that asking again tries again.
757
+ this.loads = new Map();
758
+ this.baseUrl = resolveBaseUrl(options.moduleBaseUrl ?? DEFAULT_MODULE_BASE_URL);
759
+ // `fetch` has to be called as a plain function of the window; stored and called as a method it throws "Illegal invocation".
760
+ this.fetchImpl = options.fetchImpl ?? ((input, init) => fetch(input, init));
761
+ this.importImpl = options.importImpl ?? importFromBrowser;
762
+ this.retryDelaysMs = options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
763
+ }
764
+ /**
765
+ * Finds and imports a module.
766
+ * @param name - The module, like `file-browser`.
767
+ * @param options.version - Pin an exact version like `1.2.0`. Default: the newest one the manifest names.
768
+ */
769
+ async load(name, options = {}) {
770
+ assertValidModuleName(name);
771
+ const pinnedVersion = options.version;
772
+ if (pinnedVersion !== undefined) {
773
+ assertValidVersion(name, pinnedVersion);
774
+ }
775
+ const cacheKey = `${name}@${pinnedVersion ?? 'latest'}`;
776
+ const existingLoad = this.loads.get(cacheKey);
777
+ if (existingLoad) {
778
+ return existingLoad;
779
+ }
780
+ const pendingLoad = this.loadUncached(name, pinnedVersion).catch((error) => {
781
+ this.loads.delete(cacheKey);
782
+ throw error;
783
+ });
784
+ this.loads.set(cacheKey, pendingLoad);
785
+ return pendingLoad;
786
+ }
787
+ async loadUncached(name, pinnedVersion) {
788
+ let version;
789
+ let entryUrl;
790
+ if (pinnedVersion !== undefined) {
791
+ version = pinnedVersion;
792
+ entryUrl = new URL(`${name}/${pinnedVersion}/index.js`, this.baseUrl);
793
+ }
794
+ else {
795
+ const manifest = await this.fetchManifest(name);
796
+ version = manifest.version;
797
+ entryUrl = this.resolveEntryUrl(name, manifest);
798
+ }
799
+ const Module = await this.importModuleFile(name, entryUrl);
800
+ return { Module, name, version, url: entryUrl.href };
801
+ }
802
+ /** Reads `<base>/<name>/manifest.json`. Network failures and server errors are retried; a missing module is not. */
803
+ async fetchManifest(name) {
804
+ const manifestUrl = new URL(`${name}/manifest.json`, this.baseUrl);
805
+ try {
806
+ return await this.withRetries(async () => {
807
+ const response = await this.fetchImpl(manifestUrl.href, { credentials: 'omit' });
808
+ if (response.status === 404 || response.status === 403) {
809
+ throw new ModuleLoadError('MODULE_NOT_FOUND', `There is no "${name}" module at ${manifestUrl.href} (HTTP ${response.status}).`, { moduleName: name, url: manifestUrl.href });
810
+ }
811
+ if (!response.ok) {
812
+ // Anything else (500, 502, 429 ...) may pass: try again.
813
+ throw new Error(`HTTP ${response.status} for ${manifestUrl.href}`);
814
+ }
815
+ let manifest;
816
+ try {
817
+ manifest = await response.json();
818
+ }
819
+ catch (parseError) {
820
+ // Typically a CDN or single-page app answering 200 with an HTML page for a path it doesn't know.
821
+ throw new ModuleLoadError('MANIFEST_INVALID', `The manifest at ${manifestUrl.href} is not JSON.`, { moduleName: name, url: manifestUrl.href, cause: parseError });
822
+ }
823
+ return this.validateManifest(name, manifestUrl, manifest);
824
+ });
825
+ }
826
+ catch (error) {
827
+ if (error instanceof ModuleLoadError) {
828
+ throw error;
829
+ }
830
+ throw new ModuleLoadError('MANIFEST_UNAVAILABLE', `Could not load the manifest of "${name}" from ${manifestUrl.href}: ${describeError(error)}`, { moduleName: name, url: manifestUrl.href, cause: error });
831
+ }
832
+ }
833
+ validateManifest(name, manifestUrl, manifest) {
834
+ const fail = (reason) => {
835
+ throw new ModuleLoadError('MANIFEST_INVALID', `The manifest at ${manifestUrl.href} ${reason}.`, {
836
+ moduleName: name,
837
+ url: manifestUrl.href,
838
+ });
839
+ };
840
+ if (typeof manifest !== 'object' || manifest === null) {
841
+ return fail('is not a JSON object');
842
+ }
843
+ const { name: manifestName, version, entry } = manifest;
844
+ if (manifestName !== name) {
845
+ return fail(`is for "${String(manifestName)}", not "${name}"`);
846
+ }
847
+ if (typeof version !== 'string' || !VERSION_PATTERN.test(version)) {
848
+ return fail(`has no valid "version" (found ${JSON.stringify(version)})`);
849
+ }
850
+ if (typeof entry !== 'string' || entry.length === 0) {
851
+ return fail('has no "entry"');
852
+ }
853
+ return { name: manifestName, version, entry };
854
+ }
855
+ /** The module file the manifest points at, which must be a script inside the module's own folder. */
856
+ resolveEntryUrl(name, manifest) {
857
+ const manifestUrl = new URL(`${name}/manifest.json`, this.baseUrl);
858
+ const moduleFolder = new URL(`${name}/`, this.baseUrl);
859
+ let entryUrl;
860
+ try {
861
+ entryUrl = new URL(manifest.entry, manifestUrl);
862
+ }
863
+ catch (error) {
864
+ throw new ModuleLoadError('MANIFEST_INVALID', `The manifest of "${name}" has an "entry" that is not an address: ${manifest.entry}`, {
865
+ moduleName: name,
866
+ url: manifestUrl.href,
867
+ cause: error,
868
+ });
869
+ }
870
+ const staysInsideFolder = entryUrl.origin === moduleFolder.origin && entryUrl.pathname.startsWith(moduleFolder.pathname);
871
+ const isScript = /\.m?js$/.test(entryUrl.pathname);
872
+ if (!staysInsideFolder || !isScript) {
873
+ throw new ModuleLoadError('MANIFEST_INVALID', `The manifest of "${name}" points at ${entryUrl.href}, which is not a script inside ${moduleFolder.href}.`, { moduleName: name, url: manifestUrl.href });
874
+ }
875
+ return entryUrl;
876
+ }
877
+ /** Imports the module file and checks it exports a class. */
878
+ async importModuleFile(name, entryUrl) {
879
+ let namespace;
880
+ try {
881
+ namespace = await this.withRetries(async (attemptIndex) => {
882
+ // Browsers remember a failed import of an address; a changed address makes the retry a real one.
883
+ const specifier = attemptIndex === 0 ? entryUrl.href : withRetryParameter(entryUrl, attemptIndex);
884
+ return this.importImpl(specifier);
885
+ });
886
+ }
887
+ catch (error) {
888
+ throw new ModuleLoadError('MODULE_LOAD_FAILED', `Could not load the "${name}" module from ${entryUrl.href}: ${describeError(error)}`, { moduleName: name, url: entryUrl.href, cause: error });
889
+ }
890
+ const exported = namespace?.default;
891
+ if (typeof exported !== 'function') {
892
+ throw new ModuleLoadError('MODULE_INVALID', `The file at ${entryUrl.href} does not export a module class as its default export.`, { moduleName: name, url: entryUrl.href });
893
+ }
894
+ return exported;
895
+ }
896
+ /**
897
+ * Runs an operation, trying again after a pause when it throws. A `ModuleLoadError` means "this will not get
898
+ * better by asking again" and is thrown straight away.
899
+ */
900
+ async withRetries(operation) {
901
+ let lastError;
902
+ for (let attemptIndex = 0; attemptIndex <= this.retryDelaysMs.length; attemptIndex++) {
903
+ try {
904
+ return await operation(attemptIndex);
905
+ }
906
+ catch (error) {
907
+ if (error instanceof ModuleLoadError) {
908
+ throw error;
909
+ }
910
+ lastError = error;
911
+ const pause = this.retryDelaysMs[attemptIndex];
912
+ if (pause !== undefined) {
913
+ await new Promise((resolve) => setTimeout(resolve, pause));
914
+ }
915
+ }
916
+ }
917
+ throw lastError;
918
+ }
919
+ }
920
+ /** Resolves the base address against the page and makes sure it ends with a slash, so names can be appended. */
921
+ function resolveBaseUrl(moduleBaseUrl) {
922
+ const pageUrl = typeof document !== 'undefined' ? document.baseURI : 'http://localhost/';
923
+ let baseUrl;
924
+ try {
925
+ baseUrl = new URL(moduleBaseUrl, pageUrl);
926
+ }
927
+ catch (error) {
928
+ throw new ModuleLoadError('INVALID_MODULE_BASE_URL', `moduleBaseUrl is not an address: ${moduleBaseUrl}`, { moduleName: '', cause: error });
929
+ }
930
+ if (baseUrl.protocol !== 'https:' && baseUrl.protocol !== 'http:') {
931
+ throw new ModuleLoadError('INVALID_MODULE_BASE_URL', `moduleBaseUrl must be an http(s) address, got ${baseUrl.protocol}`, { moduleName: '' });
932
+ }
933
+ if (!baseUrl.pathname.endsWith('/')) {
934
+ baseUrl.pathname += '/';
935
+ }
936
+ return baseUrl;
937
+ }
938
+ function assertValidModuleName(name) {
939
+ if (typeof name !== 'string' || name.length > MODULE_NAME_MAX_LENGTH || !MODULE_NAME_PATTERN.test(name)) {
940
+ throw new ModuleLoadError('INVALID_MODULE_NAME', `"${String(name)}" is not a module name. Use lowercase letters, digits and dashes, like "file-browser".`, { moduleName: String(name) });
941
+ }
942
+ }
943
+ function assertValidVersion(name, version) {
944
+ if (typeof version !== 'string' || !VERSION_PATTERN.test(version)) {
945
+ throw new ModuleLoadError('INVALID_VERSION', `"${String(version)}" is not a version. Use an exact version like "1.2.0".`, { moduleName: name });
946
+ }
947
+ }
948
+ function withRetryParameter(entryUrl, attemptIndex) {
949
+ const retryUrl = new URL(entryUrl.href);
950
+ retryUrl.searchParams.set('retry', String(attemptIndex));
951
+ return retryUrl.href;
952
+ }
953
+ function describeError(error) {
954
+ return error instanceof Error ? error.message : String(error);
955
+ }
956
+
957
+ /**
958
+ * The loaders that `WidgeticUI` creates for itself, one per module address. Sharing them makes two `mountModule`
959
+ * calls (or a React component mounting twice) download a module once, and keeps a page on one version of each module
960
+ * even if a release goes out while it is open.
961
+ */
962
+ const sharedModuleLoaders = new Map();
963
+ function sharedModuleLoaderFor(moduleBaseUrl) {
964
+ let loader = sharedModuleLoaders.get(moduleBaseUrl);
965
+ if (!loader) {
966
+ loader = new ModuleLoader({ moduleBaseUrl });
967
+ sharedModuleLoaders.set(moduleBaseUrl, loader);
968
+ }
969
+ return loader;
970
+ }
971
+ class WidgeticUI {
972
+ /**
973
+ * Initialize the SDK. Nothing is downloaded and nothing on the page is touched until a module is mounted.
974
+ * @param options - How modules reach the partner's token and the Widgetic API
975
+ */
976
+ constructor(options = {}) {
977
+ this.stopWatchingSystemTheme = null;
978
+ assertValidOptions(options);
979
+ this.events = new LocalEventEmitter();
980
+ this.loader = options.moduleLoader ?? sharedModuleLoaderFor(options.moduleBaseUrl ?? DEFAULT_MODULE_BASE_URL);
981
+ this.themeMode = modeOfThemeOption(options.theme) ?? 'light';
982
+ this.themeSettings = settingsOfThemeOption(options.theme);
983
+ this.lifecycleManager = new LifecycleManager(this.events, {
984
+ loader: this.loader,
985
+ moduleDefaults: {
986
+ apiUrl: options.apiUrl ?? DEFAULT_API_URL,
987
+ getToken: options.getToken,
988
+ locale: options.locale,
989
+ },
990
+ getThemeMode: () => resolveMode(this.themeMode),
991
+ getThemeSettings: () => this.themeSettings,
992
+ });
993
+ this.followSystemThemeWhenAsked();
994
+ }
995
+ /**
996
+ * Mount a module into a container.
997
+ * @param type - Which module, like `file-browser`
998
+ * @param config - The container, SDK options (`version`, `theme`, `on` ...) and the module's own options
999
+ * @returns The mounted module: subscribe with `.on`, take it down with `.unmount()`
1000
+ */
1001
+ async mount(type, config) {
1002
+ try {
1003
+ return (await this.lifecycleManager.mount(type, config));
1004
+ }
1005
+ catch (error) {
1006
+ // A mount the partner cancelled is not a failure to report: it is how a component that went away early ends.
1007
+ if (error?.code === 'MOUNT_ABORTED') {
1008
+ throw error;
1009
+ }
1010
+ console.error('Error mounting component:', error);
1011
+ config.callbacks?.onError?.(error);
1012
+ throw error;
1013
+ }
1014
+ }
1015
+ /**
1016
+ * Mount a module and get its instance ID back. `mount` is usually more convenient because it returns the
1017
+ * module itself.
1018
+ * @param type - Type of component to mount
1019
+ * @param config - Component configuration
1020
+ * @returns Promise resolving to instance ID
1021
+ */
1022
+ async mountComponent(type, config) {
1023
+ return (await this.mount(type, config)).id;
1024
+ }
1025
+ /**
1026
+ * Unmount a component instance
1027
+ * @param instanceId - ID of instance to unmount
1028
+ */
1029
+ async unmountComponent(instanceId) {
1030
+ try {
1031
+ await this.lifecycleManager.unmount(instanceId);
1032
+ }
1033
+ catch (error) {
1034
+ console.error('Error unmounting component:', error);
1035
+ throw error;
1036
+ }
1037
+ }
1038
+ /**
1039
+ * A module that is currently mounted
1040
+ * @param instanceId - ID returned by `mountComponent`, or `id` of a mounted module
1041
+ */
1042
+ getComponent(instanceId) {
1043
+ return this.lifecycleManager.get(instanceId);
1044
+ }
1045
+ /**
1046
+ * Download a module ahead of time, so mounting it later is instant. Mounting does this by itself;
1047
+ * call it when the page knows the visitor is likely to open the module soon.
1048
+ * @param type - Which module
1049
+ * @param options.version - Pin an exact version
1050
+ */
1051
+ async preload(type, options = {}) {
1052
+ ValidationUtils.requireBrowser(`preloading "${type}"`);
1053
+ await this.loader.load(type, options);
1054
+ }
1055
+ /**
1056
+ * Change the look of every mounted module (and every module mounted later).
1057
+ *
1058
+ * ui.updateTheme('dark'); // the mode only: every module keeps its colours, radius, font
1059
+ * ui.updateTheme({ preset: 'ocean' }); // a new look for the modules that have no theme of their own
1060
+ * ui.updateTheme({ mode: 'dark', colors: { primary: '#e0541b' } });
1061
+ *
1062
+ * A bare mode (or `{ mode }`) changes the mode of every module and keeps the rest of its theme. Settings replace the
1063
+ * page-wide theme, which is what every module without settings of its own has; a module whose mount call (or its own
1064
+ * `setTheme`) brought settings keeps them, and follows the mode when the call sets one.
1065
+ *
1066
+ * @param theme - `'light'`, `'dark'`, `'system'`, or an object with some of `mode`, `preset`, `colors`, `radius`, `font`
1067
+ * @throws `INVALID_THEME` for anything else. A module that refuses the settings reports it in the console and keeps its look.
1068
+ */
1069
+ updateTheme(theme) {
1070
+ if (!isThemeOption(theme)) {
1071
+ throw SDKErrorHandler.createError(`Unknown theme: ${JSON.stringify(theme)}. Use 'light', 'dark', 'system', or an object with some of mode, preset, colors, radius, font.`, 'INVALID_THEME');
1072
+ }
1073
+ const requestedMode = modeOfThemeOption(theme);
1074
+ const requestedSettings = settingsOfThemeOption(theme);
1075
+ if (requestedMode) {
1076
+ this.themeMode = requestedMode;
1077
+ }
1078
+ if (requestedSettings) {
1079
+ this.themeSettings = requestedSettings;
1080
+ }
1081
+ this.followSystemThemeWhenAsked();
1082
+ const resolvedMode = resolveMode(this.themeMode);
1083
+ if (requestedSettings) {
1084
+ // A module with settings of its own is told the mode only when this call set one.
1085
+ this.lifecycleManager.setDefaultTheme(requestedSettings, resolvedMode, requestedMode !== undefined);
1086
+ }
1087
+ else {
1088
+ this.lifecycleManager.setThemeMode(resolvedMode);
1089
+ }
1090
+ this.events.emit('theme:update', { theme: requestedSettings ? { ...requestedSettings, mode: this.themeMode } : { mode: this.themeMode } });
1091
+ }
1092
+ /**
1093
+ * Get the current page-wide theme
1094
+ * @returns The mode the SDK was asked for (`system` stays `system`), and the preset, colours, radius and font if it was given any
1095
+ */
1096
+ getTheme() {
1097
+ return { mode: this.themeMode, ...this.themeSettings };
1098
+ }
1099
+ /**
1100
+ * Subscribe to SDK events
1101
+ * @param event - Event type to subscribe to
1102
+ * @param handler - Event handler function
1103
+ * @returns Unsubscribe function
1104
+ */
1105
+ on(event, handler) {
1106
+ return this.events.on(event, handler);
1107
+ }
1108
+ /**
1109
+ * Unsubscribe from SDK events
1110
+ * @param event - Event type to unsubscribe from
1111
+ * @param handler - Event handler to remove
1112
+ */
1113
+ off(event, handler) {
1114
+ this.events.off(event, handler);
1115
+ }
1116
+ /**
1117
+ * Emit SDK events with type-safe payload
1118
+ * @param type - Event type to emit
1119
+ * @param data - Event data
1120
+ */
1121
+ emit(type, data) {
1122
+ this.events.emit(type, data);
1123
+ }
1124
+ /**
1125
+ * Cleanup and destroy SDK instance
1126
+ * Unmounts every module this instance mounted and stops listening for anything.
1127
+ */
1128
+ async destroy() {
1129
+ this.stopWatchingSystemTheme?.();
1130
+ this.stopWatchingSystemTheme = null;
1131
+ await this.lifecycleManager.cleanup();
1132
+ this.events.destroy();
1133
+ }
1134
+ /** While the theme is `system`, mounted modules follow the visitor's system; otherwise there is nothing to follow. */
1135
+ followSystemThemeWhenAsked() {
1136
+ this.stopWatchingSystemTheme?.();
1137
+ this.stopWatchingSystemTheme = null;
1138
+ if (this.themeMode === 'system') {
1139
+ this.stopWatchingSystemTheme = watchSystemTheme((systemMode) => this.lifecycleManager.setThemeMode(systemMode));
1140
+ }
1141
+ }
1142
+ }
1143
+ /**
1144
+ * Mount one module with a single call: the SDK is created, the module is mounted, and `unmount()` on the result
1145
+ * takes both down. Use `new WidgeticUI(...)` when a page mounts several modules.
1146
+ *
1147
+ * const fileBrowser = await mountModule('file-browser', {
1148
+ * container: document.getElementById('files'),
1149
+ * getToken: async () => (await fetch('/my-server/widgetic-session')).json(),
1150
+ * on: { select: ({ files }) => useFiles(files) },
1151
+ * });
1152
+ */
1153
+ async function mountModule(type, options) {
1154
+ // Before the options are split: an apiKey left in the mount options would otherwise reach the module.
1155
+ ValidationUtils.rejectApiKey(options);
1156
+ const { getToken, apiUrl, moduleBaseUrl, locale, moduleLoader, ...mountConfig } = options;
1157
+ const ui = new WidgeticUI({ getToken, apiUrl, moduleBaseUrl, locale, moduleLoader, theme: mountConfig.theme });
1158
+ let mounted;
1159
+ try {
1160
+ mounted = await ui.mount(type, mountConfig);
1161
+ }
1162
+ catch (error) {
1163
+ await ui.destroy();
1164
+ throw error;
1165
+ }
1166
+ return {
1167
+ ...mounted,
1168
+ unmount: async () => {
1169
+ try {
1170
+ await mounted.unmount();
1171
+ }
1172
+ finally {
1173
+ await ui.destroy();
1174
+ }
1175
+ },
1176
+ };
1177
+ }
1178
+ /**
1179
+ * Rejects an API key with a message that says why not, and a `getToken` that is not a function with one that says
1180
+ * what it should be. A missing `getToken` is fine here: whether a module needs a token is the module's to say.
1181
+ */
1182
+ function assertValidOptions(options) {
1183
+ ValidationUtils.rejectApiKey(options);
1184
+ const getToken = options?.getToken;
1185
+ if (getToken !== undefined && typeof getToken !== 'function') {
1186
+ throw SDKErrorHandler.createError('WidgeticUI: getToken must be a function that resolves an editor session token ' +
1187
+ '(or { token, expiresAt }) minted by your server.', 'INVALID_GET_TOKEN');
1188
+ }
1189
+ }
1190
+ // NOTE: Do not export a singleton instance from the SDK root to avoid
1191
+ // executing environment-dependent code at import time.
1192
+ // Consumers should instantiate the class themselves.
1193
+
1194
+ /**
1195
+ * High-Level UI API for UI SDK
1196
+ *
1197
+ * The shortest way to put a Widgetic module on a page: configure once, then mount by name.
1198
+ * Perfect for: Quick integration, HTML-first approaches, minimal JavaScript.
1199
+ *
1200
+ * For anything more (several instances, events, different tokens per module) use `WidgeticUI` or `mountModule`
1201
+ * directly. The mid-level and low-level APIs that used to sit beside this one handed out the SDK's internals,
1202
+ * including an HTTP client that sent an API key from the browser; they were removed.
1203
+ */
1204
+ // Shared instance behind the high-level calls
1205
+ let sharedUIInstance = null;
1206
+ function requireSharedUI() {
1207
+ if (!sharedUIInstance) {
1208
+ throw SDKErrorHandler.createError('Call HighLevelUIAPI.initialize({ getToken }) before mounting a component.', 'NOT_INITIALIZED');
1209
+ }
1210
+ return sharedUIInstance;
1211
+ }
1212
+ /**
1213
+ * High-Level UI API - Declarative & Auto-magical
1214
+ *
1215
+ * Characteristics: one-call initialization, convention over configuration.
1216
+ */
1217
+ const HighLevelUIAPI = {
1218
+ // Main UI SDK class for setups that need more than the shared instance
1219
+ WidgeticUI,
1220
+ /**
1221
+ * Configure the shared SDK instance. Calling it again replaces the instance and unmounts what the old one mounted.
1222
+ */
1223
+ initialize: async (options) => {
1224
+ // Built first: invalid options throw before the working instance is touched.
1225
+ const newInstance = new WidgeticUI(options);
1226
+ const previousInstance = sharedUIInstance;
1227
+ sharedUIInstance = newInstance;
1228
+ await previousInstance?.destroy();
1229
+ return newInstance;
1230
+ },
1231
+ /**
1232
+ * Mount a module into a container, given as an element or a CSS selector.
1233
+ * @returns The instance ID to hand to `unmountComponent`
1234
+ */
1235
+ mountComponent: async (type, container, options = {}) => {
1236
+ return requireSharedUI().mountComponent(type, { ...options, container });
1237
+ },
1238
+ /**
1239
+ * Take a mounted module down.
1240
+ * @param instanceId - What `mountComponent` returned
1241
+ */
1242
+ unmountComponent: async (instanceId) => {
1243
+ await requireSharedUI().unmountComponent(instanceId);
1244
+ },
1245
+ };
1246
+
1247
+ class EventSystem {
1248
+ constructor(bridge, targetOrigin) {
1249
+ // Maps event types to their respective handlers
1250
+ this.handlers = new Map();
1251
+ // Separate map for host-specific event handlers
1252
+ this.hostHandlers = new Map();
1253
+ // Bound listener reference for clean teardown
1254
+ this.messageListener = null;
1255
+ // console.log('Initializing Event System');
1256
+ this.bridge = bridge || (typeof window !== 'undefined' ? window.parent : {});
1257
+ this.targetOrigin = targetOrigin || (typeof window !== 'undefined' && window.location?.origin ? window.location.origin : '*');
1258
+ this.setupMessageListener();
1259
+ }
1260
+ setupMessageListener() {
1261
+ this.messageListener = (event) => {
1262
+ this.handleMessage(event);
1263
+ };
1264
+ // Set up appropriate message listener based on bridge type
1265
+ if (this.bridge instanceof MessagePort) {
1266
+ this.bridge.onmessage = this.messageListener;
1267
+ }
1268
+ else if (typeof window !== 'undefined') {
1269
+ window.addEventListener('message', this.messageListener);
1270
+ }
1271
+ }
1272
+ // Handle incoming messages from host application
1273
+ handleMessage(event) {
1274
+ try {
1275
+ if (!this.validateMessage(event)) {
1276
+ return;
1277
+ }
1278
+ const { type, data } = event.data;
1279
+ const handlers = this.hostHandlers.get(type);
1280
+ if (handlers) {
1281
+ handlers.forEach(handler => {
1282
+ try {
1283
+ handler(data);
1284
+ }
1285
+ catch (error) {
1286
+ console.error(`Error in host event handler for ${type}:`, error);
1287
+ this.emitError('message_handler_error', error);
1288
+ }
1289
+ });
1290
+ }
1291
+ }
1292
+ catch (error) {
1293
+ console.error('Error processing message:', error);
1294
+ this.emitError('message_processing_error', error);
1295
+ }
1296
+ }
1297
+ // Validate incoming messages for security and structure
1298
+ validateMessage(event) {
1299
+ if (this.bridge instanceof MessagePort) {
1300
+ return true;
1301
+ }
1302
+ if (!event.data || typeof event.data !== 'object') {
1303
+ return false;
1304
+ }
1305
+ const { type, source } = event.data;
1306
+ if (!type || !source) {
1307
+ return false;
1308
+ }
1309
+ if (source !== 'partner-platform') {
1310
+ return false;
1311
+ }
1312
+ return true;
1313
+ }
1314
+ // Subscribe to events with automatic cleanup function
1315
+ on(event, handler) {
1316
+ if (!this.handlers.has(event)) {
1317
+ this.handlers.set(event, new Set());
1318
+ }
1319
+ this.handlers.get(event)?.add(handler);
1320
+ // console.log(`Registered handler for event: ${event}`);
1321
+ return () => this.off(event, handler);
1322
+ }
1323
+ // Unsubscribe from events
1324
+ off(event, handler) {
1325
+ const handlers = this.handlers.get(event);
1326
+ if (handlers) {
1327
+ handlers.delete(handler);
1328
+ if (handlers.size === 0) {
1329
+ this.handlers.delete(event);
1330
+ }
1331
+ }
1332
+ }
1333
+ // Type-safe event emission with error handling
1334
+ emit(type, data) {
1335
+ try {
1336
+ // Create event with proper type casting
1337
+ const eventData = {
1338
+ ...data,
1339
+ timestamp: Date.now()
1340
+ };
1341
+ const event = {
1342
+ type,
1343
+ ...eventData
1344
+ };
1345
+ // console.log('Emitting event:', event);
1346
+ const handlers = this.handlers.get(type);
1347
+ handlers?.forEach(handler => {
1348
+ try {
1349
+ handler(event);
1350
+ }
1351
+ catch (error) {
1352
+ console.error(`Error in event handler for ${type}:`, error);
1353
+ this.emitError('event_handler_error', error);
1354
+ }
1355
+ });
1356
+ if (this.bridge) {
1357
+ this.sendToHost(event);
1358
+ }
1359
+ }
1360
+ catch (error) {
1361
+ console.error('Error emitting event:', error);
1362
+ this.emitError('event_emission_error', error);
1363
+ }
1364
+ }
1365
+ // Send events to host application
1366
+ sendToHost(event) {
1367
+ const message = {
1368
+ ...event,
1369
+ source: 'widgetic-ui-sdk'
1370
+ };
1371
+ if (this.bridge instanceof MessagePort) {
1372
+ this.bridge.postMessage(message);
1373
+ }
1374
+ else if (typeof window !== 'undefined' && this.bridge && 'postMessage' in this.bridge) {
1375
+ this.bridge.postMessage(message, this.targetOrigin);
1376
+ }
1377
+ }
1378
+ // Convert and emit errors as SDK events
1379
+ emitError(code, error) {
1380
+ const errorEvent = {
1381
+ type: 'messaging:error',
1382
+ error: {
1383
+ message: error.message,
1384
+ code,
1385
+ name: error.name,
1386
+ stack: error.stack,
1387
+ details: error
1388
+ },
1389
+ timestamp: Date.now()
1390
+ };
1391
+ const handlers = this.handlers.get('error');
1392
+ handlers?.forEach(handler => {
1393
+ try {
1394
+ handler(errorEvent);
1395
+ }
1396
+ catch (err) {
1397
+ console.error('Error in error handler:', err);
1398
+ }
1399
+ });
1400
+ }
1401
+ // Cleanup resources and event listeners
1402
+ destroy() {
1403
+ if (this.bridge instanceof MessagePort) {
1404
+ this.bridge.close();
1405
+ }
1406
+ else if (typeof window !== 'undefined' && this.messageListener) {
1407
+ window.removeEventListener('message', this.messageListener);
1408
+ this.messageListener = null;
1409
+ }
1410
+ this.handlers.clear();
1411
+ this.hostHandlers.clear();
1412
+ }
1413
+ }
1414
+
1415
+ class StateManager {
1416
+ constructor(config = {}) {
1417
+ // console.log('Initializing State Manager');
1418
+ this.state = new Map();
1419
+ this.listeners = new Map();
1420
+ this.snapshots = new Map();
1421
+ this.maxSnapshots = config.maxSnapshots || 10;
1422
+ }
1423
+ /**
1424
+ * Update component state with optional snapshot creation and silent updates
1425
+ * @param componentId - Unique identifier for the component
1426
+ * @param key - State property to update
1427
+ * @param value - New value for the state property
1428
+ * @param options - Configuration for state update behavior
1429
+ */
1430
+ setState(componentId, key, value, options = {}) {
1431
+ try {
1432
+ // Initialize component state if not exists
1433
+ if (!this.state.has(componentId)) {
1434
+ this.state.set(componentId, new Map());
1435
+ }
1436
+ const componentState = this.state.get(componentId);
1437
+ const oldValue = componentState.get(key);
1438
+ componentState.set(key, value);
1439
+ // Create state snapshot if requested
1440
+ if (options.snapshot) {
1441
+ this.createSnapshot(componentId);
1442
+ }
1443
+ // Notify listeners unless silent update
1444
+ if (!options.silent) {
1445
+ this.notifyStateChange(componentId, key, value, oldValue);
1446
+ }
1447
+ // console.log(`State updated for ${componentId}.${key}:`, value);
1448
+ }
1449
+ catch (error) {
1450
+ console.error('Error setting state:', error);
1451
+ throw error;
1452
+ }
1453
+ }
1454
+ /**
1455
+ * Retrieve specific state value for a component
1456
+ */
1457
+ getState(componentId, key) {
1458
+ return this.state.get(componentId)?.get(key);
1459
+ }
1460
+ /**
1461
+ * Get entire state map for a component
1462
+ */
1463
+ getComponentState(componentId) {
1464
+ return this.state.get(componentId);
1465
+ }
1466
+ /**
1467
+ * Subscribe to state changes with automatic cleanup
1468
+ */
1469
+ subscribe(componentId, callback) {
1470
+ if (!this.listeners.has(componentId)) {
1471
+ this.listeners.set(componentId, new Set());
1472
+ }
1473
+ this.listeners.get(componentId).add(callback);
1474
+ return () => this.unsubscribe(componentId, callback);
1475
+ }
1476
+ /**
1477
+ * Remove state change subscription
1478
+ */
1479
+ unsubscribe(componentId, callback) {
1480
+ this.listeners.get(componentId)?.delete(callback);
1481
+ }
1482
+ /**
1483
+ * Create a point-in-time snapshot of component state
1484
+ */
1485
+ createSnapshot(componentId) {
1486
+ if (!this.snapshots.has(componentId)) {
1487
+ this.snapshots.set(componentId, []);
1488
+ }
1489
+ const snapshot = {
1490
+ timestamp: Date.now(),
1491
+ state: new Map(this.state.get(componentId))
1492
+ };
1493
+ const componentSnapshots = this.snapshots.get(componentId);
1494
+ componentSnapshots.push(snapshot);
1495
+ // Remove oldest snapshot if limit reached
1496
+ if (componentSnapshots.length > this.maxSnapshots) {
1497
+ componentSnapshots.shift();
1498
+ }
1499
+ }
1500
+ /**
1501
+ * Restore component state from a snapshot
1502
+ * @param index - Optional index of snapshot to restore, defaults to latest
1503
+ */
1504
+ restoreSnapshot(componentId, index = -1) {
1505
+ try {
1506
+ const snapshots = this.snapshots.get(componentId);
1507
+ if (!snapshots?.length)
1508
+ return false;
1509
+ const targetIndex = index < 0 ? snapshots.length - 1 : index;
1510
+ const snapshot = snapshots[targetIndex];
1511
+ if (!snapshot)
1512
+ return false;
1513
+ this.state.set(componentId, new Map(snapshot.state));
1514
+ this.notifyStateChange(componentId, '*', this.getComponentState(componentId));
1515
+ return true;
1516
+ }
1517
+ catch (error) {
1518
+ console.error('Error restoring snapshot:', error);
1519
+ return false;
1520
+ }
1521
+ }
1522
+ /**
1523
+ * Notify all listeners of state changes
1524
+ */
1525
+ notifyStateChange(componentId, key, newValue, oldValue) {
1526
+ const listeners = this.listeners.get(componentId);
1527
+ if (listeners) {
1528
+ listeners.forEach(listener => {
1529
+ try {
1530
+ listener({ componentId, key, newValue, oldValue });
1531
+ }
1532
+ catch (error) {
1533
+ console.error('Error in state change listener:', error);
1534
+ }
1535
+ });
1536
+ }
1537
+ }
1538
+ /**
1539
+ * Clean up resources for specific component or entire system
1540
+ */
1541
+ cleanup(componentId) {
1542
+ if (componentId) {
1543
+ this.state.delete(componentId);
1544
+ this.listeners.delete(componentId);
1545
+ this.snapshots.delete(componentId);
1546
+ }
1547
+ else {
1548
+ this.state.clear();
1549
+ this.listeners.clear();
1550
+ this.snapshots.clear();
1551
+ }
1552
+ }
1553
+ }
1554
+
1555
+ // Default light theme configuration
1556
+ const DEFAULT_THEME = {
1557
+ mode: 'light',
1558
+ colors: {
1559
+ primary: '#007bff',
1560
+ secondary: '#6c757d',
1561
+ background: '#ffffff',
1562
+ surface: '#f8f9fa',
1563
+ text: '#212529',
1564
+ border: '#dee2e6'
1565
+ },
1566
+ spacing: {
1567
+ unit: 4,
1568
+ scale: [0, 4, 8, 16, 24, 32, 48, 64]
1569
+ },
1570
+ typography: {
1571
+ fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
1572
+ scale: [12, 14, 16, 18, 20, 24, 30, 36, 48, 60]
1573
+ }
1574
+ };
1575
+ // Dark theme variant
1576
+ const DARK_THEME = {
1577
+ colors: {
1578
+ primary: '#3b82f6',
1579
+ secondary: '#64748b',
1580
+ background: '#0f172a',
1581
+ surface: '#1e293b',
1582
+ text: '#f8fafc',
1583
+ border: '#334155'
1584
+ }};
1585
+ class ThemeManager {
1586
+ constructor(events, initialTheme) {
1587
+ this.events = events;
1588
+ this.activePreset = 'default';
1589
+ // console.log('Initializing Theme Manager');
1590
+ this.currentTheme = this.createDefaultTheme();
1591
+ if (initialTheme) {
1592
+ this.updateTheme(initialTheme);
1593
+ }
1594
+ this.setupSystemThemeListener();
1595
+ }
1596
+ /**
1597
+ * Get current theme configuration
1598
+ */
1599
+ getCurrentTheme() {
1600
+ return { ...this.currentTheme };
1601
+ }
1602
+ /**
1603
+ * Update theme with partial configuration
1604
+ */
1605
+ updateTheme(updates) {
1606
+ try {
1607
+ // console.log('Updating theme with:', updates);
1608
+ const newTheme = this.mergeThemes(this.currentTheme, updates);
1609
+ this.validateTheme(newTheme);
1610
+ this.currentTheme = newTheme;
1611
+ this.applyTheme();
1612
+ this.notifyThemeUpdate();
1613
+ }
1614
+ catch (error) {
1615
+ console.error('Error updating theme:', error);
1616
+ throw new Error(`Theme update failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
1617
+ }
1618
+ }
1619
+ /**
1620
+ * Set theme mode (light/dark/system)
1621
+ */
1622
+ setMode(mode) {
1623
+ this.updateTheme({ mode });
1624
+ this.applyColorScheme(mode);
1625
+ }
1626
+ /**
1627
+ * Listen for system theme changes
1628
+ */
1629
+ setupSystemThemeListener() {
1630
+ if (window.matchMedia) {
1631
+ window.matchMedia('(prefers-color-scheme: dark)')
1632
+ .addEventListener('change', e => {
1633
+ if (this.currentTheme.mode === 'system') {
1634
+ this.applyColorScheme(e.matches ? 'dark' : 'light');
1635
+ }
1636
+ });
1637
+ }
1638
+ }
1639
+ /**
1640
+ * Create default theme instance
1641
+ */
1642
+ createDefaultTheme() {
1643
+ return { ...DEFAULT_THEME };
1644
+ }
1645
+ /**
1646
+ * Merge base theme with updates
1647
+ */
1648
+ mergeThemes(base, updates) {
1649
+ return {
1650
+ mode: updates.mode ?? base.mode,
1651
+ colors: updates.colors ? { ...base.colors, ...updates.colors } : base.colors,
1652
+ spacing: updates.spacing ? { ...base.spacing, ...updates.spacing } : base.spacing,
1653
+ typography: updates.typography ? { ...base.typography, ...updates.typography } : base.typography
1654
+ };
1655
+ }
1656
+ /**
1657
+ * Validate theme configuration
1658
+ */
1659
+ validateTheme(theme) {
1660
+ // Validate color values
1661
+ Object.entries(theme.colors).forEach(([key, value]) => {
1662
+ if (!this.isValidColor(value)) {
1663
+ throw new Error(`Invalid color value for ${key}: ${value}`);
1664
+ }
1665
+ });
1666
+ // Validate spacing values
1667
+ if (theme.spacing.unit <= 0) {
1668
+ throw new Error('Spacing unit must be positive');
1669
+ }
1670
+ // Validate typography
1671
+ if (!theme.typography.fontFamily) {
1672
+ throw new Error('Font family is required');
1673
+ }
1674
+ }
1675
+ /**
1676
+ * Validate color format
1677
+ */
1678
+ isValidColor(color) {
1679
+ const colorRegex = /^(#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{8}|rgb\(.*\)|rgba\(.*\)|hsl\(.*\)|hsla\(.*\))$/;
1680
+ return colorRegex.test(color);
1681
+ }
1682
+ /**
1683
+ * Apply color scheme based on mode
1684
+ */
1685
+ applyColorScheme(mode) {
1686
+ const theme = mode === 'dark' ? DARK_THEME : DEFAULT_THEME;
1687
+ this.updateTheme({ colors: theme.colors });
1688
+ }
1689
+ /**
1690
+ * Apply theme to document root
1691
+ */
1692
+ applyTheme() {
1693
+ document.documentElement.style.setProperty('--theme-mode', this.currentTheme.mode);
1694
+ // Apply colors as CSS variables
1695
+ Object.entries(this.currentTheme.colors).forEach(([key, value]) => {
1696
+ document.documentElement.style.setProperty(`--color-${key}`, value);
1697
+ });
1698
+ // Apply spacing scale
1699
+ document.documentElement.style.setProperty('--spacing-unit', `${this.currentTheme.spacing.unit}px`);
1700
+ this.currentTheme.spacing.scale.forEach((value, index) => {
1701
+ document.documentElement.style.setProperty(`--spacing-${index}`, `${value}px`);
1702
+ });
1703
+ // Apply typography settings
1704
+ document.documentElement.style.setProperty('--font-family', this.currentTheme.typography.fontFamily);
1705
+ this.currentTheme.typography.scale.forEach((value, index) => {
1706
+ document.documentElement.style.setProperty(`--font-size-${index}`, `${value}px`);
1707
+ });
1708
+ }
1709
+ /**
1710
+ * Notify listeners of theme updates
1711
+ */
1712
+ notifyThemeUpdate() {
1713
+ this.events.emit('theme:update', {
1714
+ theme: this.currentTheme
1715
+ });
1716
+ }
1717
+ }
1718
+
1719
+ class WidgeticComponent {
1720
+ constructor(container, config) {
1721
+ // console.log('Initializing Widgetic Component:', this.constructor.name);
1722
+ this.container = container;
1723
+ this.config = config;
1724
+ // Initialize component infrastructure
1725
+ this.shadow = this.initializeShadowDOM();
1726
+ this.state = {
1727
+ status: 'initializing',
1728
+ error: null
1729
+ };
1730
+ this.events = config.events;
1731
+ this.id = config.id;
1732
+ // Apply theme if provided
1733
+ if (config.theme) {
1734
+ this.applyTheme(config.theme);
1735
+ }
1736
+ // Listen for theme updates
1737
+ if (this.events) {
1738
+ this.events.on('theme:update', (data) => {
1739
+ const theme = data?.theme || data;
1740
+ if (theme && typeof theme === 'object') {
1741
+ this.applyTheme(theme);
1742
+ }
1743
+ });
1744
+ }
1745
+ }
1746
+ /**
1747
+ * Initialize shadow DOM for component isolation
1748
+ * @private
1749
+ */
1750
+ initializeShadowDOM() {
1751
+ try {
1752
+ return this.container.attachShadow({ mode: 'closed' });
1753
+ }
1754
+ catch (error) {
1755
+ console.error('Error initializing shadow DOM:', error);
1756
+ throw new Error('Failed to initialize component shadow DOM');
1757
+ }
1758
+ }
1759
+ /**
1760
+ * Update component state and notify listeners
1761
+ * @param updates - Partial state updates
1762
+ */
1763
+ setState(updates) {
1764
+ this.state = { ...this.state, ...updates };
1765
+ this.events.emit('state:update', {
1766
+ componentId: this.id,
1767
+ state: this.state
1768
+ });
1769
+ }
1770
+ /**
1771
+ * Handle component errors
1772
+ * @param error - Error to handle
1773
+ */
1774
+ handleError(error) {
1775
+ console.error(`Error in ${this.constructor.name}:`, error);
1776
+ this.setState({
1777
+ status: 'error',
1778
+ error
1779
+ });
1780
+ this.events.emit('error', {
1781
+ componentId: this.id,
1782
+ error
1783
+ });
1784
+ }
1785
+ /**
1786
+ * Apply theme to component using Constructable Stylesheets if supported
1787
+ * @param theme - Theme configuration to apply
1788
+ */
1789
+ applyTheme(theme) {
1790
+ this.container.style.setProperty('--theme-mode', theme.mode);
1791
+ const cssText = `
1792
+ :host {
1793
+ --theme-mode: ${theme.mode};
1794
+ ${Object.entries(theme.colors)
1795
+ .map(([key, value]) => `--color-${key}: ${value};`)
1796
+ .join('\n')}
1797
+ --spacing-unit: ${theme.spacing.unit}px;
1798
+ ${theme.spacing.scale
1799
+ .map((value, index) => `--spacing-${index}: ${value}px;`)
1800
+ .join('\n')}
1801
+ --font-family: ${theme.typography.fontFamily};
1802
+ ${theme.typography.scale
1803
+ .map((value, index) => `--font-size-${index}: ${value}px;`)
1804
+ .join('\n')}
1805
+ }
1806
+ `;
1807
+ // Check for Constructable Stylesheet support
1808
+ if (typeof CSSStyleSheet !== 'undefined' &&
1809
+ 'replaceSync' in CSSStyleSheet.prototype &&
1810
+ this.shadow &&
1811
+ 'adoptedStyleSheets' in this.shadow) {
1812
+ try {
1813
+ if (!this.themeStyleSheet) {
1814
+ this.themeStyleSheet = new CSSStyleSheet();
1815
+ this.shadow.adoptedStyleSheets = [...this.shadow.adoptedStyleSheets, this.themeStyleSheet];
1816
+ }
1817
+ this.themeStyleSheet.replaceSync(cssText);
1818
+ return;
1819
+ }
1820
+ catch {
1821
+ // Fallback to <style> element if replaceSync fails
1822
+ }
1823
+ }
1824
+ // Fallback: update or append single theme <style> element
1825
+ let style = this.shadow.querySelector('style[data-widgetic-theme]');
1826
+ if (!style) {
1827
+ style = document.createElement('style');
1828
+ style.setAttribute('data-widgetic-theme', 'true');
1829
+ this.shadow.appendChild(style);
1830
+ }
1831
+ style.textContent = cssText;
1832
+ }
1833
+ }
1834
+
1835
+ class MessagingSystem {
1836
+ constructor(config) {
1837
+ this.config = config;
1838
+ // Store event handlers for different event types
1839
+ this.handlers = new Map();
1840
+ // Store handlers specifically for host messages
1841
+ this.hostHandlers = new Map();
1842
+ // Bound listener reference for clean teardown
1843
+ this.messageListener = null;
1844
+ try {
1845
+ // console.log('Initializing Messaging System');
1846
+ ValidationUtils.validateConfig(config, ['origin'], 'MessagingSystem.constructor');
1847
+ this.bridge = typeof window !== 'undefined' ? window.parent : {};
1848
+ this.security = config.security;
1849
+ this.setupMessageListener();
1850
+ }
1851
+ catch (error) {
1852
+ throw SDKErrorHandler.handleError(error, 'MessagingSystem.constructor');
1853
+ }
1854
+ }
1855
+ /**
1856
+ * Set up message event listener based on bridge type
1857
+ * Handles both MessagePort and Window message events
1858
+ */
1859
+ setupMessageListener() {
1860
+ this.messageListener = (event) => {
1861
+ try {
1862
+ // Validate incoming messages for security
1863
+ if (!this.validateMessage(event)) {
1864
+ return;
1865
+ }
1866
+ const { type, data } = event.data;
1867
+ const handlers = this.hostHandlers.get(type);
1868
+ if (handlers) {
1869
+ handlers.forEach(handler => {
1870
+ try {
1871
+ handler(data);
1872
+ }
1873
+ catch (error) {
1874
+ console.error(`Error in host event handler for ${type}:`, error);
1875
+ this.emitError('message_handler_error', error);
1876
+ }
1877
+ });
1878
+ }
1879
+ }
1880
+ catch (error) {
1881
+ console.error('Error processing message:', error);
1882
+ this.emitError('message_processing_error', error);
1883
+ }
1884
+ };
1885
+ // Set up appropriate listener based on bridge type
1886
+ if (this.bridge instanceof MessagePort) {
1887
+ this.bridge.onmessage = this.messageListener;
1888
+ }
1889
+ else if (typeof window !== 'undefined') {
1890
+ window.addEventListener('message', this.messageListener);
1891
+ }
1892
+ }
1893
+ /**
1894
+ * Validate incoming messages for security and structure
1895
+ * Checks origin, message format, and source
1896
+ */
1897
+ validateMessage(event) {
1898
+ // Skip validation for MessagePort (already secure)
1899
+ if (this.bridge instanceof MessagePort) {
1900
+ return true;
1901
+ }
1902
+ // Validate message structure
1903
+ if (!event.data || typeof event.data !== 'object') {
1904
+ return false;
1905
+ }
1906
+ const { type, source } = event.data;
1907
+ // Validate required fields
1908
+ if (!type || !source) {
1909
+ return false;
1910
+ }
1911
+ // Validate message source
1912
+ if (source !== 'partner-platform') {
1913
+ return false;
1914
+ }
1915
+ return true;
1916
+ }
1917
+ /**
1918
+ * Subscribe to events with automatic cleanup
1919
+ */
1920
+ on(event, handler) {
1921
+ if (!this.handlers.has(event)) {
1922
+ this.handlers.set(event, new Set());
1923
+ }
1924
+ this.handlers.get(event)?.add(handler);
1925
+ return () => this.off(event, handler);
1926
+ }
1927
+ /**
1928
+ * Remove event subscription
1929
+ */
1930
+ off(event, handler) {
1931
+ this.handlers.get(event)?.delete(handler);
1932
+ }
1933
+ /**
1934
+ * Emit events with type-safe payload
1935
+ * Handles both local events and host communication
1936
+ */
1937
+ emit(type, data) {
1938
+ try {
1939
+ // Create event with proper type casting
1940
+ const eventData = {
1941
+ ...data,
1942
+ timestamp: Date.now()
1943
+ };
1944
+ const event = {
1945
+ type,
1946
+ ...eventData
1947
+ };
1948
+ // console.log('Emitting event:', event);
1949
+ // Notify all registered handlers
1950
+ const handlers = this.handlers.get(type);
1951
+ handlers?.forEach(handler => {
1952
+ try {
1953
+ handler(event);
1954
+ }
1955
+ catch (error) {
1956
+ console.error(`Error in event handler for ${type}:`, error);
1957
+ this.emitError('event_handler_error', error);
1958
+ }
1959
+ });
1960
+ // Forward to host if bridge exists
1961
+ if (this.bridge) {
1962
+ this.sendToHost(event);
1963
+ }
1964
+ }
1965
+ catch (error) {
1966
+ console.error('Error emitting event:', error);
1967
+ this.emitError('event_emission_error', error);
1968
+ }
1969
+ }
1970
+ /**
1971
+ * Send message to host application
1972
+ * Handles different bridge types appropriately
1973
+ */
1974
+ sendToHost(event) {
1975
+ const message = {
1976
+ ...event,
1977
+ source: 'widgetic-ui-sdk'
1978
+ };
1979
+ if (this.bridge instanceof MessagePort) {
1980
+ this.bridge.postMessage(message);
1981
+ }
1982
+ else if (typeof window !== 'undefined' && this.bridge && 'postMessage' in this.bridge) {
1983
+ this.bridge.postMessage(message, this.config.origin || window.location.origin);
1984
+ }
1985
+ }
1986
+ /**
1987
+ * Handle and emit error events
1988
+ */
1989
+ emitError(code, error) {
1990
+ const errorEvent = {
1991
+ type: 'messaging:error',
1992
+ error: {
1993
+ message: error.message,
1994
+ code,
1995
+ name: error.name,
1996
+ stack: error.stack,
1997
+ details: error
1998
+ },
1999
+ timestamp: Date.now()
2000
+ };
2001
+ const handlers = this.handlers.get('error');
2002
+ handlers?.forEach(handler => {
2003
+ try {
2004
+ handler(errorEvent);
2005
+ }
2006
+ catch (err) {
2007
+ console.error('Error in error handler:', err);
2008
+ }
2009
+ });
2010
+ }
2011
+ /**
2012
+ * Clean up resources and event listeners
2013
+ */
2014
+ destroy() {
2015
+ if (this.bridge instanceof MessagePort) {
2016
+ this.bridge.close();
2017
+ }
2018
+ else if (typeof window !== 'undefined' && this.messageListener) {
2019
+ window.removeEventListener('message', this.messageListener);
2020
+ this.messageListener = null;
2021
+ }
2022
+ this.handlers.clear();
2023
+ this.hostHandlers.clear();
2024
+ }
2025
+ }
2026
+
2027
+ /**
2028
+ * Core Module Index
2029
+ * Exports all core components of the UI SDK.
2030
+ * These components form the foundation of the SDK's functionality.
2031
+ */
2032
+ // Event System: Handles all inter-component communication and host messaging
2033
+ /**
2034
+ * Core Component Architecture:
2035
+ *
2036
+ * - EventSystem: Central event bus for all component communication
2037
+ * - StateManager: Manages component state and provides undo/redo functionality
2038
+ * - ThemeManager: Handles theme configuration and system-wide style updates
2039
+ * - WidgeticComponent: Base class providing core component functionality
2040
+ * - LifecycleManager: Controls component instantiation and cleanup
2041
+ * - MessagingSystem: Handles secure host-component communication
2042
+ *
2043
+ * These components work together to provide:
2044
+ * 1. Secure component isolation
2045
+ * 2. Type-safe event handling
2046
+ * 3. Centralized state management
2047
+ * 4. Consistent theming
2048
+ * 5. Proper resource cleanup
2049
+ * 6. Cross-origin communication
2050
+ */
2051
+ class Core {
2052
+ constructor() {
2053
+ // console.log('Initializing UI SDK core');
2054
+ }
2055
+ }
2056
+
2057
+ class HostCommunication {
2058
+ /**
2059
+ * Initialize host communication system
2060
+ * @param origin - Allowed origin for message validation
2061
+ * @param events - Event emitter for SDK-wide communication
2062
+ * @param security - Security manager instance
2063
+ */
2064
+ constructor(origin, events, security) {
2065
+ this.origin = origin;
2066
+ this.events = events;
2067
+ // Stable bound listener reference for event removal
2068
+ this.boundHandleMessage = (event) => {
2069
+ this.handleMessage(event);
2070
+ };
2071
+ // console.log('Initializing Host Communication');
2072
+ this.security = security;
2073
+ this.setupMessageHandling();
2074
+ }
2075
+ /**
2076
+ * Set up message event listener for host communication
2077
+ * Binds message handler to window events
2078
+ * @private
2079
+ */
2080
+ setupMessageHandling() {
2081
+ if (typeof window !== 'undefined') {
2082
+ window.addEventListener('message', this.boundHandleMessage);
2083
+ }
2084
+ }
2085
+ /**
2086
+ * Handle incoming messages from host application
2087
+ * Validates messages and routes events to appropriate handlers
2088
+ * @param event - Message event from host
2089
+ * @private
2090
+ */
2091
+ handleMessage(event) {
2092
+ try {
2093
+ // Skip invalid messages
2094
+ if (!this.validateMessage(event)) {
2095
+ return;
2096
+ }
2097
+ // Extract and emit event data
2098
+ const { type, data } = event.data;
2099
+ this.events.emit(type, data);
2100
+ }
2101
+ catch (error) {
2102
+ console.error('Error handling message:', error);
2103
+ this.events.emit('error', {
2104
+ componentId: 'host-communication',
2105
+ error: error instanceof Error ? error : new Error('Message handling failed')
2106
+ });
2107
+ }
2108
+ }
2109
+ /**
2110
+ * Validate incoming messages for security
2111
+ * Checks origin and message structure
2112
+ * @param event - Message event to validate
2113
+ * @returns boolean indicating message validity
2114
+ * @private
2115
+ */
2116
+ validateMessage(event) {
2117
+ // Verify message origin
2118
+ if (event.origin !== this.origin) {
2119
+ return false;
2120
+ }
2121
+ // Validate message structure and content
2122
+ if (!this.security.validateMessage(event)) {
2123
+ return false;
2124
+ }
2125
+ return true;
2126
+ }
2127
+ /**
2128
+ * Create secure communication channel with host
2129
+ * Uses MessageChannel API for secure bi-directional communication
2130
+ * @returns Promise that resolves when channel is established
2131
+ */
2132
+ async createSecureChannel() {
2133
+ // Create new message channel
2134
+ const channel = new MessageChannel();
2135
+ // Send port to host application
2136
+ window.parent.postMessage({ type: 'secure-channel-request' }, this.origin, [
2137
+ channel.port2
2138
+ ]);
2139
+ // Set up channel message handling
2140
+ this.channel = channel.port1;
2141
+ this.channel.onmessage = this.boundHandleMessage;
2142
+ }
2143
+ /**
2144
+ * Clean up resources and event listeners
2145
+ * Called when host communication is no longer needed
2146
+ */
2147
+ destroy() {
2148
+ if (typeof window !== 'undefined') {
2149
+ window.removeEventListener('message', this.boundHandleMessage);
2150
+ }
2151
+ this.channel?.close();
2152
+ }
2153
+ }
2154
+
2155
+ /**
2156
+ * HTTP helpers
2157
+ *
2158
+ * Small request/response helpers. The SDK itself makes no authenticated API calls: the UI modules talk to the
2159
+ * Widgetic API with the editor session token the partner's `getToken` returns. A browser-side HTTP client that
2160
+ * attached an API key to requests used to live here; it was removed so an API key can never end up in a browser.
2161
+ */
2162
+ /**
2163
+ * Create a secure HTTP request
2164
+ * @param url - Request URL
2165
+ * @param options - Request options
2166
+ * @returns Configured request
2167
+ */
2168
+ function createSecureRequest(url, options = {}) {
2169
+ const headers = new Headers(options.headers);
2170
+ // Add security headers
2171
+ headers.set('X-Requested-With', 'XMLHttpRequest');
2172
+ return new Request(url, {
2173
+ ...options,
2174
+ headers,
2175
+ credentials: 'same-origin',
2176
+ });
2177
+ }
2178
+ /**
2179
+ * Validate HTTP response
2180
+ * @param response - Response to validate
2181
+ * @returns True if response is valid
2182
+ */
2183
+ function validateResponse(response) {
2184
+ // Check status
2185
+ if (!response.ok) {
2186
+ return false;
2187
+ }
2188
+ // Check content type for JSON responses
2189
+ const contentType = response.headers.get('content-type');
2190
+ if (contentType && !contentType.includes('application/json')) {
2191
+ console.warn('Unexpected content type:', contentType);
2192
+ }
2193
+ return true;
2194
+ }
2195
+
2196
+ /**
2197
+ * Security Manager
2198
+ *
2199
+ * Provides core security features for the UI SDK including:
2200
+ * - Content Security Policy (CSP) configuration
2201
+ * - Request origin validation
2202
+ * - CSRF protection
2203
+ * - Development environment support
2204
+ *
2205
+ * Usage:
2206
+ * ```typescript
2207
+ * const security = new SecurityManager(['allowed-domain.com']);
2208
+ * security.validateRequest(request);
2209
+ * ```
2210
+ *
2211
+ * CSP is automatically configured on instantiation.
2212
+ */
2213
+ class SecurityManager {
2214
+ /**
2215
+ * Validate domain against allowed list
2216
+ * @param domain - Domain to validate
2217
+ * @returns boolean indicating if domain is valid
2218
+ */
2219
+ validateDomain(domain) {
2220
+ if (!domain || typeof domain !== 'string') {
2221
+ return false;
2222
+ }
2223
+ // Clean domain format
2224
+ const cleanDomain = domain.replace(/^https?:\/\//i, '').replace(/\/.*$/, '').toLowerCase();
2225
+ // Always allow Widgetic domains
2226
+ if (cleanDomain === 'widgetic.com' || cleanDomain.endsWith('.widgetic.com')) {
2227
+ return true;
2228
+ }
2229
+ // Allow development domains in non-production
2230
+ if (!config.isProduction) {
2231
+ if (this.ALLOWED_DEV_ORIGINS.includes(cleanDomain)) {
2232
+ return true;
2233
+ }
2234
+ }
2235
+ // Check against allowed origins
2236
+ return this.allowedOrigins.some(allowed => {
2237
+ if (allowed === '*')
2238
+ return true;
2239
+ const cleanAllowed = allowed.replace(/^https?:\/\//i, '').replace(/\/.*$/, '').toLowerCase();
2240
+ if (cleanAllowed.startsWith('*.')) {
2241
+ const domainPart = cleanAllowed.slice(2);
2242
+ return cleanDomain === domainPart || cleanDomain.endsWith('.' + domainPart);
2243
+ }
2244
+ return cleanDomain === cleanAllowed;
2245
+ });
2246
+ }
2247
+ /**
2248
+ * Initialize security manager
2249
+ * Sets up CSP and configures allowed origins
2250
+ * @param allowedOrigins - List of allowed origins
2251
+ */
2252
+ constructor(allowedOrigins = []) {
2253
+ this.allowedOrigins = allowedOrigins;
2254
+ /**
2255
+ * Development CSP Configuration
2256
+ * Relaxed rules for local development
2257
+ * @private
2258
+ */
2259
+ this.DEVELOPMENT_CSP = {
2260
+ defaultSrc: ["'self'", 'http://localhost:*'],
2261
+ scriptSrc: [
2262
+ "'self'",
2263
+ "'unsafe-eval'", // Required for dev tools
2264
+ 'http://localhost:*',
2265
+ DEFAULT_CONFIG.CDN_URL,
2266
+ 'https://*.widgetic.com'
2267
+ ],
2268
+ styleSrc: ["'self'", "'unsafe-inline'", 'http://localhost:*'],
2269
+ imgSrc: ["'self'", 'data:', 'https:', 'http://localhost:*'],
2270
+ connectSrc: [
2271
+ "'self'",
2272
+ 'http://localhost:*',
2273
+ 'ws://localhost:*', // For HMR
2274
+ DEFAULT_CONFIG.API_URL,
2275
+ 'https://*.widgetic.com'
2276
+ ],
2277
+ frameAncestors: ["'self'", 'http://localhost:*'],
2278
+ };
2279
+ /**
2280
+ * Production CSP Configuration
2281
+ * Strict rules for production environment
2282
+ * @private
2283
+ */
2284
+ this.PRODUCTION_CSP = {
2285
+ defaultSrc: ["'self'"],
2286
+ scriptSrc: [
2287
+ "'self'",
2288
+ DEFAULT_CONFIG.CDN_URL,
2289
+ 'https://*.widgetic.com'
2290
+ ],
2291
+ styleSrc: ["'self'", "'unsafe-inline'"],
2292
+ imgSrc: ["'self'", 'data:', 'https:'],
2293
+ connectSrc: [
2294
+ "'self'",
2295
+ DEFAULT_CONFIG.API_URL,
2296
+ 'https://*.widgetic.com'
2297
+ ],
2298
+ frameAncestors: ["'self'"],
2299
+ };
2300
+ /**
2301
+ * Allowed Development Origins
2302
+ * Origins that are always allowed in development
2303
+ * @private
2304
+ */
2305
+ this.ALLOWED_DEV_ORIGINS = [
2306
+ 'localhost',
2307
+ '127.0.0.1',
2308
+ DEFAULT_CONFIG.CLIENT_URL,
2309
+ 'null' // For file:// protocol testing
2310
+ ];
2311
+ this.setupCSP();
2312
+ }
2313
+ /**
2314
+ * Set up Content Security Policy
2315
+ * In an embedded UI SDK, injecting top-level document CSP meta tags
2316
+ * can interfere with the host application. Boundaries are maintained
2317
+ * via iframe isolation and shadow DOM scoping.
2318
+ * @private
2319
+ */
2320
+ setupCSP() {
2321
+ // Preserved as safe no-op to prevent host application pollution
2322
+ }
2323
+ /**
2324
+ * Build CSP directive string
2325
+ * Converts CSP config to valid directive string
2326
+ * @private
2327
+ */
2328
+ buildCSPString() {
2329
+ const cspConfig = config.isProduction ?
2330
+ this.PRODUCTION_CSP :
2331
+ this.DEVELOPMENT_CSP;
2332
+ const directives = [];
2333
+ for (const [key, values] of Object.entries(cspConfig)) {
2334
+ if (values && values.length) {
2335
+ const directive = key.replace(/([A-Z])/g, '-$1').toLowerCase();
2336
+ directives.push(`${directive} ${values.join(' ')}`);
2337
+ }
2338
+ }
2339
+ return directives.join('; ');
2340
+ }
2341
+ /**
2342
+ * Validate request origin
2343
+ * Checks if origin is allowed to make requests
2344
+ * @param origin - Request origin to validate
2345
+ */
2346
+ validateOrigin(origin) {
2347
+ if (!origin || typeof origin !== 'string') {
2348
+ return false;
2349
+ }
2350
+ if (origin === 'null') {
2351
+ return !config.isProduction;
2352
+ }
2353
+ let hostname;
2354
+ try {
2355
+ hostname = new URL(origin.startsWith('http') ? origin : `https://${origin}`).hostname.toLowerCase();
2356
+ }
2357
+ catch {
2358
+ hostname = origin.replace(/^https?:\/\//i, '').replace(/\/.*$/, '').toLowerCase();
2359
+ }
2360
+ // Allow development origins in non-production
2361
+ if (!config.isProduction) {
2362
+ if (this.ALLOWED_DEV_ORIGINS.includes(hostname)) {
2363
+ return true;
2364
+ }
2365
+ }
2366
+ // Always allow Widgetic domains
2367
+ if (hostname === 'widgetic.com' || hostname.endsWith('.widgetic.com')) {
2368
+ return true;
2369
+ }
2370
+ // Check against allowed origins
2371
+ return this.allowedOrigins.some(allowed => {
2372
+ if (allowed === '*')
2373
+ return true;
2374
+ const cleanAllowed = allowed.replace(/^https?:\/\//i, '').replace(/\/.*$/, '').toLowerCase();
2375
+ if (cleanAllowed.startsWith('*.')) {
2376
+ const domain = cleanAllowed.slice(2);
2377
+ return hostname === domain || hostname.endsWith('.' + domain);
2378
+ }
2379
+ return hostname === cleanAllowed || origin.toLowerCase() === allowed.toLowerCase();
2380
+ });
2381
+ }
2382
+ /**
2383
+ * Validate HTTP request
2384
+ * Checks origin and CSRF token
2385
+ * @param request - Request to validate
2386
+ */
2387
+ validateRequest(request) {
2388
+ const origin = request.headers.get('origin');
2389
+ // Handle same-origin requests
2390
+ if (!origin && !config.isProduction) {
2391
+ return true; // Allow in development
2392
+ }
2393
+ if (!origin)
2394
+ return false;
2395
+ // Validate origin
2396
+ if (!this.validateOrigin(origin)) {
2397
+ console.warn(`Invalid request origin: ${origin}`);
2398
+ return false;
2399
+ }
2400
+ // Skip CSRF validation in development
2401
+ if (!config.isProduction) {
2402
+ return true;
2403
+ }
2404
+ // Validate CSRF token if present
2405
+ const csrfToken = request.headers.get('x-csrf-token');
2406
+ if (csrfToken && !this.validateCSRFToken(csrfToken)) {
2407
+ console.warn('Invalid CSRF token');
2408
+ return false;
2409
+ }
2410
+ return true;
2411
+ }
2412
+ /**
2413
+ * Validate CSRF token
2414
+ * Placeholder for CSRF token validation
2415
+ * @private
2416
+ */
2417
+ validateCSRFToken(token) {
2418
+ // TODO: Implement CSRF token validation
2419
+ return true;
2420
+ }
2421
+ /**
2422
+ * Validate message event
2423
+ * Checks message structure and content
2424
+ * @param event - Message event to validate
2425
+ */
2426
+ validateMessage(event) {
2427
+ // Verify message has data
2428
+ if (!event.data) {
2429
+ console.warn('Invalid message: missing data');
2430
+ return false;
2431
+ }
2432
+ // Verify message has required properties
2433
+ const { type, data } = event.data;
2434
+ if (!type || typeof type !== 'string') {
2435
+ console.warn('Invalid message: missing or invalid type');
2436
+ return false;
2437
+ }
2438
+ // Verify data is an object
2439
+ if (data && typeof data !== 'object') {
2440
+ console.warn('Invalid message: data must be an object');
2441
+ return false;
2442
+ }
2443
+ return true;
2444
+ }
2445
+ }
2446
+ /**
2447
+ * Validate origin against allowed list
2448
+ * @param origin - Origin to validate
2449
+ * @param allowedOrigins - List of allowed origins
2450
+ * @returns True if origin is valid
2451
+ */
2452
+ function validateOrigin(origin, allowedOrigins = []) {
2453
+ const security = new SecurityManager(allowedOrigins);
2454
+ return security.validateOrigin(origin);
2455
+ }
2456
+ /**
2457
+ * Sanitize input string
2458
+ * @param input - Input to sanitize
2459
+ * @returns Sanitized input
2460
+ */
2461
+ function sanitizeInput(input) {
2462
+ if (typeof input !== 'string') {
2463
+ return '';
2464
+ }
2465
+ // Remove potentially dangerous characters
2466
+ return input
2467
+ .replace(/[<>]/g, '') // Remove angle brackets
2468
+ .replace(/javascript:/gi, '') // Remove javascript: protocol
2469
+ .replace(/on\w+=/gi, '') // Remove event handlers
2470
+ .trim();
2471
+ }
2472
+ /**
2473
+ * Create secure context for iframe communication
2474
+ * @param allowedOrigins - List of allowed origins
2475
+ * @returns Security context
2476
+ */
2477
+ function createSecureContext(allowedOrigins = []) {
2478
+ const security = new SecurityManager(allowedOrigins);
2479
+ return {
2480
+ validateMessage: (event) => security.validateMessage(event),
2481
+ validateOrigin: (origin) => security.validateOrigin(origin),
2482
+ sanitizeInput,
2483
+ };
2484
+ }
2485
+
2486
+ /**
2487
+ * Version and name of the SDK.
2488
+ *
2489
+ * Keep `SDK_VERSION` equal to "version" in package.json; `tests/unit/version.test.ts` fails when they differ.
2490
+ */
2491
+ const SDK_VERSION = '0.1.0';
2492
+ const SDK_NAME = '@widgetic/ui-sdk';
2493
+
2494
+ /**
2495
+ * Widgetic UI SDK
2496
+ * Framework-agnostic loader for Widgetic's UI modules.
2497
+ *
2498
+ * This SDK puts Widgetic's UI on a partner's page:
2499
+ * - File browsing and uploads
2500
+ * - Widget creation and editing
2501
+ * - Composition editing
2502
+ *
2503
+ * Compatible with any framework or vanilla JavaScript.
2504
+ *
2505
+ * import { mountModule } from '@widgetic/ui-sdk';
2506
+ *
2507
+ * const fileBrowser = await mountModule('file-browser', {
2508
+ * container: document.getElementById('files'),
2509
+ * getToken: async () => (await fetch('/my-server/widgetic-session')).json(),
2510
+ * on: { select: ({ files }) => useFiles(files) },
2511
+ * });
2512
+ *
2513
+ * The SDK holds no credentials: the partner's server mints a short-lived editor session token and `getToken`
2514
+ * returns it. An API key never belongs in a browser.
2515
+ */
2516
+ // The loader: the supported way to use the SDK
2517
+ /**
2518
+ * Default export for convenience
2519
+ */
2520
+ var index = {
2521
+ SDK_VERSION,
2522
+ SDK_NAME,
2523
+ WidgeticUI,
2524
+ mountModule,
2525
+ HighLevelUIAPI,
2526
+ };
2527
+
2528
+ exports.ComponentError = ComponentError;
2529
+ exports.ConfigManager = ConfigManager;
2530
+ exports.Core = Core;
2531
+ exports.DEFAULT_API_URL = DEFAULT_API_URL;
2532
+ exports.DEFAULT_CONFIG = DEFAULT_CONFIG;
2533
+ exports.DEFAULT_MODULE_BASE_URL = DEFAULT_MODULE_BASE_URL;
2534
+ exports.EventSystem = EventSystem;
2535
+ exports.HighLevelUIAPI = HighLevelUIAPI;
2536
+ exports.HostCommunication = HostCommunication;
2537
+ exports.LifecycleManager = LifecycleManager;
2538
+ exports.MessagingSystem = MessagingSystem;
2539
+ exports.ModuleLoadError = ModuleLoadError;
2540
+ exports.ModuleLoader = ModuleLoader;
2541
+ exports.ModuleMountError = ModuleMountError;
2542
+ exports.SDK_NAME = SDK_NAME;
2543
+ exports.SDK_VERSION = SDK_VERSION;
2544
+ exports.SecurityError = SecurityError;
2545
+ exports.StateManager = StateManager;
2546
+ exports.ThemeManager = ThemeManager;
2547
+ exports.UILoader = WidgeticUI;
2548
+ exports.ValidationError = ValidationError;
2549
+ exports.WidgeticComponent = WidgeticComponent;
2550
+ exports.WidgeticUI = WidgeticUI;
2551
+ exports.config = config;
2552
+ exports.createSecureContext = createSecureContext;
2553
+ exports.createSecureRequest = createSecureRequest;
2554
+ exports.default = index;
2555
+ exports.mountModule = mountModule;
2556
+ exports.sanitizeInput = sanitizeInput;
2557
+ exports.validateOrigin = validateOrigin;
2558
+ exports.validateResponse = validateResponse;
2559
+ //# sourceMappingURL=index.js.map