@wix/editor-application 1.308.0

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 (50) hide show
  1. package/README.md +1 -0
  2. package/dist/cjs/environment-api/index.js +584 -0
  3. package/dist/cjs/environment-api/index.js.map +1 -0
  4. package/dist/cjs/index.js +773 -0
  5. package/dist/cjs/index.js.map +1 -0
  6. package/dist/cjs/platform-frame/index.js +368 -0
  7. package/dist/cjs/platform-frame/index.js.map +1 -0
  8. package/dist/cjs/platform-frame-api/index.js +341 -0
  9. package/dist/cjs/platform-frame-api/index.js.map +1 -0
  10. package/dist/cjs/platform-worker/index.js +552 -0
  11. package/dist/cjs/platform-worker/index.js.map +1 -0
  12. package/dist/cjs/platform-worker-api/index.js +550 -0
  13. package/dist/cjs/platform-worker-api/index.js.map +1 -0
  14. package/dist/esm/environment-api/index.js +579 -0
  15. package/dist/esm/environment-api/index.js.map +1 -0
  16. package/dist/esm/index.js +764 -0
  17. package/dist/esm/index.js.map +1 -0
  18. package/dist/esm/platform-frame/index.js +366 -0
  19. package/dist/esm/platform-frame/index.js.map +1 -0
  20. package/dist/esm/platform-frame-api/index.js +339 -0
  21. package/dist/esm/platform-frame-api/index.js.map +1 -0
  22. package/dist/esm/platform-worker/index.js +550 -0
  23. package/dist/esm/platform-worker/index.js.map +1 -0
  24. package/dist/esm/platform-worker-api/index.js +548 -0
  25. package/dist/esm/platform-worker-api/index.js.map +1 -0
  26. package/dist/statics/environment-api/index.js +586 -0
  27. package/dist/statics/environment-api/index.js.map +1 -0
  28. package/dist/statics/index.js +775 -0
  29. package/dist/statics/index.js.map +1 -0
  30. package/dist/statics/platform-frame/index.js +369 -0
  31. package/dist/statics/platform-frame/index.js.map +1 -0
  32. package/dist/statics/platform-frame-api/index.js +344 -0
  33. package/dist/statics/platform-frame-api/index.js.map +1 -0
  34. package/dist/statics/platform-worker/index.js +553 -0
  35. package/dist/statics/platform-worker/index.js.map +1 -0
  36. package/dist/statics/platform-worker-api/index.js +552 -0
  37. package/dist/statics/platform-worker-api/index.js.map +1 -0
  38. package/dist/types/environment-api/index.d.ts +27 -0
  39. package/dist/types/environment-api/index.d.ts.map +1 -0
  40. package/dist/types/index.d.ts +253 -0
  41. package/dist/types/index.d.ts.map +1 -0
  42. package/dist/types/platform-frame/index.d.ts +27 -0
  43. package/dist/types/platform-frame/index.d.ts.map +1 -0
  44. package/dist/types/platform-frame-api/index.d.ts +27 -0
  45. package/dist/types/platform-frame-api/index.d.ts.map +1 -0
  46. package/dist/types/platform-worker/index.d.ts +27 -0
  47. package/dist/types/platform-worker/index.d.ts.map +1 -0
  48. package/dist/types/platform-worker-api/index.d.ts +27 -0
  49. package/dist/types/platform-worker-api/index.d.ts.map +1 -0
  50. package/package.json +96 -0
