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