@@ -0,0 +1,764 @@
1
+ import { PlatformAppEvent, PlatformPrivateEvent, PlatformLifecycleEvent, PlatformAppEventEmitter } from '@wix/public-editor-platform-events';
2
+ import { EventType } from '@wix/public-editor-platform-interfaces';
3
+ import { createErrorBuilder, BaseError } from '@wix/public-editor-platform-errors';
4
+
5
+ class ApplicationLifecycle {
6
+ constructor(events) {
7
+ this.events = events;
8
+ this.subscribe();
9
+ }
10
+ callbacks = {};
11
+ subscribe() {
12
+ this.events.subscribe((event) => {
13
+ const { type, payload } = event;
14
+ if (this.callbacks[type]) {
15
+ this.callbacks[type].forEach(({ fn }) => fn(payload));
16
+ }
17
+ });
18
+ }
19
+ addCallback(event, fn) {
20
+ if (!this.callbacks[event]) {
21
+ this.callbacks[event] = [];
22
+ }
23
+ const id = `${performance.now()}`;
24
+ this.callbacks[event].push({
25
+ id,
26
+ fn
27
+ });
28
+ return () => {
29
+ this.callbacks[event] = this.callbacks[event].filter(
30
+ (cb) => cb.id !== id
31
+ );
32
+ };
33
+ }
34
+ /**
35
+ * NOTE: currently, we return function to unsubscribe from the event,
36
+ * probably it is better to return `this` to allow chaining
37
+ * and provide another way to unsubscribe from events.
38
+ */
39
+ onEditorReady(fn) {
40
+ return this.addCallback(PlatformAppEvent.EditorReady, fn);
41
+ }
42
+ }
43
+
44
+ var EditorPlatformApplicationErrorCode = /* @__PURE__ */ ((EditorPlatformApplicationErrorCode2) => {
45
+ EditorPlatformApplicationErrorCode2["ApplicationRuntimeError"] = "ApplicationRuntimeError";
46
+ EditorPlatformApplicationErrorCode2["ApplicationCreationError"] = "ApplicationCreationError";
47
+ EditorPlatformApplicationErrorCode2["ApplicationLoadError"] = "ApplicationLoadError";
48
+ EditorPlatformApplicationErrorCode2["ApplicationFetchError"] = "ApplicationFetchError";
49
+ EditorPlatformApplicationErrorCode2["ApplicationExecuteError"] = "ApplicationExecuteError";
50
+ EditorPlatformApplicationErrorCode2["ApplicationWasRemoved"] = "ApplicationWasRemoved";
51
+ EditorPlatformApplicationErrorCode2["UndefinedApiMethod"] = "UndefinedApiMethod";
52
+ EditorPlatformApplicationErrorCode2["ApplicationIsNotMutable"] = "ApplicationIsNotMutable";
53
+ EditorPlatformApplicationErrorCode2["FailedToGetPrivateAPI"] = "FailedToGetPrivateAPI";
54
+ return EditorPlatformApplicationErrorCode2;
55
+ })(EditorPlatformApplicationErrorCode || {});
56
+ class EditorPlatformApplicationError extends BaseError {
57
+ state = {};
58
+ constructor(message, code) {
59
+ super(message, code, "Editor Platform Application Error");
60
+ }
61
+ withUrl(url) {
62
+ this.state = { ...this.state, url };
63
+ return this;
64
+ }
65
+ withAppDefinitionId(appDefinitionId) {
66
+ this.state = { ...this.state, appDefinitionId };
67
+ return this;
68
+ }
69
+ withApiMethod(apiMethod) {
70
+ this.state = { ...this.state, apiMethod };
71
+ return this;
72
+ }
73
+ withApiType(apiType) {
74
+ this.state = { ...this.state, apiType };
75
+ return this;
76
+ }
77
+ }
78
+ const createEditorPlatformApplicationError = createErrorBuilder(EditorPlatformApplicationError);
79
+
80
+ class ChainAPIConfiguration {
81
+ constructor(api) {
82
+ this.api = api;
83
+ }
84
+ exposePublicAPI(api) {
85
+ this.api.public = api;
86
+ return this;
87
+ }
88
+ exposePrivateAPI(api) {
89
+ this.api.private = api;
90
+ return this;
91
+ }
92
+ }
93
+ class EditorPlatformApplication {
94
+ constructor(type, context) {
95
+ this.type = type;
96
+ this.#context = context;
97
+ const bindings = this.#context.getBindings();
98
+ this.appDefinitionId = bindings.appDefinitionId;
99
+ const events = this.#context.getEvents();
100
+ this.lifecycle = new ApplicationLifecycle(events);
101
+ events.addEventListener(EventType.removeAppCompleted, (e) => {
102
+ if (e.appDefinitionId === this.appDefinitionId) {
103
+ this.state = "REMOVED";
104
+ }
105
+ });
106
+ const registerApplicationInContainer = __APPLICATION_REGISTRY_KEY;
107
+ registerApplicationInContainer(this);
108
+ events.notify({
109
+ type: PlatformAppEvent.ApplicationInit,
110
+ payload: {}
111
+ });
112
+ }
113
+ appDefinitionId;
114
+ state = "READY";
115
+ lifecycle;
116
+ #applicationAPI = {};
117
+ #chainAPIConfiguration = new ChainAPIConfiguration(
118
+ this.#applicationAPI
119
+ );
120
+ #manifest;
121
+ #context;
122
+ get context() {
123
+ return this.#context;
124
+ }
125
+ get events() {
126
+ return this.#context.getEvents();
127
+ }
128
+ setManifest(manifest) {
129
+ this.#manifest = manifest;
130
+ }
131
+ getManifest() {
132
+ return this.#manifest;
133
+ }
134
+ exposePublicAPI(api) {
135
+ return this.#chainAPIConfiguration.exposePublicAPI(api);
136
+ }
137
+ exposePrivateAPI(api) {
138
+ return this.#chainAPIConfiguration.exposePrivateAPI(api);
139
+ }
140
+ getPublicAPI() {
141
+ return this.#applicationAPI.public;
142
+ }
143
+ getPrivateAPI() {
144
+ return this.#applicationAPI.private;
145
+ }
146
+ ready() {
147
+ }
148
+ buildApplicationError(message) {
149
+ return createEditorPlatformApplicationError(
150
+ EditorPlatformApplicationErrorCode.ApplicationRuntimeError,
151
+ message
152
+ ).withAppDefinitionId(this.appDefinitionId);
153
+ }
154
+ }
155
+
156
+ var EditorPlatformApplicationContextErrorCode = /* @__PURE__ */ ((EditorPlatformApplicationContextErrorCode2) => {
157
+ EditorPlatformApplicationContextErrorCode2["IncorrectEnvironment"] = "IncorrectEnvironment";
158
+ return EditorPlatformApplicationContextErrorCode2;
159
+ })(EditorPlatformApplicationContextErrorCode || {});
160
+ class EditorPlatformApplicationContextError extends BaseError {
161
+ state = {};
162
+ constructor(message, code) {
163
+ super(message, code, "Editor Platform Application Context Error");
164
+ }
165
+ withUrl(url) {
166
+ this.state = { ...this.state, url };
167
+ return this;
168
+ }
169
+ withAppDefinitionId(appDefinitionId) {
170
+ this.state = { ...this.state, appDefinitionId };
171
+ return this;
172
+ }
173
+ }
174
+ const createEditorPlatformApplicationContextError = createErrorBuilder(EditorPlatformApplicationContextError);
175
+ async function transformEventPayload(eventPayload, privateAPI) {
176
+ if (!eventPayload?.type) {
177
+ return eventPayload;
178
+ }
179
+ switch (eventPayload.type) {
180
+ case "componentSelectionChanged":
181
+ const componentRefs = eventPayload.componentRefs || [];
182
+ const components = await Promise.all(
183
+ componentRefs.map((ref) => {
184
+ return privateAPI.components.getComponent(ref);
185
+ })
186
+ );
187
+ return {
188
+ type: eventPayload.type,
189
+ components
190
+ };
191
+ default:
192
+ return eventPayload;
193
+ }
194
+ }
195
+ class ApplicationBoundEvents {
196
+ constructor(appDefinitionId, events, privateAPI) {
197
+ this.appDefinitionId = appDefinitionId;
198
+ this.privateAPI = privateAPI;
199
+ this.events = events;
200
+ this.subscribe = events.subscribe.bind(events);
201
+ this.commit = events.commit.bind(events);
202
+ this.startTransaction = events.startTransaction.bind(events);
203
+ this.silent = events.silent.bind(events);
204
+ }
205
+ events;
206
+ subscribe;
207
+ commit;
208
+ startTransaction;
209
+ silent;
210
+ notify(event) {
211
+ this.events.notify({
212
+ type: event.type,
213
+ payload: event.payload,
214
+ meta: {
215
+ appDefinitionId: this.appDefinitionId
216
+ }
217
+ });
218
+ }
219
+ notifyCustomEvent(type, payload) {
220
+ this.notify({
221
+ type: PlatformAppEvent.CustomEvent,
222
+ payload: {
223
+ ...payload,
224
+ type
225
+ }
226
+ });
227
+ }
228
+ /**
229
+ * TODO: we should use same interface for all events
230
+ * (subscribe vs addEventListener)
231
+ */
232
+ addEventListener(eventType, fn) {
233
+ return this.events.subscribe(async (event) => {
234
+ const isAppMatch = event.meta?.appDefinitionId === this.appDefinitionId || event.meta?.appDefinitionId === null;
235
+ const transformPayload = () => transformEventPayload(event.payload, this.privateAPI);
236
+ if (eventType === "*") {
237
+ fn(await transformPayload());
238
+ } else if (event.type === PlatformAppEvent.CustomEvent) {
239
+ if (eventType === event.payload?.type && !isAppMatch) {
240
+ fn(await transformPayload());
241
+ }
242
+ } else if (event.type === PlatformAppEvent.HostEvent) {
243
+ if (eventType === event.payload?.type && isAppMatch) {
244
+ fn(await transformPayload());
245
+ }
246
+ }
247
+ });
248
+ }
249
+ }
250
+ const WAIT_INJECTED_TIMEOUT = 200;
251
+ const WAIT_INJECTED_RETRY_COUNT = 50;
252
+ class ContextInjectionStatus {
253
+ _resolveContextInjected = () => {
254
+ };
255
+ _isInjected = false;
256
+ key;
257
+ constructor(uuid) {
258
+ this.key = `__${uuid}_CONTEXT_INJECTION_STATUS_KEY`;
259
+ if (!globalThis[this.key]) {
260
+ globalThis[this.key] = new Promise((resolve) => {
261
+ this._resolveContextInjected = () => {
262
+ this._isInjected = true;
263
+ resolve();
264
+ };
265
+ });
266
+ }
267
+ }
268
+ isInjected() {
269
+ return !!this._isInjected;
270
+ }
271
+ resolveInjected() {
272
+ this._resolveContextInjected?.();
273
+ }
274
+ waitInjected() {
275
+ return new Promise((resolve, reject) => {
276
+ let injected = false;
277
+ let timeoutId;
278
+ let retryCount = 0;
279
+ const timeout = () => {
280
+ if (injected) {
281
+ return;
282
+ }
283
+ timeoutId = setTimeout(() => {
284
+ retryCount++;
285
+ if (retryCount < WAIT_INJECTED_RETRY_COUNT) {
286
+ if (retryCount % 10 === 0) {
287
+ console.log(
288
+ createEditorPlatformApplicationContextError(
289
+ EditorPlatformApplicationContextErrorCode.IncorrectEnvironment,
290
+ "contexts are not resolved, still re-trying"
291
+ ).withMessage(`try number ${retryCount}`).message
292
+ );
293
+ }
294
+ timeout();
295
+ return;
296
+ }
297
+ if (!injected) {
298
+ const error = createEditorPlatformApplicationContextError(
299
+ EditorPlatformApplicationContextErrorCode.IncorrectEnvironment,
300
+ "contexts are not resolved, threw by timeout"
301
+ );
302
+ reject(error);
303
+ }
304
+ }, WAIT_INJECTED_TIMEOUT);
305
+ };
306
+ timeout();
307
+ const _waitContextInjectedPromise = globalThis[this.key];
308
+ _waitContextInjectedPromise.then(() => {
309
+ injected = true;
310
+ clearTimeout(timeoutId);
311
+ resolve();
312
+ });
313
+ });
314
+ }
315
+ }
316
+ const ENVIRONMENT_CONTEXT_KEY = "__ENVIRONMENT_CONTEXT_KEY";
317
+ var PlatformEnvironment = /* @__PURE__ */ ((PlatformEnvironment2) => {
318
+ PlatformEnvironment2["Worker"] = "Worker";
319
+ PlatformEnvironment2["Frame"] = "Frame";
320
+ return PlatformEnvironment2;
321
+ })(PlatformEnvironment || {});
322
+ class EnvironmentContext {
323
+ constructor(environmentContext) {
324
+ this.environmentContext = environmentContext;
325
+ }
326
+ static status = new ContextInjectionStatus("environment");
327
+ static async inject(context) {
328
+ if (globalThis[ENVIRONMENT_CONTEXT_KEY]) {
329
+ throw createEditorPlatformApplicationContextError(
330
+ EditorPlatformApplicationContextErrorCode.IncorrectEnvironment,
331
+ "Environment context already exists and should not be overridden"
332
+ );
333
+ }
334
+ globalThis[ENVIRONMENT_CONTEXT_KEY] = new EnvironmentContext(context);
335
+ this.status.resolveInjected();
336
+ }
337
+ static async getInstance() {
338
+ await this.status.waitInjected();
339
+ return globalThis[ENVIRONMENT_CONTEXT_KEY];
340
+ }
341
+ getPrivateAPI() {
342
+ return this.environmentContext.privateApi;
343
+ }
344
+ getEvents() {
345
+ return this.environmentContext.events;
346
+ }
347
+ getApplicationAPIs() {
348
+ return this.environmentContext.applicationAPIs ?? {};
349
+ }
350
+ getEnvironment() {
351
+ return this.environmentContext.environment;
352
+ }
353
+ }
354
+ const APPLICATION_CONTEXT_KEY = "__APPLICATION_CONTEXT_KEY";
355
+ class ApplicationContext {
356
+ constructor(applicationContext, environment) {
357
+ this.applicationContext = applicationContext;
358
+ this.environment = environment;
359
+ this.events = new ApplicationBoundEvents(
360
+ this.applicationContext.appDefinitionId,
361
+ this.environment.getEvents(),
362
+ this.environment.getPrivateAPI()
363
+ );
364
+ }
365
+ static status = new ContextInjectionStatus("application");
366
+ /**
367
+ * TODO: use generics for context type
368
+ * - application
369
+ * - editor
370
+ */
371
+ static async inject(context) {
372
+ const environment = await EnvironmentContext.getInstance();
373
+ if (environment.getEnvironment() !== PlatformEnvironment.Frame) {
374
+ throw createEditorPlatformApplicationContextError(
375
+ EditorPlatformApplicationContextErrorCode.IncorrectEnvironment,
376
+ "Application context can be injected only in frame environment"
377
+ );
378
+ }
379
+ if (globalThis[APPLICATION_CONTEXT_KEY]) {
380
+ throw createEditorPlatformApplicationContextError(
381
+ EditorPlatformApplicationContextErrorCode.IncorrectEnvironment,
382
+ "Application context already exists and should not be overridden"
383
+ );
384
+ }
385
+ globalThis[APPLICATION_CONTEXT_KEY] = new ApplicationContext(
386
+ context,
387
+ await EnvironmentContext.getInstance()
388
+ );
389
+ this.status.resolveInjected();
390
+ }
391
+ static async getInstance() {
392
+ const environment = await EnvironmentContext.getInstance();
393
+ if (environment.getEnvironment() === PlatformEnvironment.Frame) {
394
+ await this.status.waitInjected();
395
+ return globalThis[APPLICATION_CONTEXT_KEY];
396
+ } else {
397
+ return __APPLICATION_CONTEXT_KEY;
398
+ }
399
+ }
400
+ events;
401
+ getAppDefinitionId() {
402
+ return this.applicationContext.appDefinitionId;
403
+ }
404
+ getBindings() {
405
+ return this.applicationContext;
406
+ }
407
+ getEvents() {
408
+ return this.events;
409
+ }
410
+ getPrivateAPI() {
411
+ return this.environment.getPrivateAPI();
412
+ }
413
+ getPrivateApplicationAPI() {
414
+ const appDefinitionId = this.getAppDefinitionId();
415
+ if (!appDefinitionId) {
416
+ throw createEditorPlatformApplicationContextError(
417
+ EditorPlatformApplicationContextErrorCode.IncorrectEnvironment,
418
+ "appDefinitionId is not available"
419
+ );
420
+ }
421
+ return this.environment.getApplicationAPIs()[appDefinitionId];
422
+ }
423
+ }
424
+
425
+ var ApplicationType = /* @__PURE__ */ ((ApplicationType2) => {
426
+ ApplicationType2["EditorAddon"] = "EDITOR_ADDON";
427
+ ApplicationType2["Platform"] = "PLATFORM";
428
+ return ApplicationType2;
429
+ })(ApplicationType || {});
430
+
431
+ class WixEditorPlatformApplication extends EditorPlatformApplication {
432
+ static async create() {
433
+ return new WixEditorPlatformApplication(
434
+ await ApplicationContext.getInstance()
435
+ );
436
+ }
437
+ constructor(context) {
438
+ super(ApplicationType.Platform, context);
439
+ }
440
+ }
441
+
442
+ class WixEditorPlatformAddon extends EditorPlatformApplication {
443
+ static async create() {
444
+ const context = await ApplicationContext.getInstance();
445
+ const instance = new WixEditorPlatformAddon(
446
+ context
447
+ );
448
+ try {
449
+ await instance.init();
450
+ return instance;
451
+ } catch (e) {
452
+ const error = createEditorPlatformApplicationError(
453
+ EditorPlatformApplicationErrorCode.ApplicationRuntimeError
454
+ ).withParentError(e).withMessage("Failed to initialize addon");
455
+ console.error(error);
456
+ return instance;
457
+ }
458
+ }
459
+ constructor(context) {
460
+ super(ApplicationType.EditorAddon, context);
461
+ }
462
+ async init() {
463
+ try {
464
+ await this.registerToolsPanel();
465
+ } catch (e) {
466
+ throw createEditorPlatformApplicationError(
467
+ EditorPlatformApplicationErrorCode.ApplicationRuntimeError
468
+ ).withMessage("Failed to register addon tools panel").withParentError(e);
469
+ }
470
+ }
471
+ async registerToolsPanel() {
472
+ const bindings = this.context.getBindings();
473
+ const { url, width, height, initialPosition } = bindings.data?.toolPanelConfig;
474
+ if (url) {
475
+ await this.context.getPrivateAPI().addons.registerToolsPanel(
476
+ { appDefinitionId: bindings.appDefinitionId, applicationId: "111" },
477
+ {
478
+ title: bindings.appDefinitionName
479
+ },
480
+ {
481
+ url,
482
+ // TODO: this can become "200px", "50%" etc in future. For now we simply assume numeric values like "250".
483
+ width: Number(width),
484
+ height: Number(height),
485
+ initialPosition: {
486
+ x: Number(initialPosition.x),
487
+ y: Number(initialPosition.y)
488
+ }
489
+ }
490
+ );
491
+ }
492
+ }
493
+ }
494
+
495
+ class WorkerEventsBridge {
496
+ constructor(platformAppEvents) {
497
+ this.platformAppEvents = platformAppEvents;
498
+ }
499
+ /**
500
+ * Notify by event from Worker Manager (platform infrastructure)
501
+ */
502
+ notify(event) {
503
+ switch (event.type) {
504
+ case PlatformLifecycleEvent.EditorReady:
505
+ this.platformAppEvents.notify({
506
+ ...event,
507
+ // @ts-expect-error TODO: fix me
508
+ type: PlatformAppEvent.EditorReady
509
+ });
510
+ break;
511
+ case PlatformPrivateEvent.HostEvent:
512
+ this.platformAppEvents.notify({
513
+ ...event,
514
+ type: PlatformAppEvent.HostEvent
515
+ });
516
+ break;
517
+ }
518
+ }
519
+ /**
520
+ * Subscribe to Worker (Application) event
521
+ */
522
+ subscribe(cb) {
523
+ this.platformAppEvents.subscribe((event) => {
524
+ cb(event);
525
+ });
526
+ }
527
+ }
528
+
529
+ const PLATFORM_FRAME_API_TYPE = "PLATFORM_FRAME_API";
530
+ class PlatformFrameAPI {
531
+ type = PLATFORM_FRAME_API_TYPE;
532
+ #events = new PlatformAppEventEmitter();
533
+ #eventsBridge = new WorkerEventsBridge(this.#events);
534
+ #privateAPI;
535
+ #applicationPrivateAPI;
536
+ async initFrameEnvironment(appDefinitionId, privateAPI, applicationPrivateAPI) {
537
+ this.#applicationPrivateAPI = applicationPrivateAPI;
538
+ this.#privateAPI = privateAPI;
539
+ await EnvironmentContext.inject({
540
+ environment: PlatformEnvironment.Frame,
541
+ privateApi: privateAPI,
542
+ events: this.#events,
543
+ applicationAPIs: {
544
+ [appDefinitionId]: this.#applicationPrivateAPI
545
+ }
546
+ });
547
+ await ApplicationContext.inject({
548
+ appDefinitionId,
549
+ appDefinitionName: ""
550
+ });
551
+ }
552
+ notify(event) {
553
+ this.#eventsBridge.notify(event);
554
+ }
555
+ subscribe(cb) {
556
+ this.#eventsBridge.subscribe(cb);
557
+ }
558
+ }
559
+
560
+ const APPLICATION_REGISTRY_KEY = "__APPLICATION_REGISTRY_KEY";
561
+ async function executeApplication(events, spec, bundle) {
562
+ const executable = new Function(
563
+ APPLICATION_CONTEXT_KEY,
564
+ APPLICATION_REGISTRY_KEY,
565
+ bundle
566
+ );
567
+ let instance;
568
+ const applicationRegistryCallback = (_instance) => {
569
+ if (instance) {
570
+ throw createEditorPlatformApplicationError(
571
+ EditorPlatformApplicationErrorCode.ApplicationExecuteError,
572
+ "Application registry called more than once"
573
+ ).withAppDefinitionId(spec.appDefinitionId);
574
+ }
575
+ if (_instance.type !== spec.type) {
576
+ throw createEditorPlatformApplicationError(
577
+ EditorPlatformApplicationErrorCode.ApplicationExecuteError,
578
+ "Application has different type"
579
+ ).withMessage("expected type", spec.type).withMessage("received type", _instance.type);
580
+ }
581
+ instance = _instance;
582
+ };
583
+ try {
584
+ const context = { ...spec };
585
+ executable.call(
586
+ void 0,
587
+ new ApplicationContext(context, await EnvironmentContext.getInstance()),
588
+ applicationRegistryCallback
589
+ );
590
+ } catch (e) {
591
+ throw createEditorPlatformApplicationError(
592
+ EditorPlatformApplicationErrorCode.ApplicationExecuteError,
593
+ e.message
594
+ ).withAppDefinitionId(spec.appDefinitionId).withParentError(e);
595
+ }
596
+ return new Promise((resolve, reject) => {
597
+ const unsubscribe = events.subscribe((event) => {
598
+ const timeoutId = setTimeout(() => {
599
+ clearTimeout(timeoutId);
600
+ unsubscribe();
601
+ if (!instance) {
602
+ reject(
603
+ createEditorPlatformApplicationError(
604
+ EditorPlatformApplicationErrorCode.ApplicationExecuteError,
605
+ "Application registry was not called, threw by timeout"
606
+ ).withAppDefinitionId(spec.appDefinitionId)
607
+ );
608
+ }
609
+ }, 5e3);
610
+ if (event.type === PlatformAppEvent.ApplicationInit && event.meta.appDefinitionId === spec.appDefinitionId) {
611
+ clearTimeout(timeoutId);
612
+ unsubscribe();
613
+ if (!instance) {
614
+ reject(
615
+ createEditorPlatformApplicationError(
616
+ EditorPlatformApplicationErrorCode.ApplicationExecuteError,
617
+ "Application registry was not called"
618
+ ).withAppDefinitionId(spec.appDefinitionId)
619
+ );
620
+ }
621
+ resolve({ instance });
622
+ }
623
+ });
624
+ });
625
+ }
626
+
627
+ class PlatformApplicationContainer {
628
+ constructor(privateApi, events) {
629
+ this.privateApi = privateApi;
630
+ this.events = events;
631
+ this.events.subscribe((event) => {
632
+ switch (event.type) {
633
+ case PlatformAppEvent.HostEvent: {
634
+ if (event.payload.type === EventType.removeAppCompleted) {
635
+ this.events.withEvent(
636
+ this.events.factories.createApplicationRemovedEvent(
637
+ event.payload.appDefinitionId
638
+ ),
639
+ () => {
640
+ return this.removeApplication(event.payload.appDefinitionId);
641
+ }
642
+ );
643
+ }
644
+ break;
645
+ }
646
+ }
647
+ });
648
+ }
649
+ apps = {};
650
+ async runApplication(app) {
651
+ const bundle = await this.loadApplication(app);
652
+ const instance = await this.executeApplication(app, bundle);
653
+ this.setApplication(app.appDefinitionId, instance);
654
+ return instance;
655
+ }
656
+ setApplication(appDefId, instance) {
657
+ this.apps[appDefId] = instance;
658
+ this.events.withEvent(
659
+ this.events.factories.createApplicationApiInitEvent(
660
+ appDefId,
661
+ // TODO: both types are set here...
662
+ // @ts-expect-error TODO: fix me
663
+ instance?.api?.private ? "private" : "public"
664
+ ),
665
+ () => {
666
+ this.privateApi.applicationManager.setApplication(instance);
667
+ }
668
+ );
669
+ }
670
+ getApplication(appDefId) {
671
+ return this.apps[appDefId];
672
+ }
673
+ getAppDefinitionIds() {
674
+ return Object.keys(this.apps);
675
+ }
676
+ removeApplication(appDefinitionId) {
677
+ delete this.apps[appDefinitionId];
678
+ }
679
+ async loadApplication(app) {
680
+ const url = app.url;
681
+ return this.events.withEvent(
682
+ this.events.factories.createApplicationLoadEvent(app, url),
683
+ async () => {
684
+ try {
685
+ return await this.loadApplicationBundle(url);
686
+ } catch (e) {
687
+ throw createEditorPlatformApplicationError(
688
+ EditorPlatformApplicationErrorCode.ApplicationLoadError
689
+ ).withUrl(url).withAppDefinitionId(app.appDefinitionId).withParentError(e);
690
+ }
691
+ }
692
+ );
693
+ }
694
+ async loadApplicationBundle(url) {
695
+ const res = await fetch("url", {
696
+ method: "GET"
697
+ });
698
+ const isSuccessfulResponse = res.status >= 200 && res.status <= 299;
699
+ if (!isSuccessfulResponse) {
700
+ throw createEditorPlatformApplicationError(
701
+ EditorPlatformApplicationErrorCode.ApplicationFetchError
702
+ ).withUrl(url);
703
+ }
704
+ return res.text();
705
+ }
706
+ async executeApplication(app, bundle) {
707
+ return this.events.withEvent(
708
+ this.events.factories.createApplicationExecuteEvent(app, app.url),
709
+ async () => {
710
+ const { instance } = await executeApplication(this.events, app, bundle);
711
+ return instance;
712
+ }
713
+ );
714
+ }
715
+ }
716
+
717
+ const PLATFORM_WORKER_API_TYPE = "PLATFORM_WORKER_API";
718
+ class PlatformWorkerAPI {
719
+ type = PLATFORM_WORKER_API_TYPE;
720
+ #events = new PlatformAppEventEmitter();
721
+ #eventsBridge = new WorkerEventsBridge(this.#events);
722
+ #container = null;
723
+ #privateAPI;
724
+ #pendingWaiters = [];
725
+ async initWorkerEnvironment(buildPrivateAPI) {
726
+ this.#privateAPI = await buildPrivateAPI({
727
+ // TODO: should be per application (within the container before app execution)
728
+ type: "EDITOR_ADDON"
729
+ });
730
+ await EnvironmentContext.inject({
731
+ environment: PlatformEnvironment.Worker,
732
+ events: this.#events,
733
+ privateApi: this.#privateAPI,
734
+ applicationAPIs: {}
735
+ });
736
+ this.#container = new PlatformApplicationContainer(
737
+ this.#privateAPI,
738
+ this.#events
739
+ );
740
+ this.#pendingWaiters.forEach((res) => res(this));
741
+ }
742
+ async notify(event) {
743
+ await this.waitReady();
744
+ this.#eventsBridge.notify(event);
745
+ }
746
+ subscribe(cb) {
747
+ this.#eventsBridge.subscribe(cb);
748
+ }
749
+ async runApplication(app) {
750
+ await this.waitReady();
751
+ await this.#container.runApplication(app);
752
+ }
753
+ waitReady() {
754
+ return new Promise((res) => {
755
+ if (this.#privateAPI) {
756
+ return res(this);
757
+ }
758
+ this.#pendingWaiters.push(res);
759
+ });
760
+ }
761
+ }
762
+
763
+ export { ApplicationType, EditorPlatformApplication, PLATFORM_FRAME_API_TYPE, PLATFORM_WORKER_API_TYPE, PlatformFrameAPI, PlatformWorkerAPI, WixEditorPlatformAddon, WixEditorPlatformApplication };
764
+ //# sourceMappingURL=index.js.map