@3dsource/metabox-modular-configurator-api 3.0.36-dev.0 → 3.0.37

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.
@@ -1,1808 +1,477 @@
1
- import { fromEvent } from 'rxjs';
2
-
3
- /**
4
- * Base class for commands sent to the Metabox API.
5
- *
6
- * ### What does it unlock?
7
- * Base class that all other commands inherit from in a class hierarchy. Provides common properties
8
- * and methods that are automatically available to all command subclasses.
9
- *
10
- * ### Practical Application
11
- * Base class all commands inherit from. Never instantiate directly — use specific subclasses like
12
- * SetProduct, SetCamera, etc. All commands are sent via `api.sendCommandToMetabox(new CommandName(...))`.
13
- *
14
- * ### AI Coding Best Practices
15
- * Never construct a generic CommandBase. Always use the specific typed command class. When generating
16
- * dynamic command dispatch, use a switch/map pattern matching command names to their constructors.
17
- *
18
- * @internal
19
- * @hidden
20
- */
21
- class CommandBase {
22
- }
23
-
24
- /**
25
- * Wrapper helper function to use with RxJS the same way as `fromEvent`, to listen to events from the Communicator.
26
- *
27
- * ### What does it unlock?
28
- * Function that creates an event listener subscription. Allows developers to subscribe to specific events from the Communicator.
29
- *
30
- * ### Practical Application
31
- * Function that creates event listener subscriptions. Alternative to api.addEventListener() — both subscribe
32
- * to configurator events. Use to react to state changes, screenshot readiness, viewport loading, showcase status, etc.
33
- *
34
- * ### AI Coding Best Practices
35
- * Prefer api.addEventListener() directly from the Communicator object. If using fromCommunicatorEvent, pass the
36
- * event name and handler. Key events: configuratorDataUpdated, viewportReady, screenshotReady, showcaseStatusChanged,
37
- * getCameraResult. Always subscribe BEFORE sending commands that trigger responses.
38
- *
39
- * @param {Communicator} target - The Communicator instance to listen on.
40
- * @param {T} eventName - The event name from {@link FromMetaBoxApiEvents} to subscribe to.
41
- * @returns An Observable that emits the typed payload each time the event fires.
42
- * @internal
43
- */
1
+ import { fromEvent } from "rxjs";
2
+ var CommandBase = class {};
44
3
  function fromCommunicatorEvent(target, eventName) {
45
- return fromEvent(target, eventName);
4
+ return fromEvent(target, eventName);
46
5
  }
47
-
48
- /**
49
- * Registry of all action identifiers that can be sent from the host application to the Metabox Modular Configurator.
50
- * Each key maps to a string used as the `action` field in the postMessage envelope.
51
- *
52
- * ### What does it unlock?
53
- * Variable containing all available action names. Interface listing all actions that the modular configurator supports.
54
- *
55
- * ### Practical Application
56
- * Master action registry object — all supported configurator action names. Invaluable reference for building
57
- * admin dashboards, permission systems, or feature-availability displays.
58
- *
59
- * ### AI Coding Best Practices
60
- * Iterate this object to dynamically build action dropdowns, command palettes, or feature checklists in admin tools.
61
- * Each key is an action name, value is its description. Excellent reference for AI coding agents to understand
62
- * the full command vocabulary available.
63
- */
64
6
  const MetaboxModularConfiguratorActions = {
65
- metaboxConfig: 'metaboxConfig',
66
- resumeStream: 'resumeStream',
67
- stopStream: 'stopStream',
68
- setEnvironment: 'setEnvironment',
69
- setEnvironmentMaterialById: 'setEnvironmentMaterialById',
70
- setComponent: 'setComponent',
71
- setComponentMaterialById: 'setComponentMaterialById',
72
- setMaterials: 'setMaterials',
73
- getPdf: 'getPdf',
74
- getCallToActionInformation: 'getCallToActionInformation',
75
- getScreenshot: 'getScreenshot',
76
- showEmbeddedMenu: 'showEmbeddedMenu',
77
- showOverlayInterface: 'showOverlayInterface',
78
- getCamera: 'getCamera',
79
- setCamera: 'setCamera',
80
- resetCamera: 'resetCamera',
81
- resetConfiguration: 'resetConfiguration',
82
- applyZoom: 'applyZoom',
83
- initShowcase: 'initShowcase',
84
- playShowcase: 'playShowcase',
85
- pauseShowcase: 'pauseShowcase',
86
- stopShowcase: 'stopShowcase',
87
- sendCommandToUnreal: 'sendCommandToUnreal',
88
- showMeasurement: 'showMeasurement',
89
- hideMeasurement: 'hideMeasurement',
90
- resetUserInactivityTimer: 'resetUserInactivityTimer',
7
+ metaboxConfig: "metaboxConfig",
8
+ resumeStream: "resumeStream",
9
+ stopStream: "stopStream",
10
+ setEnvironment: "setEnvironment",
11
+ setEnvironmentMaterialById: "setEnvironmentMaterialById",
12
+ setComponent: "setComponent",
13
+ setComponentMaterialById: "setComponentMaterialById",
14
+ setMaterials: "setMaterials",
15
+ getPdf: "getPdf",
16
+ getCallToActionInformation: "getCallToActionInformation",
17
+ getScreenshot: "getScreenshot",
18
+ showEmbeddedMenu: "showEmbeddedMenu",
19
+ showOverlayInterface: "showOverlayInterface",
20
+ getCamera: "getCamera",
21
+ setCamera: "setCamera",
22
+ resetCamera: "resetCamera",
23
+ resetConfiguration: "resetConfiguration",
24
+ applyZoom: "applyZoom",
25
+ initShowcase: "initShowcase",
26
+ playShowcase: "playShowcase",
27
+ pauseShowcase: "pauseShowcase",
28
+ stopShowcase: "stopShowcase",
29
+ sendCommandToUnreal: "sendCommandToUnreal",
30
+ showMeasurement: "showMeasurement",
31
+ hideMeasurement: "hideMeasurement",
32
+ resetUserInactivityTimer: "resetUserInactivityTimer"
91
33
  };
92
-
93
- /**
94
- * Represents a command to send Metabox Config to Metabox Modular Configurator.
95
- *
96
- * ### What does it unlock?
97
- * Configuration object passed to MetaBox during initialization. Specifies domain, host, standalone mode,
98
- * and other parameters that control how the configurator behaves.
99
- *
100
- * ### Practical Application
101
- * Internal configuration object auto-sent during initialization. Contains appId and config.
102
- * DO NOT call directly — integrateMetabox() handles this automatically as part of its setup sequence.
103
- *
104
- * ### AI Coding Best Practices
105
- * NEVER instantiate or send MetaboxConfig manually. It is auto-sent by integrateMetabox().
106
- * Use the IntegrateMetaboxConfig parameter of integrateMetabox() instead for setting domain, standalone,
107
- * loadingImage, introImage, state, etc.
108
- *
109
- * @internal
110
- * Automatically sent when the Communicator instance is ready.
111
- *
112
- * @param {string} appId - The unique identifier for the Communicator Instance
113
- * @param {MetaboxCommandConfig} config - optional initial config: standalone - if true - disable metabox custom template and all logic
114
- */
115
- class MetaboxConfig extends CommandBase {
116
- constructor(appId, config) {
117
- super();
118
- this.data = {
119
- action: MetaboxModularConfiguratorActions.metaboxConfig,
120
- payload: { appId, config },
121
- };
122
- }
123
- }
124
-
125
- /**
126
- * Represents a command to get a PDF from Metabox Modular Configurator.
127
- * This class sends a message to the Metabox API to generate a PDF based on the current configuration.
128
- * The document is streamed to the browser as a download once it is ready — that path needs no
129
- * subscription and has not changed.
130
- *
131
- * The PDF is not stored anywhere, so there is no document handle to receive. To follow the render
132
- * rather than just let it land, listen to the 'pdfStatusChanged' event before sending the command:
133
- * it reports `'started'`, then `'ready'` or `'failed'`.
134
- *
135
- * @remarks
136
- * `pdfStatusChanged` is additive and requires configurator-side support. Where the configurator does
137
- * not emit it yet, the automatic download remains the only signal — so use the event for progress and
138
- * error reporting, and never gate the export flow on it alone.
139
- *
140
- * ### What does it unlock?
141
- * Generates a native MetaBox PDF document server-side. The download works on its own;
142
- * `pdfStatusChanged` additionally makes the render observable — whether it started, finished or failed.
143
- *
144
- * ### Practical Application
145
- * Generates a branded PDF from the current configurator state. Use for B2B quote workflows,
146
- * downloadable spec sheets, or emailing configured product summaries to prospects. Subscribe to
147
- * `pdfStatusChanged` to disable the export button while the render runs — it is not instant, and a
148
- * second click starts a second render — and to surface a failure instead of leaving the user waiting.
149
- *
150
- * ### AI Coding Best Practices
151
- * `api.sendCommandToMetabox(new GetPdf())` takes no parameters. Subscribe to `pdfStatusChanged` BEFORE
152
- * sending. Do not wait for a file handle: there is none, the browser download is the delivery. Keep a
153
- * timeout of your own, since a configurator without this event will never report. Failure detail, when
154
- * available, arrives on `statusMessageChanged`.
155
- *
156
- * @example
157
- * import { GetPdf, Communicator, PdfStatus } from '@3dsource/metabox-modular-configurator-api';
158
- * window.env3DSource.apiReady = (api: Communicator) => {
159
- *
160
- * //Subscribe to the event before sending the command to ensure you capture the response
161
- * api.addEventListener('pdfStatusChanged', (status: PdfStatus) => {
162
- * if (status === 'failed') {
163
- * console.warn('PDF render failed');
164
- * }
165
- * console.log('PDF render:', status);
166
- * });
167
- *
168
- * api.sendCommandToMetabox(new GetPdf());
169
- * };
170
- */
171
- class GetPdf extends CommandBase {
172
- constructor() {
173
- super();
174
- this.data = { action: MetaboxModularConfiguratorActions.getPdf };
175
- }
176
- }
177
-
178
- /**
179
- * Represents a command to get a Call To Action Information from Metabox Modular Configurator.
180
- * This class sends a message to the Metabox API to generate Call To Action information based on the current
181
- * configuration and sends it to the endpoint URL from the CTA information.
182
- *
183
- * `ecomConfiguratorDataUpdated` is not its reply — that fires once, as the ecom data loads — so
184
- * subscribe to it from the apiReady callback, not around this call. To follow the workflow itself,
185
- * listen to 'ctaStatusChanged': it reports `'started'`, then `'ready'` or `'failed'`.
186
- *
187
- * @remarks
188
- * `ctaStatusChanged` is additive and requires configurator-side support. There is no redirect url to
189
- * receive: MetaBox posts the configuration to the callback URL from admin and navigates to the
190
- * `redirectUrl` the endpoint returns, reporting an unusable reply in its own UI. On success the user
191
- * is navigated away, so treat `'started'` and `'failed'` as the load-bearing states.
192
- *
193
- * ### What does it unlock?
194
- * Runs the CTA workflow. The CTA label and callback URL reach the host on the load-time
195
- * `ecomConfiguratorDataUpdated` event, not from this command.
196
- *
197
- * ### Practical Application
198
- * Triggers the CTA (Call-to-Action) workflow configured in MetaBox admin. The CTA label and callback URL are set in admin.
199
- * When invoked, MetaBox POSTs the full configuration JSON (including BOM) to your callback URL endpoint, which returns a { redirectUrl }.
200
- *
201
- * ### AI Coding Best Practices
202
- * Call only after user completes configuration. Subscribe to ecomConfiguratorDataUpdated to get CTA label/URL for building
203
- * custom CTA buttons in your UI. The POST payload includes the full bill of materials — your backend endpoint processes it
204
- * and returns a redirect URL.
205
- *
206
- * @example
207
- * import { Communicator, EcomConfigurator, GetCallToActionInformation } from '@3dsource/metabox-modular-configurator-api';
208
- * window.env3DSource.apiReady = (api: Communicator) => {
209
- *
210
- * //Subscribe as soon as the api is ready: this event fires once, when the ecom data loads
211
- * api.addEventListener('ecomConfiguratorDataUpdated', (data:EcomConfigurator) => {
212
- * console.log('Ecom configurator params:', data);
213
- * });
214
- *
215
- * // Send the command to get Call To Action information from Metabox Modular Configurator
216
- * api.sendCommandToMetabox(new GetCallToActionInformation());
217
- * };
218
- */
219
- class GetCallToActionInformation extends CommandBase {
220
- constructor() {
221
- super();
222
- this.data = {
223
- action: MetaboxModularConfiguratorActions.getCallToActionInformation,
224
- };
225
- }
226
- }
227
-
228
- /**
229
- * Represents a command to get the camera configuration from Unreal.
230
- * This class sends a message to the Metabox API to get the camera from a scene.
231
- * To listen for changes after sending this command, listen to the 'getCameraResult' event.
232
- *
233
- * ### What does it unlock?
234
- * Retrieves camera presets for the configurator; allowing extraction and application of saved camera positions.
235
- *
236
- * ### Practical Application
237
- * Requests current camera state — returns asynchronously via the getCameraResult event. Returns a CameraCommandPayload
238
- * with fov, mode, position, rotation, and restrictions. Use to save camera positions, create shareable view links,
239
- * or build 'save this angle' features.
240
- *
241
- * ### AI Coding Best Practices
242
- * ALWAYS subscribe to getCameraResult BEFORE calling GetCamera(). Pattern: `api.addEventListener('getCameraResult', handler);`
243
- * then `api.sendCommandToMetabox(new GetCamera())`. The returned CameraCommandPayload can be fed directly back into
244
- * SetCamera to restore the view.
245
- *
246
- * @example
247
- * import { Communicator, CameraCommandPayload, GetCamera } from '@3dsource/metabox-modular-configurator-api';
248
- * window.env3DSource.apiReady = (api: Communicator) => {
249
- *
250
- * //Subscribe to the event before sending the command to ensure you capture the response
251
- * api.addEventListener('getCameraResult', (data:CameraCommandPayload) => {
252
- * console.log('Camera params after get camera command:', data);
253
- * });
254
- *
255
- * api.sendCommandToMetabox(new GetCamera());
256
- * };
257
- */
258
- class GetCamera extends CommandBase {
259
- constructor() {
260
- super();
261
- this.data = { action: MetaboxModularConfiguratorActions.getCamera };
262
- }
263
- }
264
-
265
- /**
266
- * Represents a command to set the camera configuration.
267
- * This class sends a message to the Metabox API to set the camera on a scene.
268
- * **Important**: No need to listen to any events to see changes.
269
- *
270
- * ### What does it unlock?
271
- * Sets camera presets with restriction parameters (FOV, rotation, position).
272
- *
273
- * ### Practical Application
274
- * Sets camera with precise control: fov (degrees), mode ('orbit'|'fps'), position ({x,y,z}),
275
- * rotation ({horizontal,vertical}), and restrictions (min/max distance, FOV, rotation bounds).
276
- * Use for guided tours, preset view buttons, or restricting camera to prevent users seeing behind the product.
277
- *
278
- * ### AI Coding Best Practices
279
- * Only include fields you want to change — omitted values keep current settings. Use orbit mode for typical product viewing,
280
- * fps for walkthrough/room scenes. Apply restrictions to prevent bad angles. Full interface:
281
- * `{fov?, mode?, position?, rotation?, restrictions?}`.
282
- *
283
- * @example
284
- * import { SetCamera, Communicator } from '@3dsource/metabox-modular-configurator-api';
285
- * window.env3DSource.apiReady = (api: Communicator) => {
286
- * api.sendCommandToMetabox(new SetCamera({
287
- * fov: 45,
288
- * mode: 'orbit',
289
- * position: { x: 100, y: 100, z: 100 },
290
- * rotation: { horizontal: 0, vertical: 0 },
291
- * restrictions: {
292
- * maxDistanceToPivot: 0,
293
- * maxFov: 0,
294
- * maxHorizontalRotation: 0,
295
- * maxVerticalRotation: 0,
296
- * minDistanceToPivot: 0,
297
- * minFov: 0,
298
- * minHorizontalRotation: 0,
299
- * minVerticalRotation: 0,
300
- * },
301
- * }));
302
- * };
303
- *
304
- * @param {CameraCommandPayload} camera - The camera configuration.
305
- */
306
- class SetCamera extends CommandBase {
307
- constructor(camera) {
308
- super();
309
- this.data = {
310
- action: MetaboxModularConfiguratorActions.setCamera,
311
- payload: { camera },
312
- };
313
- }
314
- }
315
-
316
- /**
317
- * Represents a command to reset the camera to its initial position.
318
- * This class sends a message to the Metabox API to reset the camera on a scene.
319
- *
320
- * ### What does it unlock?
321
- * Resets the camera to its default state and position. Used to return camera to initial configuration after user manipulation.
322
- *
323
- * ### Practical Application
324
- * Resets camera to the default position defined in the component/environment template. Essential for 'Reset View' buttons.
325
- * Also, useful after programmatic camera moves to return to a known starting state.
326
- *
327
- * ### AI Coding Best Practices
328
- * Call `api.sendCommandToMetabox(new ResetCamera())`. No parameters. Restores template defaults — not the last user position.
329
- * Good practice to call after SetComponent changes that may shift the focal point of the assembly.
330
- *
331
- * @example
332
- * import { ResetCamera, Communicator } from '@3dsource/metabox-modular-configurator-api';
333
- * window.env3DSource.apiReady = (api: Communicator) => {
334
- * api.sendCommandToMetabox(new ResetCamera());
335
- * };
336
- */
337
- class ResetCamera extends CommandBase {
338
- constructor() {
339
- super();
340
- this.data = { action: MetaboxModularConfiguratorActions.resetCamera };
341
- }
342
- }
343
-
344
- /**
345
- * Represents a command to reset the modular configurator state to its defaults.
346
- * This class sends a message to the Metabox API to restore the component tree, component materials,
347
- * environment, and environment materials to the values defined by the configurator template.
348
- * To listen for changes after sending this command, listen to the 'configuratorDataUpdated' event.
349
- *
350
- * ### What does it unlock?
351
- * Resets the entire modular configurator state to defaults — root and child components, all component
352
- * material selections, environment, and environment materials all return to the template-defined initial
353
- * values. Used to give users a clean 'Start Over' affordance without reloading the iframe.
354
- *
355
- * ### Practical Application
356
- * Powers 'Reset to Defaults' / 'Start Over' buttons in modular configurators where users have built up
357
- * an assembly with multiple SetComponent / SetComponentMaterial calls. Unlike ResetCamera (which only
358
- * touches viewport state), ResetConfiguration wipes all user-applied selections back to template
359
- * defaults. The configurator responds with a full ModularConfiguratorEnvelope via configuratorDataUpdated,
360
- * so UI state derived from the envelope (configurationTree, componentsByComponentType, material chips)
361
- * will re-sync automatically.
362
- *
363
- * ### AI Coding Best Practices
364
- * Call `api.sendCommandToMetabox(new ResetConfiguration())`. No parameters. Subscribe to
365
- * configuratorDataUpdated BEFORE sending so you capture the reset envelope. If your UI maintains local
366
- * selection state separate from the envelope, clear it in the same handler. After reset, the root
367
- * component is back to the template default — no need to re-issue SetComponent for the root unless you
368
- * want a different starting assembly. Pair with ResetCamera if you also want the viewport returned to
369
- * its default framing.
370
- *
371
- * @example
372
- * import { ResetConfiguration, Communicator, ModularConfiguratorEnvelope } from '@3dsource/metabox-modular-configurator-api';
373
- * window.env3DSource.apiReady = (api: Communicator) => {
374
- *
375
- * //Subscribe to the event before sending the command to ensure you capture the response
376
- * api.addEventListener('configuratorDataUpdated', (data: ModularConfiguratorEnvelope) => {
377
- * console.log('Configurator reset to default state:', data);
378
- * });
379
- *
380
- * api.sendCommandToMetabox(new ResetConfiguration());
381
- * };
382
- */
383
- class ResetConfiguration extends CommandBase {
384
- constructor() {
385
- super();
386
- this.data = {
387
- action: MetaboxModularConfiguratorActions.resetConfiguration,
388
- };
389
- }
390
- }
391
-
392
- /**
393
- * Represents a command to apply zoom and change the camera zoom on a scene.
394
- * This class sends a command to the Metabox API to change zoom on a scene.
395
- *
396
- * ### What does it unlock?
397
- * Controls zoom functionality for the configurator; allowing users to adjust the zoom level of 3D objects and camera presets.
398
- *
399
- * ### Practical Application
400
- * Implements programmatic zoom on the pixel-streamed viewport. Use to build zoom slider controls, pinch-to-zoom on mobile,
401
- * or 'zoom to detail' buttons. Takes a numeric delta: positive zooms in, negative zooms out
402
- * (e.g., ApplyZoom(50) zooms in, ApplyZoom(-50) zooms out).
403
- *
404
- * ### AI Coding Best Practices
405
- * Always use numeric delta values, not absolute zoom levels. Pair with a UI slider that sends incremental values.
406
- * Debounce zoom input to ~100ms intervals to prevent overwhelming the Unreal stream.
407
- * Pattern: `api.sendCommandToMetabox(new ApplyZoom(50))`.
408
- *
409
- * @example
410
- * import { ApplyZoom, Communicator } from '@3dsource/metabox-modular-configurator-api';
411
- * window.env3DSource.apiReady = (api: Communicator) => {
412
- * api.sendCommandToMetabox(new ApplyZoom(50));
413
- * };
414
- *
415
- * @param {number} zoom - The zoom value to apply.
416
- */
417
- class ApplyZoom extends CommandBase {
418
- constructor(zoom) {
419
- super();
420
- this.data = {
421
- action: MetaboxModularConfiguratorActions.applyZoom,
422
- payload: { zoom },
423
- };
424
- }
425
- }
426
-
427
- /**
428
- * Represents a command to initialize Showcase for a component scene and start a sequence for the component.
429
- * This class sends a command to the Metabox API to initialize showcase if the component has a sequence.
430
- * To check this, find the showcase property in the current component and listen to the 'configuratorDataUpdated' event.
431
- * If this property exists, you can send the init showcase command.
432
- *
433
- * To listen for changes after sending this command, listen to the 'showcaseStatusChanged' event.
434
- *
435
- * ### What does it unlock?
436
- * Initializes and displays the showcase/demo view for the configurator. Used when transitioning into presentation or demo mode.
437
- *
438
- * ### Practical Application
439
- * Loads the showcase/animation sequence attached to the current component. Must be called BEFORE PlayShowcase.
440
- * Use to initialize auto-playing product demos, trade show presentations, or hero section animations on landing pages.
441
- *
442
- * ### AI Coding Best Practices
443
- * ALWAYS call InitShowcase() before PlayShowcase(). Required sequence: InitShowcase → PlayShowcase → PauseShowcase/StopShowcase.
444
- * Subscribe to showcaseStatusChanged to track playback state ('playing'/'paused'/'stopped').
445
- *
446
- * @example
447
- * import { Communicator, ShowCaseStatus, InitShowcase } from '@3dsource/metabox-modular-configurator-api';
448
- * window.env3DSource.apiReady = (api: Communicator) => {
449
- * //Subscribe to the event before sending the command to ensure you capture the response
450
- * api.addEventListener('showcaseStatusChanged', (data:ShowCaseStatus) => {
451
- * console.log('Showcase status value after changed:', data);
452
- * });
453
- *
454
- * api.sendCommandToMetabox(new InitShowcase());
455
- * };
456
- */
457
- class InitShowcase extends CommandBase {
458
- constructor() {
459
- super();
460
- this.data = {
461
- action: MetaboxModularConfiguratorActions.initShowcase,
462
- };
463
- }
464
- }
465
-
466
- /**
467
- * Represents a command to play Showcase for a component when it is already initialized and paused.
468
- * This class sends a command to the Metabox API to play showcase for a component if it is already initialized and paused.
469
- *
470
- * To listen for changes after sending this command, listen to the 'showcaseStatusChanged' event.
471
- *
472
- * ### What does it unlock?
473
- * Starts or resumes the showcase/timeline playback. Executes the internal MetaBox play command internally.
474
- *
475
- * ### Practical Application
476
- * Starts or resumes showcase playback. Use for 'Play Demo' buttons on landing pages, auto-play on page load,
477
- * or resuming demos after inactivity timeout on kiosk displays.
478
- *
479
- * ### AI Coding Best Practices
480
- * Call `api.sendCommandToMetabox(new PlayShowcase())`. Must call InitShowcase() first or it won't play.
481
- * Subscribe to showcaseStatusChanged to track state. Auto-play pattern: wait for viewportReady → InitShowcase →
482
- * PlayShowcase.
483
- *
484
- * @example
485
- * import { Communicator, PlayShowcase } from '@3dsource/metabox-modular-configurator-api';
486
- * window.env3DSource.apiReady = (api: Communicator) => {
487
- * //Subscribe to the event before sending the command to ensure you capture the response
488
- * api.addEventListener('showcaseStatusChanged', (data) => {
489
- * console.log('Showcase status value after changed:', data);
490
- * });
491
- *
492
- * api.sendCommandToMetabox(new PlayShowcase());
493
- * };
494
- */
495
- class PlayShowcase extends CommandBase {
496
- constructor() {
497
- super();
498
- this.data = { action: MetaboxModularConfiguratorActions.playShowcase };
499
- }
500
- }
501
-
502
- /**
503
- * @internal
504
- * @hidden
505
- * Represents a command to send Unreal command.
506
- */
507
- class UnrealCommand extends CommandBase {
508
- constructor(payload) {
509
- super();
510
- this.data = {
511
- action: MetaboxModularConfiguratorActions.sendCommandToUnreal,
512
- payload,
513
- };
514
- }
515
- }
516
-
517
- /**
518
- * Represents a command to pause Showcase for a component when it is already initialized and playing.
519
- * This class sends a command to the Metabox API to pause showcase for a component if it is already initialized and playing.
520
- *
521
- * To listen for changes after sending this command, listen to the 'showcaseStatusChanged' event.
522
- *
523
- * ### What does it unlock?
524
- * Pauses the showcase/timeline playback. Can be called independently without requiring any flag parameters.
525
- *
526
- * ### Practical Application
527
- * Pauses showcase animation playback. The showcase remains initialized and can be resumed with
528
- * PlayShowcase. Use when you need to temporarily freeze the animation (e.g., on a "Pause" button click).
529
- *
530
- * ### AI Coding Best Practices
531
- * Call `api.sendCommandToMetabox(new PauseShowcase())`. No parameters. Subscribe to showcaseStatusChanged
532
- * to confirm 'pause' state. Use PlayShowcase to resume or StopShowcase to reset.
533
- *
534
- * @example
535
- * import { Communicator, ShowCaseStatus, PauseShowcase } from '@3dsource/metabox-modular-configurator-api';
536
- * window.env3DSource.apiReady = (api: Communicator) => {
537
- *
538
- * //Subscribe to the event before sending the command to ensure you capture the response
539
- * api.addEventListener('showcaseStatusChanged', (data:ShowCaseStatus) => {
540
- * console.log('Showcase status value after changed:', data);
541
- * });
542
- *
543
- * api.sendCommandToMetabox(new PauseShowcase());
544
- * };
545
- */
546
- class PauseShowcase extends CommandBase {
547
- constructor() {
548
- super();
549
- this.data = { action: MetaboxModularConfiguratorActions.pauseShowcase };
550
- }
551
- }
552
-
553
- /**
554
- * Represents a command to stop Showcase for a component when it is already initialized, and you want to destroy it.
555
- * This class sends a command to the Metabox API to stop showcase for a component if it is already initialized.
556
- *
557
- * To listen for changes after sending this command, listen to the 'showcaseStatusChanged' event.
558
- *
559
- * ### What does it unlock?
560
- * Stops the showcase/timeline playback and closes the showcase mode. Returns to normal configurator view.
561
- *
562
- * ### Practical Application
563
- * Stops showcase playback and exits showcase mode entirely. Returns to normal interactive configurator view.
564
- * Use for 'Exit Demo' buttons or auto-trigger when the user starts actively configuring the product.
565
- *
566
- * ### AI Coding Best Practices
567
- * Call `api.sendCommandToMetabox(new StopShowcase())`. Fully resets the showcase state. Subscribe to
568
- * showcaseStatusChanged to confirm 'stopped' status. After stopping, the configurator returns to full
569
- * interactive mode — re-enable configuration controls.
570
- *
571
- * @example
572
- * import { Communicator, ShowCaseStatus } from '@3dsource/metabox-modular-configurator-api';
573
- * window.env3DSource.apiReady = (api: Communicator) => {
574
- *
575
- * //Subscribe to the event before sending the command to ensure you capture the response
576
- * api.addEventListener('showcaseStatusChanged', (data:ShowCaseStatus) => {
577
- * console.log('Showcase status value after changed:', data);
578
- * });
579
- *
580
- * api.sendCommandToMetabox(new StopShowcase());
581
- * };
582
- */
583
- class StopShowcase extends CommandBase {
584
- constructor() {
585
- super();
586
- this.data = { action: MetaboxModularConfiguratorActions.stopShowcase };
587
- }
588
- }
589
-
590
- /**
591
- * Represents a command to get a screenshot.
592
- *
593
- * To listen for changes after sending this command, listen to the 'screenshotReady' event before command is sent.
594
- *
595
- * ### What does it unlock?
596
- * Takes a screenshot on the server side (Unreal Engine) of the 3D scene. Returns high-quality image.
597
- * Requires subscription to the screenshotReady event to receive the rendered image.
598
- *
599
- * ### Practical Application
600
- * Renders a high-res screenshot on the Unreal Engine server. Takes format ('image/png'|'image/jpeg'|'image/webp')
601
- * and optional size ({x, y}). Returns base64 data via screenshotReady event. Use for thumbnails, social sharing,
602
- * saving config snapshots, or attaching images to quotes.
603
- *
604
- * ### AI Coding Best Practices
605
- * Subscribe to screenshotReady BEFORE sending GetScreenshot. Pattern:
606
- * `api.addEventListener('screenshotReady', (data) => { if(data) saveImage(data, 'name.png'); })`.
607
- * Specify size for consistent outputs: `new GetScreenshot('image/png', {x:2048, y:2048})`.
608
- * Use saveImage() helper to convert base64 to downloadable file.
609
- *
610
- * @example
611
- * import { Communicator, saveImage, GetScreenshot } from '@3dsource/metabox-modular-configurator-api';
612
- * window.env3DSource.apiReady = (api: Communicator) => {
613
- *
614
- * //Subscribe to the event before sending the command to ensure you capture the response
615
- * api.addEventListener('screenshotReady', (data:string) => {
616
- * // The data is a base64 string of the image. You can use it to display the image or save it as a file.
617
- * console.log('Get screenshot here:', data);
618
- * saveImage(data, 'Render.png');
619
- * });
620
- *
621
- * api.sendCommandToMetabox(new GetScreenshot('image/png', { x: 1024, y: 1024 }));
622
- * };
623
- *
624
- * @param {MimeType} mimeType - The output format.
625
- * @param {{ x: number; y: number }} [size] - Optional size in pixels.
626
- */
627
- class GetScreenshot extends CommandBase {
628
- constructor(mimeType, size) {
629
- super();
630
- this.data = {
631
- action: MetaboxModularConfiguratorActions.getScreenshot,
632
- payload: { format: mimeType, size },
633
- };
634
- }
635
- }
636
-
637
- /**
638
- * Represents a command to set a component by its data (ID, typeId).
639
- * This action sends a message to the Metabox API to set a component using the provided data.
640
- * To listen for changes after sending this command, listen to the 'configuratorDataUpdated' event.
641
- *
642
- * ### What does it unlock?
643
- * Sets a component during initialization, which triggers the reconstruction of the component tree structure.
644
- * Simulates clicking a component in the menu.
645
- *
646
- * ### Practical Application
647
- * Selects a component in the modular assembly. Takes componentId (UUID), typeId (category string).
648
- * CRITICAL: Always set root component (isRoot:true) FIRST — nothing renders without it. Then add children (isRoot:false).
649
- * Simulates clicking a component in the menu.
650
- *
651
- * ### AI Coding Best Practices
652
- * ALWAYS set root first: `new SetComponent('id', 'type', true)`. Then children: `new SetComponent('childId', 'childType', false)`.
653
- * Get valid IDs from configuratorDataUpdated event data — the configurator definition contains all available components and types.
654
- * Wrong order = blank viewport. The typeId must match componentType values from the configurator.
655
- *
656
- * @example
657
- * import { Communicator, ModularConfiguratorEnvelope, SetComponent } from '@3dsource/metabox-modular-configurator-api';
658
- * window.env3DSource.apiReady = (api: Communicator) => {
659
- *
660
- * //Subscribe to the event before sending the command to ensure you capture the response
661
- * api.addEventListener('configuratorDataUpdated', (data:ModularConfiguratorEnvelope) => {
662
- * console.log('State updated after applied new component:', data);
663
- * });
664
- *
665
- * api.sendCommandToMetabox(new SetComponent(
666
- * 'ffea6b5c-3a8a-4f56-9417-e605acb5cca3', 'typeId'
667
- * ));
668
- * };
669
- *
670
- * @param {string} id - The component ID.
671
- * @param {string} typeId - The component type ID.
672
- */
673
- class SetComponent extends CommandBase {
674
- constructor(id, typeId) {
675
- super();
676
- this.data = {
677
- payload: { id, typeId },
678
- action: MetaboxModularConfiguratorActions.setComponent,
679
- };
680
- }
681
- }
682
-
683
- /**
684
- * Represents a command to set component material by its slot ID and Material ID.
685
- * To listen for changes after sending this command, listen to the 'configuratorDataUpdated' event.
686
- *
687
- * ### What does it unlock?
688
- * Sets a material variant for a component. Simulates selecting a different material from the menu for a specific component.
689
- *
690
- * ### Practical Application
691
- * Applies a material to a specific slot on a component. Takes componentId (UUID), slotId (string), and materialId (UUID).
692
- * Use to build swatch pickers, apply preset themes/bundles, or sync material selections from an external
693
- * PIM/ERP system via externalId mapping.
694
- *
695
- * ### AI Coding Best Practices
696
- * Get valid slotId and materialId values from the configuratorDataUpdated envelope —
697
- * check component slot definitions and material lists. Pattern:
698
- * `new SetComponentMaterial('component-uuid', 'slot-name', 'material-uuid')`. The referenced component must already be set in the tree.
699
- *
700
- * @example
701
- * import { Communicator, ModularConfiguratorEnvelope, SetComponentMaterial } from '@3dsource/metabox-modular-configurator-api';
702
- * window.env3DSource.apiReady = (api: Communicator) => {
703
- *
704
- * //Subscribe to the event before sending the command to ensure you capture the response
705
- * api.addEventListener('configuratorDataUpdated', (data:ModularConfiguratorEnvelope) => {
706
- * console.log('State updated after applied new material:', data);
707
- * });
708
- *
709
- * api.sendCommandToMetabox(new SetComponentMaterial(
710
- * 'ffea6b5c-3a8a-4f56-9417-e605acb5cca3',
711
- * 'carpaint',
712
- * 'dd829d6e-9200-47a7-8d5b-af5df89b7e91',
713
- * ));
714
- * };
715
- *
716
- * @param {string} componentId - The component ID.
717
- * @param {string} slotId - The slot ID.
718
- * @param {string} materialId - The material ID.
719
- */
720
- class SetComponentMaterial extends CommandBase {
721
- constructor(componentId, slotId, materialId) {
722
- super();
723
- this.data = {
724
- payload: { componentId, slotId, materialId },
725
- action: MetaboxModularConfiguratorActions.setComponentMaterialById,
726
- };
727
- }
728
- }
729
-
730
- /**
731
- * Represents a command to set the environment by its ID.
732
- * To listen for changes after sending this command, listen to the 'configuratorDataUpdated' event.
733
- *
734
- * ### What does it unlock?
735
- * Sets environmental/lighting settings for the scene. Controls factors like lighting conditions and environmental appearance.
736
- *
737
- * ### Practical Application
738
- * Changes the 3D scene/environment (studio, showroom, outdoor, etc.). Takes an environmentId UUID.
739
- * Environments include lighting, backdrop, and optionally dynamic sky (udsEnabled) with time-of-day (udsHour) control.
740
- *
741
- * ### AI Coding Best Practices
742
- * Call `api.sendCommandToMetabox(new SetEnvironment('env-uuid'))`. Get valid environment IDs from the configurator
743
- * definition in configuratorDataUpdated. Set environment after root component during initialization. Each environment has
744
- * its own material slots, thumbnails, and lighting properties.
745
- *
746
- * @example
747
- * import { Communicator, ModularConfiguratorEnvelope } from '@3dsource/metabox-modular-configurator-api';
748
- * window.env3DSource.apiReady = (api: Communicator) => {
749
- *
750
- * //Subscribe to the event before sending the command to ensure you capture the response
751
- * api.addEventListener('configuratorDataUpdated', (data:ModularConfiguratorEnvelope) => {
752
- * console.log('State updated after applied new environment:', data);
753
- * });
754
- *
755
- * api.sendCommandToMetabox(new SetEnvironment('55555555-1234-1234-1234-01234567890'))
756
- * };
757
- *
758
- * @param {string} environmentId - The environment ID.
759
- */
760
- class SetEnvironment extends CommandBase {
761
- constructor(environmentId) {
762
- super();
763
- this.data = {
764
- action: MetaboxModularConfiguratorActions.setEnvironment,
765
- payload: { id: environmentId },
766
- };
767
- }
768
- }
769
-
770
- /**
771
- * Represents a command to set an environment material by its slot ID and Material ID.
772
- * To listen for changes after sending this command, listen to the 'configuratorDataUpdated' event.
773
- *
774
- * ### What does it unlock?
775
- * Sets environmental material properties such as textures and appearance attributes for the scene environment.
776
- *
777
- * ### Practical Application
778
- * Applies materials to environment slots (floor, walls, backdrop textures). Takes slotId and materialId.
779
- * Use for scene-based configurators where the environment is also customizable — kitchen visualizers,
780
- * room planners, trade show booth designers.
781
- *
782
- * ### AI Coding Best Practices
783
- * Pattern: `new SetEnvironmentMaterial('floor-slot-id', 'material-uuid')`. Get valid slot and material IDs from
784
- * the environment definition's slots array in configuratorDataUpdated. Only useful when the active environment
785
- * has configurable material slots.
786
- *
787
- * @example
788
- * import { Communicator, ModularConfiguratorEnvelope } from '@3dsource/metabox-modular-configurator-api';
789
- * window.env3DSource.apiReady = (api: Communicator) => {
790
- *
791
- * //Subscribe to the event before sending the command to ensure you capture the response
792
- * api.addEventListener('configuratorDataUpdated', (data:ModularConfiguratorEnvelope) => {
793
- * console.log('State updated after applied new environment material:', data);
794
- * });
795
- *
796
- * api.sendCommandToMetabox(new SetEnvironmentMaterial(
797
- * 'carpaint',
798
- * 'dd829d6e-9200-47a7-8d5b-af5df89b7e91',
799
- * ));
800
- * };
801
- *
802
- * @param {string} slotId - The slot ID.
803
- * @param {string} materialId - The material ID.
804
- */
805
- class SetEnvironmentMaterial extends CommandBase {
806
- constructor(slotId, materialId) {
807
- super();
808
- this.data = {
809
- action: MetaboxModularConfiguratorActions.setEnvironmentMaterialById,
810
- payload: { slotId, materialId },
811
- };
812
- }
813
- }
814
-
815
- /**
816
- * Represents a command to apply several materials at once.
817
- * To listen for changes after sending this command, listen to the 'configuratorDataUpdated' event.
818
- *
819
- * ### What does it unlock?
820
- * Applies a whole material set in a single message instead of one command per slot. Simulates picking
821
- * every swatch of a preset at once, so the assembly updates in one pass rather than slot by slot.
822
- *
823
- * ### Practical Application
824
- * Takes an array of {@link SetComponentMaterial} and {@link SetEnvironmentMaterial} instances and sends
825
- * them as one batch, preserving order. Use it to apply presets or themed bundles across several
826
- * components, to restore a saved configuration, or to sync a full material set from an external
827
- * PIM/ERP system — instead of firing (and debouncing) N separate commands.
828
- *
829
- * ### AI Coding Best Practices
830
- * Build the entries from the configuratorDataUpdated envelope — walk `configurationTree`, take each
831
- * active component's `product.slots` and each slot's `enabledMaterials`. Pattern:
832
- * `new SetMaterials([new SetComponentMaterial('component-uuid', 'body', 'uuid'),
833
- * new SetEnvironmentMaterial('floor', 'uuid')])`. Nothing is validated client-side: entries are sent
834
- * exactly as given, in order, and every referenced component must already be set in the tree.
835
- * Keep using `SetComponentMaterial` on its own for a single swatch click.
836
- *
837
- * @example
838
- * import { Communicator,ModularConfiguratorEnvelope,SetComponentMaterial,SetEnvironmentMaterial,SetMaterials } from '@3dsource/metabox-modular-configurator-api';
839
- * window.env3DSource.apiReady = (api: Communicator) => {
840
- *
841
- * //Subscribe to the event before sending the command to ensure you capture the response
842
- * api.addEventListener('configuratorDataUpdated', (data:ModularConfiguratorEnvelope) => {
843
- * console.log('State updated after applied new materials:', data);
844
- * });
845
- *
846
- * api.sendCommandToMetabox(new SetMaterials([
847
- * new SetComponentMaterial('ffea6b5c-3a8a-4f56-9417-e605acb5cca3', 'carpaint', 'dd829d6e-9200-47a7-8d5b-af5df89b7e91'),
848
- * new SetEnvironmentMaterial('floor', '7c1f4b2a-58e3-4a19-9d6c-2b0f83e5a114'),
849
- * ]));
850
- * };
851
- *
852
- * @param {MaterialCommand[]} commands - The material commands to apply, in order.
853
- */
854
- class SetMaterials extends CommandBase {
855
- constructor(commands) {
856
- super();
857
- this.data = {
858
- action: MetaboxModularConfiguratorActions.setMaterials,
859
- payload: {
860
- // Entries are copied so the batch never aliases the source command's own `data`.
861
- // The narrowing is guaranteed by the command classes the constructor accepts.
862
- materials: commands.map(({ data }) => {
863
- const envelope = data;
864
- return { ...envelope, payload: { ...envelope.payload } };
865
- }),
866
- },
867
- };
868
- }
869
- }
870
-
871
- /**
872
- * Represents a command to toggle the embedded Metabox menu.
873
- * This command can only be used when using the metabox menu.
874
- *
875
- * ### What does it unlock?
876
- * Shows the embedded menu interface. Only works when using the MetaBox native menu (not in standalone/custom menu
877
- * mode).
878
- *
879
- * ### Practical Application
880
- * Toggles the native MetaBox right sidebar menu. Takes a boolean parameter. Pass false to hide when building custom UI.
881
- * In standalone mode, the menu is already hidden — this is only relevant in default (non-standalone) mode.
882
- *
883
- * ### AI Coding Best Practices
884
- * In standalone mode (`{standalone:true}`), this is unnecessary (menu already hidden). In default mode,
885
- * call `new ShowEmbeddedMenu(false)` early in initialization to hide built-in UI before rendering custom controls.
886
- * Pattern for custom UI: `ShowEmbeddedMenu(false)` + `ShowOverlayInterface(false)`.
887
- *
888
- * @example
889
- * import { ShowEmbeddedMenu, Communicator } from '@3dsource/metabox-modular-configurator-api';
890
- * window.env3DSource.apiReady = (api: Communicator) => {
891
- * api.sendCommandToMetabox(new ShowEmbeddedMenu(true));
892
- * };
893
- *
894
- * @param {boolean} visible - A flag indicating whether the embedded menu should be visible.
895
- */
896
- class ShowEmbeddedMenu extends CommandBase {
897
- constructor(visible) {
898
- super();
899
- this.data = {
900
- action: MetaboxModularConfiguratorActions.showEmbeddedMenu,
901
- payload: { visible },
902
- };
903
- }
904
- }
905
-
906
- /**
907
- * Represents a command to toggle the Unreal Overlay Interface Menu.
908
- * This action sends a message to the Metabox API to toggle the visibility of the Unreal overlay UI.
909
- *
910
- * ### What does it unlock?
911
- * Shows the overlay interface elements. Displays UI controls and buttons overlaid on the 3D scene.
912
- *
913
- * ### Practical Application
914
- * Toggles viewport overlay controls (buttons overlaid on the 3D scene). Takes a boolean.
915
- * Use `ShowOverlayInterface(false)` alongside `ShowEmbeddedMenu(false)` when building fully custom UI
916
- * that replaces all native MetaBox controls.
917
- *
918
- * ### AI Coding Best Practices
919
- * In standalone mode, overlays are already hidden. In default mode, call `new ShowOverlayInterface(false)`
920
- * early in initialization to prevent flash of native UI. Always pair with `ShowEmbeddedMenu(false)` for clean custom UI.
921
- * Pass true to restore if entering a mode that uses native controls.
922
- *
923
- * @example
924
- * import { ShowOverlayInterface, Communicator } from '@3dsource/metabox-modular-configurator-api';
925
- * window.env3DSource.apiReady = (api: Communicator) => {
926
- * api.sendCommandToMetabox(new ShowOverlayInterface(true));
927
- * };
928
- *
929
- * @param {boolean} visible - A flag indicating whether the Unreal overlay UI should be visible.
930
- */
931
- class ShowOverlayInterface extends CommandBase {
932
- constructor(visible) {
933
- super();
934
- this.data = {
935
- action: MetaboxModularConfiguratorActions.showOverlayInterface,
936
- payload: { visible },
937
- };
938
- }
939
- }
940
-
941
- /**
942
- * Represents a command to show measurement for a product when it is already loaded.
943
- * This class sends a command to the Metabox API to show measurement for a product if it is already initialized.
944
- *
945
- * ### What does it unlock?
946
- * Shows the measurement overlay. Works as a toggle with HideMeasurement to control visibility.
947
- *
948
- * ### Practical Application
949
- * Shows the measurement/dimension overlay tools on the 3D viewport. Use for B2B or technical applications
950
- * where buyers need to verify product dimensions, check fit specifications, or confirm measurements during procurement.
951
- *
952
- * ### AI Coding Best Practices
953
- * Call `api.sendCommandToMetabox(new ShowMeasurement())`. No parameters. Pair with HideMeasurement for toggle behavior.
954
- * Track visibility state in your app to keep toggle buttons in sync.
955
- *
956
- * @example
957
- * import { ShowMeasurement, Communicator } from '@3dsource/metabox-modular-configurator-api';
958
- * window.env3DSource.apiReady = (api: Communicator) => {
959
- * api.sendCommandToMetabox(new ShowMeasurement());
960
- * };
961
- */
962
- class ShowMeasurement extends CommandBase {
963
- constructor() {
964
- super();
965
- this.data = { action: MetaboxModularConfiguratorActions.showMeasurement };
966
- }
967
- }
968
-
969
- /**
970
- * Represents a command to hide measurement for a product when it is already loaded.
971
- * This class sends a command to the Metabox API to hide measurement for a product if it is already initialized.
972
- *
973
- * ### What does it unlock?
974
- * Hides the measurement overlay. Executes unconditionally to hide the UI controls.
975
- *
976
- * ### Practical Application
977
- * Hides the measurement/dimension overlay. Use when transitioning from a technical spec view back to a clean
978
- * product presentation, or to keep consumer-facing configurators visually clean.
979
- *
980
- * ### AI Coding Best Practices
981
- * Call `api.sendCommandToMetabox(new HideMeasurement())`. No parameters. Pair with ShowMeasurement as a toggle.
982
- * Track visibility state in your app state to keep toggle buttons in sync.
983
- *
984
- * @example
985
- * import { HideMeasurement, Communicator } from '@3dsource/metabox-modular-configurator-api';
986
- * window.env3DSource.apiReady = (api: Communicator) => {
987
- * api.sendCommandToMetabox(new HideMeasurement());
988
- * };
989
- */
990
- class HideMeasurement extends CommandBase {
991
- constructor() {
992
- super();
993
- this.data = { action: MetaboxModularConfiguratorActions.hideMeasurement };
994
- }
995
- }
996
-
997
- /**
998
- * Represents a command to resume the pixel streaming session.
999
- * This class sends a message to the Metabox API to resume a paused or disconnected stream.
1000
- *
1001
- * ### What does it unlock?
1002
- * Resumes the Unreal Engine pixel streaming connection after it has been paused, disconnected, or stopped due to inactivity (AFK timeout).
1003
- *
1004
- * ### Practical Application
1005
- * Used to reconnect the 3D streaming session without a full page reload. Essential for 'Reconnect' or 'Resume' buttons
1006
- * shown when the stream is interrupted, e.g., after an idle timeout or network disruption.
1007
- *
1008
- * ### AI Coding Best Practices
1009
- * Call `api.sendCommandToMetabox(new ResumeStream())`. No parameters. Resumes the existing streaming session —
1010
- * does not reinitialize the configurator or reset component/environment state.
1011
- *
1012
- * @example
1013
- * import { ResumeStream, Communicator } from '@3dsource/metabox-modular-configurator-api';
1014
- * window.env3DSource.apiReady = (api: Communicator) => {
1015
- * api.sendCommandToMetabox(new ResumeStream());
1016
- * };
1017
- */
1018
- class ResumeStream extends CommandBase {
1019
- constructor() {
1020
- super();
1021
- this.data = { action: MetaboxModularConfiguratorActions.resumeStream };
1022
- }
1023
- }
1024
-
1025
- /**
1026
- * Represents a command to stop the pixel streaming session.
1027
- * This class sends a message to the Metabox API to stop the active stream and release its resources.
1028
- *
1029
- * ### What does it unlock?
1030
- * Stops the Unreal Engine pixel streaming connection, terminating the active session and freeing server-side resources.
1031
- *
1032
- * ### Practical Application
1033
- * Used to explicitly end the 3D streaming session — e.g., when the user closes a modal, navigates away, or a
1034
- * custom "Stop"/"Disconnect" button is pressed. Pair with {@link ResumeStream} to restart the session later
1035
- * without a full page reload.
1036
- *
1037
- * ### AI Coding Best Practices
1038
- * Call `api.sendCommandToMetabox(new StopStream())`. No parameters. Stops the existing streaming session —
1039
- * does not reset component/environment state. Use `ResumeStream` to reconnect afterwards.
1040
- *
1041
- * @example
1042
- * import { StopStream, Communicator } from '@3dsource/metabox-modular-configurator-api';
1043
- * window.env3DSource.apiReady = (api: Communicator) => {
1044
- * api.sendCommandToMetabox(new StopStream());
1045
- * };
1046
- */
1047
- class StopStream extends CommandBase {
1048
- constructor() {
1049
- super();
1050
- this.data = { action: MetaboxModularConfiguratorActions.stopStream };
1051
- }
1052
- }
1053
-
1054
- /**
1055
- * Represents a command to reset the user inactivity (AFK) timer.
1056
- * This class sends a message to the Metabox API to restart the inactivity countdown,
1057
- * keeping the session alive when activity is detected programmatically.
1058
- *
1059
- * ### What does it unlock?
1060
- * Resets the AFK inactivity timer, preventing an imminent disconnect when the countdown is active.
1061
- *
1062
- * ### Practical Application
1063
- * Used to programmatically signal user activity and reset the inactivity countdown.
1064
- * Pair with the `userInactivityDetected` event to show a custom "Stay connected?" prompt
1065
- * and call this command when the user confirms, dismissing the countdown.
1066
- *
1067
- * ### AI Coding Best Practices
1068
- * Call `api.sendCommandToMetabox(new ResetUserInactivityTimer())`. No parameters.
1069
- * Typically triggered from a "Stay connected" or "I'm still here" button rendered when
1070
- * `userInactivityDetected.countdownVisible` is `true`.
1071
- *
1072
- * @example
1073
- * import { ResetUserInactivityTimer, Communicator } from '@3dsource/metabox-modular-configurator-api';
1074
- * window.env3DSource.apiReady = (api: Communicator) => {
1075
- * api.addEventListener('userInactivityDetected', ({ countdownVisible }) => {
1076
- * if (countdownVisible) {
1077
- * // show custom UI, then on user confirmation:
1078
- * api.sendCommandToMetabox(new ResetUserInactivityTimer());
1079
- * }
1080
- * });
1081
- * };
1082
- */
1083
- class ResetUserInactivityTimer extends CommandBase {
1084
- constructor() {
1085
- super();
1086
- this.data = {
1087
- action: MetaboxModularConfiguratorActions.resetUserInactivityTimer,
1088
- };
1089
- }
1090
- }
1091
-
1092
- /**
1093
- * EventDispatcher is a class that manages event listeners and dispatches events to them.
1094
- *
1095
- * ### What does it unlock?
1096
- * Parent class of Communicator that dispatches commands. Acts as an event dispatcher that routes command messages internally.
1097
- *
1098
- * ### Practical Application
1099
- * Internal event routing layer — parent class of Communicator. Routes postMessage commands between your app
1100
- * and the Unreal Engine pixel stream. Not used directly but understanding it helps debug message delivery issues.
1101
- *
1102
- * ### AI Coding Best Practices
1103
- * Do not reference or extend EventDispatcher in application code. Use only the Communicator interface methods.
1104
- * If debugging communication failures, check browser console for postMessage errors related to this layer.
1105
- */
1106
- class EventDispatcher {
1107
- constructor() {
1108
- /**
1109
- * Storage for callback listeners by message type.
1110
- */
1111
- this.listeners = [];
1112
- }
1113
- /**
1114
- * Removes all registered listeners. Subclasses override this to perform additional cleanup.
1115
- * @param key - Instance key (used by subclass overrides for registry cleanup).
1116
- */
1117
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
1118
- destroy(key) {
1119
- this.listeners = [];
1120
- }
1121
- /**
1122
- * Adds an event listener for receiving specific types of messages.
1123
- *
1124
- * @param {string} messageType - The message type to listen for.
1125
- * @param callback - The callback function to execute when a message is received.
1126
- */
1127
- addEventListener(messageType, callback) {
1128
- this.listeners.push({ messageType, callback });
1129
- return this;
1130
- }
1131
- /**
1132
- * Dispatches an event to all listeners of a specific message type.
1133
- *
1134
- * @param {string} messageType - The message type.
1135
- * @param data - The data associated with the event.
1136
- */
1137
- dispatchEvent(messageType, data) {
1138
- // Allocation-free dispatch on the hot message path. The length snapshot
1139
- // keeps the previous filter-snapshot semantics: listeners added during
1140
- // dispatch are not invoked for this event, and removeEventListener
1141
- // reassigns the array so the in-flight loop is unaffected.
1142
- const listeners = this.listeners;
1143
- const len = listeners.length;
1144
- for (let i = 0; i < len; i++) {
1145
- const listener = listeners[i];
1146
- if (listener.messageType === messageType) {
1147
- listener.callback(data);
1148
- }
1149
- }
1150
- return this;
1151
- }
1152
- /**
1153
- * Removes an event listener for a specific type of message.
1154
- *
1155
- * @param {string} messageType - The message type.
1156
- * @param callback - The callback function to remove.
1157
- */
1158
- removeEventListener(messageType, callback) {
1159
- this.listeners = this.listeners.filter((listener) => !(listener.messageType === messageType && listener.callback === callback));
1160
- return this;
1161
- }
1162
- }
1163
-
1164
- /**
1165
- * @internal
1166
- * @hidden
1167
- * Core constants used for host-to-iframe communication and URL construction.
1168
- */
1169
- /**
1170
- * Storage key for the Metabox Communicator instance registry.
1171
- *
1172
- * ### What does it unlock?
1173
- * Constant string identifier for MetaBox version. Used internally to reference the MetaBox system and versioning.
1174
- *
1175
- * ### Practical Application
1176
- * Internal system reference for versioning.
1177
- * Not needed in front-end application code.
1178
- *
1179
- * ### AI Coding Best Practices
1180
- * Skip in application code. This constant is for internal MetaBox system identification only.
1181
- *
1182
- * @internal
1183
- */
1184
- const Metabox = 'metabox';
1185
- /**
1186
- * Identifier used as the `host` field in postMessage envelopes sent to the iframe.
1187
- *
1188
- * ### What does it unlock?
1189
- * Constant for the MetaBox host connection point. Specifies endpoint for MetaBox connections.
1190
- *
1191
- * ### Practical Application
1192
- * MetaBox endpoint constant. The host the configurator iframe connects to for Unreal Engine pixel streaming.
1193
- * Not needed in front-end application code.
1194
- *
1195
- * ### AI Coding Best Practices
1196
- * Skip in application code. This constant is for internal MetaBox system identification only.
1197
- *
1198
- * @internal
1199
- */
1200
- const MetaboxHost = 'metaboxHost';
1201
- /**
1202
- * Action string dispatched by the iframe when the configurator app has loaded.
1203
- *
1204
- * ### What does it unlock?
1205
- * App initialization flag variable. Signals when MetaBox has completed loading.
1206
- *
1207
- * ### Practical Application
1208
- * Use the viewportReady event (more reliable) to gate your UI rendering — don't show controls until MetaBox confirms it's ready.
1209
- *
1210
- * ### AI Coding Best Practices
1211
- * Prefer the viewportReady event over this variable: `api.addEventListener('viewportReady', (ready) => { if(ready) enableUI(); })`.
1212
- * viewportReady is the reliable signal that MetaBox is ready to accept commands.
1213
- *
1214
- * @internal
1215
- */
1216
- const AppLoaded = 'appLoaded';
1217
- /**
1218
- * Default MetaBox domain for production environments.
1219
- *
1220
- * ### What does it unlock?
1221
- * Constant for the standard default MetaBox domain. Used as the primary domain for connecting to MetaBox server.
1222
- *
1223
- * ### Practical Application
1224
- * Default MetaBox domain constant (HTTPS). The base domain used when no override is specified.
1225
- * Override only via IntegrateMetaboxConfig.domain if connecting to a custom or self-hosted MetaBox instance.
1226
- *
1227
- * ### AI Coding Best Practices
1228
- * Let integrateMetabox() use the default. Override only if needed:
1229
- * `integrateMetabox(id, container, callback, { domain: 'https://custom.domain.com' })`. HTTPS is mandatory.
1230
- *
1231
- * @internal
1232
- */
1233
- /**
1234
- * @deprecated
1235
- */
1236
- const Metabox_V3 = 'metabox_v3';
1237
- /**
1238
- * @deprecated
1239
- */
1240
- const MetaboxHost_V3 = 'metaboxHost_v3';
1241
- /**
1242
- * @deprecated
1243
- */
1244
- const AppLoaded_V3 = 'appLoaded_v3';
1245
- const MetaboxDomain = 'metabox.3dsource.com';
1246
- /**
1247
- * Base route URL segment for the Modular Configurator.
1248
- *
1249
- * ### What does it unlock?
1250
- * Base route URL constant used for loading the configurator. Standard path endpoint for accessing the modular configurator.
1251
- *
1252
- * ### Practical Application
1253
- * The modular configurator URL format is: `https://{domain}/metabox-configurator/modular/{configuratorId}`.
1254
- * Automatically constructed by integrateMetabox().
1255
- *
1256
- * ### AI Coding Best Practices
1257
- * Let integrateMetabox() handle URL construction. Only reference if building URLs manually
1258
- * (e.g., QR codes, email links, server-side rendering). The modular path is `/modular/{id}`.
1259
- *
1260
- * @internal
1261
- */
1262
- const BasicRouteUrl = 'metabox-configurator/modular';
1263
-
1264
- const VERSION = '3.0.36-dev.0';
1265
-
1266
- /**
1267
- * Sender checks for the host↔iframe `postMessage` channel.
1268
- *
1269
- * Deliberately not re-exported from `./index` — `public-api.ts` does
1270
- * `export * from './lib/helpers'`, and these are internal plumbing.
1271
- */
1272
- /** Id of the iframe `integrateMetabox` creates; also the hand-rolled-embed contract. */
1273
- const EmbeddedContentId = 'embeddedContent';
1274
- /** `postMessage` targetOrigin meaning "any origin, deliver to that window". */
1275
- const AnyOrigin = '*';
1276
- /**
1277
- * True iff `origin` can be used as a `postMessage` targetOrigin: a parseable
1278
- * http/https origin *and nothing more*. Excludes `''` and the opaque `'null'`
1279
- * origin (sandboxed frames, `file:`, `data:`), which are not valid targets, and
1280
- * anything carrying a path, query or credentials — every real source here
1281
- * (`URL#origin`, `MessageEvent#origin`) yields a bare origin, so a decorated
1282
- * string means the value did not come from where we think it did.
1283
- *
1284
- * `postMessage` throws a `SyntaxError` on a malformed targetOrigin and silently
1285
- * drops the message on a mismatched one, so this has to be checked up front.
1286
- */
34
+ var MetaboxConfig = class extends CommandBase {
35
+ constructor(appId, config) {
36
+ super();
37
+ this.data = {
38
+ action: MetaboxModularConfiguratorActions.metaboxConfig,
39
+ payload: {
40
+ appId,
41
+ config
42
+ }
43
+ };
44
+ }
45
+ };
46
+ var GetPdf = class extends CommandBase {
47
+ constructor() {
48
+ super();
49
+ this.data = { action: MetaboxModularConfiguratorActions.getPdf };
50
+ }
51
+ };
52
+ var GetCallToActionInformation = class extends CommandBase {
53
+ constructor() {
54
+ super();
55
+ this.data = { action: MetaboxModularConfiguratorActions.getCallToActionInformation };
56
+ }
57
+ };
58
+ var GetCamera = class extends CommandBase {
59
+ constructor() {
60
+ super();
61
+ this.data = { action: MetaboxModularConfiguratorActions.getCamera };
62
+ }
63
+ };
64
+ var SetCamera = class extends CommandBase {
65
+ constructor(camera) {
66
+ super();
67
+ this.data = {
68
+ action: MetaboxModularConfiguratorActions.setCamera,
69
+ payload: { camera }
70
+ };
71
+ }
72
+ };
73
+ var ResetCamera = class extends CommandBase {
74
+ constructor() {
75
+ super();
76
+ this.data = { action: MetaboxModularConfiguratorActions.resetCamera };
77
+ }
78
+ };
79
+ var ResetConfiguration = class extends CommandBase {
80
+ constructor() {
81
+ super();
82
+ this.data = { action: MetaboxModularConfiguratorActions.resetConfiguration };
83
+ }
84
+ };
85
+ var ApplyZoom = class extends CommandBase {
86
+ constructor(zoom) {
87
+ super();
88
+ this.data = {
89
+ action: MetaboxModularConfiguratorActions.applyZoom,
90
+ payload: { zoom }
91
+ };
92
+ }
93
+ };
94
+ var InitShowcase = class extends CommandBase {
95
+ constructor() {
96
+ super();
97
+ this.data = { action: MetaboxModularConfiguratorActions.initShowcase };
98
+ }
99
+ };
100
+ var PlayShowcase = class extends CommandBase {
101
+ constructor() {
102
+ super();
103
+ this.data = { action: MetaboxModularConfiguratorActions.playShowcase };
104
+ }
105
+ };
106
+ var UnrealCommand = class extends CommandBase {
107
+ constructor(payload) {
108
+ super();
109
+ this.data = {
110
+ action: MetaboxModularConfiguratorActions.sendCommandToUnreal,
111
+ payload
112
+ };
113
+ }
114
+ };
115
+ var PauseShowcase = class extends CommandBase {
116
+ constructor() {
117
+ super();
118
+ this.data = { action: MetaboxModularConfiguratorActions.pauseShowcase };
119
+ }
120
+ };
121
+ var StopShowcase = class extends CommandBase {
122
+ constructor() {
123
+ super();
124
+ this.data = { action: MetaboxModularConfiguratorActions.stopShowcase };
125
+ }
126
+ };
127
+ var GetScreenshot = class extends CommandBase {
128
+ constructor(mimeType, size) {
129
+ super();
130
+ this.data = {
131
+ action: MetaboxModularConfiguratorActions.getScreenshot,
132
+ payload: {
133
+ format: mimeType,
134
+ size
135
+ }
136
+ };
137
+ }
138
+ };
139
+ var SetComponent = class extends CommandBase {
140
+ constructor(id, typeId) {
141
+ super();
142
+ this.data = {
143
+ payload: {
144
+ id,
145
+ typeId
146
+ },
147
+ action: MetaboxModularConfiguratorActions.setComponent
148
+ };
149
+ }
150
+ };
151
+ var SetComponentMaterial = class extends CommandBase {
152
+ constructor(componentId, slotId, materialId) {
153
+ super();
154
+ this.data = {
155
+ payload: {
156
+ componentId,
157
+ slotId,
158
+ materialId
159
+ },
160
+ action: MetaboxModularConfiguratorActions.setComponentMaterialById
161
+ };
162
+ }
163
+ };
164
+ var SetEnvironment = class extends CommandBase {
165
+ constructor(environmentId) {
166
+ super();
167
+ this.data = {
168
+ action: MetaboxModularConfiguratorActions.setEnvironment,
169
+ payload: { id: environmentId }
170
+ };
171
+ }
172
+ };
173
+ var SetEnvironmentMaterial = class extends CommandBase {
174
+ constructor(slotId, materialId) {
175
+ super();
176
+ this.data = {
177
+ action: MetaboxModularConfiguratorActions.setEnvironmentMaterialById,
178
+ payload: {
179
+ slotId,
180
+ materialId
181
+ }
182
+ };
183
+ }
184
+ };
185
+ var SetMaterials = class extends CommandBase {
186
+ constructor(commands) {
187
+ super();
188
+ this.data = {
189
+ action: MetaboxModularConfiguratorActions.setMaterials,
190
+ payload: { materials: commands.map(({ data }) => {
191
+ const envelope = data;
192
+ return {
193
+ ...envelope,
194
+ payload: { ...envelope.payload }
195
+ };
196
+ }) }
197
+ };
198
+ }
199
+ };
200
+ var ShowEmbeddedMenu = class extends CommandBase {
201
+ constructor(visible) {
202
+ super();
203
+ this.data = {
204
+ action: MetaboxModularConfiguratorActions.showEmbeddedMenu,
205
+ payload: { visible }
206
+ };
207
+ }
208
+ };
209
+ var ShowOverlayInterface = class extends CommandBase {
210
+ constructor(visible) {
211
+ super();
212
+ this.data = {
213
+ action: MetaboxModularConfiguratorActions.showOverlayInterface,
214
+ payload: { visible }
215
+ };
216
+ }
217
+ };
218
+ var ShowMeasurement = class extends CommandBase {
219
+ constructor() {
220
+ super();
221
+ this.data = { action: MetaboxModularConfiguratorActions.showMeasurement };
222
+ }
223
+ };
224
+ var HideMeasurement = class extends CommandBase {
225
+ constructor() {
226
+ super();
227
+ this.data = { action: MetaboxModularConfiguratorActions.hideMeasurement };
228
+ }
229
+ };
230
+ var ResumeStream = class extends CommandBase {
231
+ constructor() {
232
+ super();
233
+ this.data = { action: MetaboxModularConfiguratorActions.resumeStream };
234
+ }
235
+ };
236
+ var StopStream = class extends CommandBase {
237
+ constructor() {
238
+ super();
239
+ this.data = { action: MetaboxModularConfiguratorActions.stopStream };
240
+ }
241
+ };
242
+ var ResetUserInactivityTimer = class extends CommandBase {
243
+ constructor() {
244
+ super();
245
+ this.data = { action: MetaboxModularConfiguratorActions.resetUserInactivityTimer };
246
+ }
247
+ };
248
+ var EventDispatcher = class {
249
+ constructor() {
250
+ this.listeners = [];
251
+ }
252
+ destroy(key) {
253
+ this.listeners = [];
254
+ }
255
+ addEventListener(messageType, callback) {
256
+ this.listeners.push({
257
+ messageType,
258
+ callback
259
+ });
260
+ return this;
261
+ }
262
+ dispatchEvent(messageType, data) {
263
+ const listeners = this.listeners;
264
+ const len = listeners.length;
265
+ for (let i = 0; i < len; i++) {
266
+ const listener = listeners[i];
267
+ if (listener.messageType === messageType) listener.callback(data);
268
+ }
269
+ return this;
270
+ }
271
+ removeEventListener(messageType, callback) {
272
+ this.listeners = this.listeners.filter((listener) => !(listener.messageType === messageType && listener.callback === callback));
273
+ return this;
274
+ }
275
+ };
276
+ const Metabox = "metabox";
277
+ const MetaboxHost = "metaboxHost";
278
+ const AppLoaded = "appLoaded";
279
+ const Metabox_V3 = "metabox_v3";
280
+ const MetaboxHost_V3 = "metaboxHost_v3";
281
+ const AppLoaded_V3 = "appLoaded_v3";
282
+ const MetaboxDomain = "metabox.3dsource.com";
283
+ const BasicRouteUrl = "metabox-configurator/modular";
284
+ const VERSION = "3.0.37";
285
+ const EmbeddedContentId = "embeddedContent";
1287
286
  function isTargetableOrigin(origin) {
1288
- if (!origin || origin === AnyOrigin || origin === 'null') {
1289
- return false;
1290
- }
1291
- let url;
1292
- try {
1293
- url = new URL(origin);
1294
- }
1295
- catch {
1296
- return false;
1297
- }
1298
- if (url.protocol !== 'https:' && url.protocol !== 'http:') {
1299
- return false;
1300
- }
1301
- // `URL#origin` drops path/query/hash/credentials and normalises the default
1302
- // port away, so this holds exactly for bare origins.
1303
- return url.origin === origin;
287
+ if (!origin || origin === "*" || origin === "null") return false;
288
+ let url;
289
+ try {
290
+ url = new URL(origin);
291
+ } catch {
292
+ return false;
293
+ }
294
+ if (url.protocol !== "https:" && url.protocol !== "http:") return false;
295
+ return url.origin === origin;
1304
296
  }
1305
- /**
1306
- * Decides whether an inbound `message` event may drive this Communicator.
1307
- *
1308
- * Before this gate the only check was `event.data.host === 'metabox'`, a string
1309
- * anyone can write. That matters most inside the configurator itself, which runs
1310
- * a Communicator in its own window for the embedded menu: without a sender check
1311
- * the embedding page could forge configurator *events* (screenshots handed to
1312
- * `saveImage`, catalogue/CTA data) that its own inbound guard is built to reject.
1313
- *
1314
- * The discriminator is `environment`, not the DOM: inside the configurator there
1315
- * is no `#embeddedContent` element (it does not embed itself), so a purely
1316
- * DOM-based check would fall through to "accept anything" and leave that exact
1317
- * vector open.
1318
- *
1319
- * - `'metabox'` — the peer is the same document, so only this window qualifies.
1320
- * Nothing here reads the DOM, so renaming an element cannot weaken it.
1321
- * - `'host'` — the peer is our iframe. When we have no handle on one, fall back
1322
- * to the same-window channel, mirroring `sendCommandToMetabox`, which posts to
1323
- * this window when it finds no iframe. Accepting that case keeps hand-rolled
1324
- * embeds working; a hard refusal would silently kill the API on those sites,
1325
- * which is how a domain allowlist broke this channel once already.
1326
- */
1327
297
  function acceptsMessageFrom(event, environment, iframe) {
1328
- const sameWindow = event.source === window && event.origin === window.location.origin;
1329
- if (environment === 'metabox') {
1330
- return sameWindow;
1331
- }
1332
- const own = resolveIframe(iframe)?.contentWindow;
1333
- if (own) {
1334
- return event.source === own;
1335
- }
1336
- // Our frame could not be identified: a hand-rolled embed that neither passed
1337
- // one in nor uses the contract id. Refusing would kill that integration
1338
- // silently, so accept any frame of *this* document — which still shuts out an
1339
- // opener, an ad frame or the parent, and matches the same-window fallback in
1340
- // `sendCommandToMetabox`.
1341
- return sameWindow || isFrameOfThisDocument(event.source);
298
+ const sameWindow = event.source === window && event.origin === window.location.origin;
299
+ if (environment === "metabox") return sameWindow;
300
+ const own = resolveIframe(iframe)?.contentWindow;
301
+ if (own) return event.source === own;
302
+ return sameWindow || isFrameOfThisDocument(event.source);
1342
303
  }
1343
- /** Whether `source` is the content window of an iframe in this document. */
1344
304
  function isFrameOfThisDocument(source) {
1345
- if (!source) {
1346
- return false;
1347
- }
1348
- return Array.from(document.querySelectorAll('iframe')).some((frame) => frame.contentWindow === source);
305
+ if (!source) return false;
306
+ return Array.from(document.querySelectorAll("iframe")).some((frame) => frame.contentWindow === source);
1349
307
  }
1350
- /**
1351
- * The iframe this Communicator talks to: the one the integration created while
1352
- * it is still in the document, else whatever currently holds the contract id.
1353
- * `isConnected` matters because a superseding `integrateMetabox` call removes the
1354
- * previous iframe, and a detached one would otherwise shadow the live element.
1355
- */
1356
308
  function resolveIframe(iframe) {
1357
- if (iframe?.isConnected) {
1358
- return iframe;
1359
- }
1360
- return document.getElementById(EmbeddedContentId);
1361
- }
1362
-
1363
- const communicatorMap = new Map();
1364
- /**
1365
- * Handles messaging between the host page and embedded Metabox content.
1366
- *
1367
- * ### What does it unlock?
1368
- * Internal class that creates a proxy/communication layer between the API and MetaBox.
1369
- * Handles reading and sending commands through the established connection.
1370
- *
1371
- * ### Practical Application
1372
- * The API handle returned in the integrateMetabox callback. Provides sendCommandToMetabox() to send commands,
1373
- * and addEventListener()/removeEventListener() for event subscriptions. This is your entire interface to
1374
- * the MetaBox Unreal Engine stream.
1375
- *
1376
- * ### AI Coding Best Practices
1377
- * Store the Communicator reference from the apiReadyCallback in a module-scoped variable or state store.
1378
- * NEVER send commands before this callback fires. All commands and event listeners go through this single
1379
- * api object. Clean up listeners with removeEventListener on component unmount.
1380
- *
1381
- * @internal Use {@link Communicator.createInstance} or the {@link integrateMetabox} helper to instantiate.
1382
- */
1383
- class Communicator extends EventDispatcher {
1384
- /**
1385
- * Constructs a Communicator, replacing any existing instance, and begins listening for messages.
1386
- * @internal
1387
- */
1388
- constructor(data, environment, config, connection) {
1389
- super();
1390
- /**
1391
- * Bound handler for incoming postMessage events.
1392
- */
1393
- this.binder = this.handleMessageReceived.bind(this);
1394
- /** Keeps the "rejected an inbound message" warning to one per instance. */
1395
- this.senderRejectionReported = false;
1396
- /** Keeps the "unknown configurator origin" warning to one per instance. */
1397
- this.wildcardTargetReported = false;
1398
- /** Keeps the "our iframe left the document" warning to one per instance. */
1399
- this.staleFrameReported = false;
1400
- // Assigned before the listener goes up: the gate reads all three.
1401
- this.environment = environment;
1402
- this.iframe = connection?.iframe ?? null;
1403
- this.targetOrigin = isTargetableOrigin(connection?.origin)
1404
- ? connection.origin
1405
- : null;
1406
- const { appId = 'unknown', version = VERSION } = data ?? {};
1407
- const key = `${version}_${environment}_${appId}`;
1408
- communicatorMap.get(key)?.instance.destroy(key);
1409
- communicatorMap.set(key, { instance: this });
1410
- window.addEventListener('message', this.binder);
1411
- this.sendCommandToMetabox(new MetaboxConfig(appId, {
1412
- ...config,
1413
- hostUrl: location.href,
1414
- apiVersion: VERSION,
1415
- }));
1416
- }
1417
- /**
1418
- * Listens for Metabox to signal readiness, then initializes communicator.
1419
- * @param apiReadyCallback - Called with the new Communicator once the Metabox is loaded.
1420
- * @param {MetaboxEnvironment} environment - The environment in which the Communicator is running.
1421
- * @param {MetaboxCommandConfig} config - optional initial config: standalone - if true - disable metabox custom template and all logic
1422
- * @param {CommunicatorConnection} connection - the iframe and origin `integrateMetabox`
1423
- * built, so the handshake can be attributed and later messages addressed precisely.
1424
- * Omitted by hand-rolled embeds, which are then identified through the
1425
- * `embeddedContent` id and the handshake's own origin.
1426
- * @returns A cancel function that removes the handshake `message` listener.
1427
- * `integrateMetabox` (the public entry point) calls this automatically when
1428
- * a new integration supersedes a still-pending one, so direct internal
1429
- * callers only need it for explicit early teardown. Idempotent.
1430
- */
1431
- static createInstance(apiReadyCallback, environment, config, connection) {
1432
- const iframe = connection?.iframe ?? null;
1433
- // The handshake listener outlives every rejected message, so the report is
1434
- // kept to one: a page that keeps announcing itself must not flood the
1435
- // console of the site embedding us.
1436
- let rejectionReported = false;
1437
- const startHandler = (event) => {
1438
- const message = event.data;
1439
- if (message?.envelope?.action !== AppLoaded || message.host !== Metabox) {
1440
- return;
1441
- }
1442
- // The handshake decides who we hand the API to and which appId keys the
1443
- // registry, so it is gated exactly like every later message.
1444
- if (!acceptsMessageFrom(event, environment, iframe)) {
1445
- if (!rejectionReported) {
1446
- rejectionReported = true;
1447
- console.warn(`Metabox: ignored an "${AppLoaded}" handshake from an unexpected sender.`);
1448
- }
1449
- return;
1450
- }
1451
- apiReadyCallback(new Communicator(message.envelope.payload, environment, config, {
1452
- iframe,
1453
- origin: Communicator.resolveHandshakeOrigin(event, connection),
1454
- }));
1455
- window.removeEventListener('message', startHandler);
1456
- };
1457
- window.addEventListener('message', startHandler);
1458
- return () => window.removeEventListener('message', startHandler);
1459
- }
1460
- /**
1461
- * The origin to address the configurator by, decided once from the handshake.
1462
- *
1463
- * Prefers what `integrateMetabox` computed from the iframe URL, but yields to
1464
- * the origin the handshake actually came from when the two disagree: a redirect
1465
- * (a `config.domain` override pointing at a host that 30x's elsewhere) would
1466
- * otherwise pin an origin nothing answers on, and every command would be
1467
- * dropped silently. The sender already passed the window gate, so this cannot
1468
- * be steered by an unrelated page.
1469
- */
1470
- static resolveHandshakeOrigin(event, connection) {
1471
- const expected = isTargetableOrigin(connection?.origin)
1472
- ? connection.origin
1473
- : null;
1474
- const actual = isTargetableOrigin(event.origin) ? event.origin : null;
1475
- if (expected && actual && expected !== actual) {
1476
- console.warn(`Metabox: the configurator answered from ${actual} but was embedded from ${expected}; using ${actual}.`);
1477
- return actual;
1478
- }
1479
- return expected ?? actual;
1480
- }
1481
- /**
1482
- * Cleans up resources and stops listening for messages.
1483
- */
1484
- destroy(key) {
1485
- super.destroy(key);
1486
- window.removeEventListener('message', this.binder);
1487
- }
1488
- /** Destroys all active Communicator instances and clears the internal registry. */
1489
- static clearAll() {
1490
- if (communicatorMap.size === 0) {
1491
- return;
1492
- }
1493
- communicatorMap.forEach((value, key) => value.instance.destroy(key));
1494
- communicatorMap.clear();
1495
- }
1496
- /**
1497
- * Retrieves a registered Communicator instance by its key.
1498
- * @param key - The composite key (`version_environment_appId`) identifying the instance.
1499
- */
1500
- static getCommunicator(key) {
1501
- return communicatorMap.get(key);
1502
- }
1503
- /**
1504
- * Posts a command to the Metabox iframe.
1505
- * @param command - An action command containing data to send.
1506
- */
1507
- sendCommandToMetabox(command) {
1508
- const { data } = command;
1509
- const iframe = resolveIframe(this.iframe);
1510
- this.reportStaleFrame();
1511
- const toMetaboxMessage = {
1512
- host: MetaboxHost,
1513
- envelope: { ...data },
1514
- // Deprecated mirror of `envelope`. Kept as an independent clone so a
1515
- // receiver mutating one cannot observably change the other.
1516
- payload: { ...data },
1517
- target: iframe?.contentWindow ? 'child' : 'metabox',
1518
- apiVersion: VERSION,
1519
- };
1520
- if (!iframe?.contentWindow) {
1521
- console.warn('Metabox IFrame not found or not ready. Message sends to the same window');
1522
- // Same-window channel. '/' means "only deliver if the receiver's origin
1523
- // equals mine", which is exactly the intent and, unlike
1524
- // `window.location.origin`, also holds for an opaque origin: a page under
1525
- // `sandbox="allow-scripts"` reports the origin as the string "null",
1526
- // which is not a valid targetOrigin and makes postMessage throw.
1527
- window.postMessage(toMetaboxMessage, '/');
1528
- return;
1529
- }
1530
- iframe.contentWindow.postMessage(toMetaboxMessage, this.resolveTarget());
1531
- }
1532
- /**
1533
- * A superseding `integrateMetabox` call removes the iframe this handle was
1534
- * built for. Commands then fall through to whatever now holds the contract id,
1535
- * addressed by the origin pinned for the *old* integration — so if the new one
1536
- * points at a different origin, the browser drops them without a word. The
1537
- * handle is stale at that point and should be replaced by the one from the new
1538
- * integration; say so rather than letting it fail quietly.
1539
- */
1540
- reportStaleFrame() {
1541
- if (!this.iframe || this.iframe.isConnected || this.staleFrameReported) {
1542
- return;
1543
- }
1544
- this.staleFrameReported = true;
1545
- console.warn('Metabox: the iframe this API handle was created for has left the document. ' +
1546
- 'Commands are being sent to the current #embeddedContent instead — use the handle ' +
1547
- 'from the latest integrateMetabox() call.');
1548
- }
1549
- /**
1550
- * `targetOrigin` for the iframe. The very first command is `metaboxConfig`,
1551
- * which carries `hostUrl: location.href` — on a shop page that routinely holds
1552
- * order ids and session parameters — so it must not be broadcast to whatever
1553
- * document currently occupies the frame.
1554
- *
1555
- * Falls back to a wildcard rather than refusing to send: this leg carries
1556
- * commands, and a configurator that silently stops responding on a customer
1557
- * site is worse than the status quo. The fallback is reported once so it does
1558
- * not pass unnoticed.
1559
- */
1560
- resolveTarget() {
1561
- if (this.targetOrigin) {
1562
- return this.targetOrigin;
1563
- }
1564
- if (!this.wildcardTargetReported) {
1565
- this.wildcardTargetReported = true;
1566
- console.warn('Metabox: the configurator origin is unknown, so commands are broadcast. ' +
1567
- 'Use integrateMetabox() to have it pinned.');
1568
- }
1569
- return AnyOrigin;
1570
- }
1571
- /**
1572
- * Registers an event listener for messages dispatched by the Metabox.
1573
- * @param messageType - The event name to listen for (e.g. `'configuratorDataUpdated'`).
1574
- * @param callback - Handler invoked with the typed payload when the event fires.
1575
- * @override
1576
- */
1577
- addEventListener(messageType, callback) {
1578
- return super.addEventListener(messageType, callback);
1579
- }
1580
- /**
1581
- * Dispatches a typed event to all registered listeners.
1582
- * @param messageType - The event name to dispatch.
1583
- * @param data - The payload to pass to each listener.
1584
- * @override
1585
- */
1586
- dispatchEvent(messageType, data) {
1587
- return super.dispatchEvent(messageType, data);
1588
- }
1589
- /**
1590
- * Removes a previously registered event listener.
1591
- * @param messageType - The event name the listener was registered for.
1592
- * @param callback - The same function reference that was passed to {@link addEventListener}.
1593
- * @override
1594
- */
1595
- removeEventListener(messageType, callback) {
1596
- return super.removeEventListener(messageType, callback);
1597
- }
1598
- /**
1599
- * Filters and dispatches incoming messages from the Metabox.
1600
- * @param event - The postMessage event received on a window.
1601
- */
1602
- handleMessageReceived(event) {
1603
- if (event.data?.host !== Metabox) {
1604
- return;
1605
- }
1606
- // `host` is a string anyone can write, so it says nothing about who sent
1607
- // this. Everything below dispatches configurator events to application
1608
- // listeners — screenshots, catalogue and CTA data — so the sender is checked
1609
- // before any of it runs.
1610
- if (!acceptsMessageFrom(event, this.environment, this.iframe)) {
1611
- if (!this.senderRejectionReported) {
1612
- this.senderRejectionReported = true;
1613
- console.warn(`Metabox: ignored a "${Metabox}" message from an unexpected sender ` +
1614
- `(environment: ${this.environment}). Events are only accepted from the configurator.`);
1615
- }
1616
- return;
1617
- }
1618
- const data = event.data?.envelope;
1619
- this.dispatchEvent(data?.eventType, data?.payload);
1620
- }
1621
- }
1622
-
1623
- /**
1624
- * Constructs the iframe source URL for the Metabox Modular Configurator.
1625
- *
1626
- * ### What does it unlock?
1627
- * Utility function that prepares the iframe source URL. Constructs the proper URL with parameters
1628
- * for loading the MetaBox configurator.
1629
- *
1630
- * ### Practical Application
1631
- * Utility function that constructs the iframe source URL with proper parameters.
1632
- * URL format: `https://{domain}/metabox-configurator/modular/{configuratorId}`.
1633
- * Called internally by integrateMetabox() — use directly only for manual URL construction.
1634
- *
1635
- * ### AI Coding Best Practices
1636
- * Usually called internally. Use directly only for pre-constructing embed URLs (QR codes, email links,
1637
- * preview URLs). Verify output is HTTPS. Remember modular configurators use `/modular/` path.
1638
- *
1639
- * @internal
1640
- * @hidden
1641
- *
1642
- * @param {string} configuratorId - An string identifier for the configurator.
1643
- * @param {IntegrateMetaboxConfig} config - An object containing the configuration options.
1644
- */
309
+ if (iframe?.isConnected) return iframe;
310
+ return document.getElementById(EmbeddedContentId);
311
+ }
312
+ const communicatorMap = /* @__PURE__ */ new Map();
313
+ var Communicator = class Communicator extends EventDispatcher {
314
+ constructor(data, environment, config, connection) {
315
+ super();
316
+ this.binder = this.handleMessageReceived.bind(this);
317
+ this.senderRejectionReported = false;
318
+ this.wildcardTargetReported = false;
319
+ this.staleFrameReported = false;
320
+ this.environment = environment;
321
+ this.iframe = connection?.iframe ?? null;
322
+ this.targetOrigin = isTargetableOrigin(connection?.origin) ? connection.origin : null;
323
+ const { appId = "unknown", version = VERSION } = data ?? {};
324
+ const key = `${version}_${environment}_${appId}`;
325
+ communicatorMap.get(key)?.instance.destroy(key);
326
+ communicatorMap.set(key, { instance: this });
327
+ window.addEventListener("message", this.binder);
328
+ this.sendCommandToMetabox(new MetaboxConfig(appId, {
329
+ ...config,
330
+ hostUrl: location.href,
331
+ apiVersion: VERSION
332
+ }));
333
+ }
334
+ static createInstance(apiReadyCallback, environment, config, connection) {
335
+ const iframe = connection?.iframe ?? null;
336
+ let rejectionReported = false;
337
+ const startHandler = (event) => {
338
+ const message = event.data;
339
+ if (message?.envelope?.action !== "appLoaded" || message.host !== "metabox") return;
340
+ if (!acceptsMessageFrom(event, environment, iframe)) {
341
+ if (!rejectionReported) {
342
+ rejectionReported = true;
343
+ console.warn(`Metabox: ignored an "${AppLoaded}" handshake from an unexpected sender.`);
344
+ }
345
+ return;
346
+ }
347
+ apiReadyCallback(new Communicator(message.envelope.payload, environment, config, {
348
+ iframe,
349
+ origin: Communicator.resolveHandshakeOrigin(event, connection)
350
+ }));
351
+ window.removeEventListener("message", startHandler);
352
+ };
353
+ window.addEventListener("message", startHandler);
354
+ return () => window.removeEventListener("message", startHandler);
355
+ }
356
+ static resolveHandshakeOrigin(event, connection) {
357
+ const expected = isTargetableOrigin(connection?.origin) ? connection.origin : null;
358
+ const actual = isTargetableOrigin(event.origin) ? event.origin : null;
359
+ if (expected && actual && expected !== actual) {
360
+ console.warn(`Metabox: the configurator answered from ${actual} but was embedded from ${expected}; using ${actual}.`);
361
+ return actual;
362
+ }
363
+ return expected ?? actual;
364
+ }
365
+ destroy(key) {
366
+ super.destroy(key);
367
+ window.removeEventListener("message", this.binder);
368
+ }
369
+ static clearAll() {
370
+ if (communicatorMap.size === 0) return;
371
+ communicatorMap.forEach((value, key) => value.instance.destroy(key));
372
+ communicatorMap.clear();
373
+ }
374
+ static getCommunicator(key) {
375
+ return communicatorMap.get(key);
376
+ }
377
+ sendCommandToMetabox(command) {
378
+ const { data } = command;
379
+ const iframe = resolveIframe(this.iframe);
380
+ this.reportStaleFrame();
381
+ const toMetaboxMessage = {
382
+ host: MetaboxHost,
383
+ envelope: { ...data },
384
+ payload: { ...data },
385
+ target: iframe?.contentWindow ? "child" : "metabox",
386
+ apiVersion: VERSION
387
+ };
388
+ if (!iframe?.contentWindow) {
389
+ console.warn("Metabox IFrame not found or not ready. Message sends to the same window");
390
+ window.postMessage(toMetaboxMessage, "/");
391
+ return;
392
+ }
393
+ iframe.contentWindow.postMessage(toMetaboxMessage, this.resolveTarget());
394
+ }
395
+ reportStaleFrame() {
396
+ if (!this.iframe || this.iframe.isConnected || this.staleFrameReported) return;
397
+ this.staleFrameReported = true;
398
+ console.warn("Metabox: the iframe this API handle was created for has left the document. Commands are being sent to the current #embeddedContent instead — use the handle from the latest integrateMetabox() call.");
399
+ }
400
+ resolveTarget() {
401
+ if (this.targetOrigin) return this.targetOrigin;
402
+ if (!this.wildcardTargetReported) {
403
+ this.wildcardTargetReported = true;
404
+ console.warn("Metabox: the configurator origin is unknown, so commands are broadcast. Use integrateMetabox() to have it pinned.");
405
+ }
406
+ return "*";
407
+ }
408
+ addEventListener(messageType, callback) {
409
+ return super.addEventListener(messageType, callback);
410
+ }
411
+ dispatchEvent(messageType, data) {
412
+ return super.dispatchEvent(messageType, data);
413
+ }
414
+ removeEventListener(messageType, callback) {
415
+ return super.removeEventListener(messageType, callback);
416
+ }
417
+ handleMessageReceived(event) {
418
+ if (event.data?.host !== "metabox") return;
419
+ if (!acceptsMessageFrom(event, this.environment, this.iframe)) {
420
+ if (!this.senderRejectionReported) {
421
+ this.senderRejectionReported = true;
422
+ console.warn(`Metabox: ignored a "${Metabox}" message from an unexpected sender (environment: ${this.environment}). Events are only accepted from the configurator.`);
423
+ }
424
+ return;
425
+ }
426
+ const data = event.data?.envelope;
427
+ this.dispatchEvent(data?.eventType, data?.payload);
428
+ }
429
+ };
1645
430
  const prepareIframeSrc = (configuratorId, config) => {
1646
- const base = `https://${config?.domain || MetaboxDomain}/${BasicRouteUrl}/${configuratorId}`;
1647
- const params = new URLSearchParams();
1648
- if (config?.introImage) {
1649
- params.set('introImage', config.introImage);
1650
- }
1651
- if (config?.introVideo) {
1652
- params.set('introVideo', config.introVideo);
1653
- }
1654
- if (config?.loadingImage) {
1655
- params.set('loadingImage', config.loadingImage);
1656
- }
1657
- if (config?.state) {
1658
- params.set('state', decodeURIComponent(config.state));
1659
- }
1660
- if (config?.showLoadingProgress !== undefined) {
1661
- params.set('showLoadingProgress', String(config.showLoadingProgress));
1662
- }
1663
- if (config?.showResumeStreamPopup !== undefined) {
1664
- params.set('showResumeStreamPopup', String(config.showResumeStreamPopup));
1665
- }
1666
- if (config?.showUserInactivityTimer !== undefined) {
1667
- params.set('showUserInactivityTimer', String(config.showUserInactivityTimer));
1668
- }
1669
- if (config?.userInactivityTimeout !== undefined) {
1670
- params.set('userInactivityTimeout', String(config.userInactivityTimeout));
1671
- }
1672
- if (config?.autoStartStream !== undefined) {
1673
- params.set('autoStartStream', String(config.autoStartStream));
1674
- }
1675
- const query = params.toString();
1676
- return query ? `${base}?${query}` : base;
431
+ const base = `https://${config?.domain || "metabox.3dsource.com"}/${BasicRouteUrl}/${configuratorId}`;
432
+ const params = new URLSearchParams();
433
+ if (config?.introImage) params.set("introImage", config.introImage);
434
+ if (config?.introVideo) params.set("introVideo", config.introVideo);
435
+ if (config?.loadingImage) params.set("loadingImage", config.loadingImage);
436
+ if (config?.state) params.set("state", decodeURIComponent(config.state));
437
+ if (config?.showLoadingProgress !== void 0) params.set("showLoadingProgress", String(config.showLoadingProgress));
438
+ if (config?.showResumeStreamPopup !== void 0) params.set("showResumeStreamPopup", String(config.showResumeStreamPopup));
439
+ if (config?.showUserInactivityTimer !== void 0) params.set("showUserInactivityTimer", String(config.showUserInactivityTimer));
440
+ if (config?.userInactivityTimeout !== void 0) params.set("userInactivityTimeout", String(config.userInactivityTimeout));
441
+ if (config?.autoStartStream !== void 0) params.set("autoStartStream", String(config.autoStartStream));
442
+ const query = params.toString();
443
+ return query ? `${base}?${query}` : base;
1677
444
  };
1678
-
1679
- // Cancel for the previous integration's handshake listener while it is still
1680
- // waiting for the iframe to load. A new integrateMetabox call supersedes it —
1681
- // it already replaces the single embedded iframe — so a never-completed
1682
- // handshake (failed load, SPA remount, retry) can't leak a window 'message'
1683
- // listener for the page lifetime. Idempotent, so a completed handshake's
1684
- // cancel is a harmless no-op here.
1685
445
  let cancelPendingHandshake = null;
1686
- /**
1687
- * Integrates the Metabox Modular Configurator into the page by injecting an iframe and
1688
- * initializing a Communicator instance for host-to-iframe messaging.
1689
- *
1690
- * - Builds a secure iframe URL using the provided configuratorId and config options.
1691
- * - Ensures the resulting URL uses HTTPS and that the target container exists.
1692
- * - Removes any previously embedded iframe with id "embeddedContent" before inserting a new one.
1693
- *
1694
- * ### What does it unlock?
1695
- * Main initialization function for MetaBox integration. Initializes the configurator, receives an API handle,
1696
- * and sets up all configurations.
1697
- *
1698
- * ### Practical Application
1699
- * is THE entry point function. Creates the configurator iframe, establishes postMessage communication, and returns
1700
- * the Communicator api handle via callback. Call ONCE per configurator. Params: configuratorId (modular UUID),
1701
- * containerId (DOM element ID, default 'embed3DSource'), apiReadyCallback, config (IntegrateMetaboxConfig).
1702
- *
1703
- * ### AI Coding Best Practices
1704
- * Pattern: `integrateMetabox('uuid', 'div-id', (api) => {
1705
- * set up listeners, then set a root component, then environment, then children
1706
- * }, { standalone: true })`.
1707
- * Ensure a container div exists in DOM with non-zero dimensions. HTTPS required.
1708
- * Inside callback: 1) addEventListener for configuratorDataUpdated, 2) SetComponent root, 3) SetEnvironment,
1709
- * 4) SetComponent children, 5) SetComponentMaterial.
1710
- *
1711
- * @param {string} configuratorId - The Modular Configurator ID (not a full URL). It is appended to
1712
- * `https://{domain}/metabox-configurator/modular/{configuratorId}` to form the iframe src.
1713
- *
1714
- * @param {string} containerId - The id of the container element where the iframe will be injected.
1715
- *
1716
- * @param {(api: Communicator) => void} apiReadyCallback - Called when the Communicator instance is created on the host side.
1717
- *
1718
- * @param {IntegrateMetaboxConfig} config - Optional configuration used to build the iframe URL and initialize the communicator.
1719
- * Supported fields:
1720
- * - standalone?: boolean — if true, disables Metabox custom template and related logic.
1721
- * - introImage?: string — URL to an image shown on the intro screen (added as ?introImage=...).
1722
- * - introVideo?: string — URL to a video shown on the intro screen (added as ?introVideo=...).
1723
- * - loadingImage?: string — URL to an image displayed while loading (added as ?loadingImage=...).
1724
- * - state?: string — Predefined state for configurator for initial loading (added as ?state=...).
1725
- * - domain?: string — custom domain for testing (defaults to metabox.3dsource.com). HTTPS is enforced.
1726
- * - showLoadingProgress?: boolean — if true, shows the loading progress bar (added as ?showLoadingProgress=true).
1727
- * - showResumeStreamPopup?: boolean — if true, shows the resume stream popup (added as ?showResumeStreamPopup=true).
1728
- * - showUserInactivityTimer?: boolean — if true, shows the AFK countdown popup (added as ?showUserInactivityTimer=true).
1729
- * - userInactivityTimeout?: number — inactivity timeout in seconds before disconnect (added as ?userInactivityTimeout=...).
1730
- * - autoStartStream?: boolean — controls whether the pixel stream starts automatically on load (added as ?autoStartStream=...); set false to start it manually via ResumeStream.
1731
- *
1732
- * @throws Error If configuratorId or containerId are empty strings.
1733
- * @throws Error If the computed iframe URL is invalid or does not use HTTPS.
1734
- * @throws Error If the container element with the provided id cannot be found.
1735
- *
1736
- * @returns A cancel function that stops waiting for the Metabox to load.
1737
- * Calling it is optional — a later `integrateMetabox` call automatically
1738
- * supersedes a still-pending handshake — but it lets you remove the handshake
1739
- * listener immediately on teardown (e.g. SPA route change before
1740
- * `apiReadyCallback` fires). Idempotent.
1741
- *
1742
- * @example
1743
- * import { integrateMetabox } from '@3dsource/metabox-modular-configurator-api';
1744
- *
1745
- * integrateMetabox('configurator-id',
1746
- * 'embed3DSource',
1747
- * (api) => {
1748
- * // Communicator is ready to use
1749
- * },
1750
- * {
1751
- * standalone: false,
1752
- * introImage: 'https://example.com/intro.png',
1753
- * loadingImage: 'https://example.com/loading.png',
1754
- * showLoadingProgress: true,
1755
- * showResumeStreamPopup: true,
1756
- * showUserInactivityTimer: true,
1757
- * userInactivityTimeout: 20,
1758
- * },
1759
- * );
1760
- */
446
+ const BASE_PERMISSIONS = "autoplay; fullscreen; encrypted-media";
447
+ const iframePermissions = () => "modelContext" in document || "modelContext" in navigator ? `${BASE_PERMISSIONS}; tools` : BASE_PERMISSIONS;
1761
448
  function integrateMetabox(configuratorId, containerId, apiReadyCallback, config) {
1762
- if (!configuratorId.trim()) {
1763
- throw new Error('integrateMetabox: configuratorId must be a non-empty string');
1764
- }
1765
- const iframeSrc = prepareIframeSrc(configuratorId, config);
1766
- let parsedUrl;
1767
- try {
1768
- parsedUrl = new URL(iframeSrc);
1769
- }
1770
- catch {
1771
- throw new Error('integrateMetabox: Provided iframeSrc is not a valid URL');
1772
- }
1773
- if (parsedUrl.protocol !== 'https:') {
1774
- throw new Error('integrateMetabox: iframeSrc must use HTTPS protocol');
1775
- }
1776
- if (!containerId.trim()) {
1777
- throw new Error('integrateMetabox: containerId must be a non-empty string');
1778
- }
1779
- const container = document.getElementById(containerId);
1780
- if (!container) {
1781
- throw new Error(`Container element with id ${containerId} not found`);
1782
- }
1783
- const existingIframe = document.getElementById('embeddedContent');
1784
- if (existingIframe) {
1785
- existingIframe.remove();
1786
- }
1787
- // Built before the handshake listener goes up so the Communicator can be told
1788
- // which frame is ours and which origin to address it by. The element is still
1789
- // detached here — `contentWindow` only exists once it is in the document, and
1790
- // by then the handshake it is compared against has not happened yet.
1791
- const iframe = document.createElement('iframe');
1792
- // Supersede a prior integration still waiting for its handshake.
1793
- cancelPendingHandshake?.();
1794
- const cancel = Communicator.createInstance(apiReadyCallback, 'host', config, {
1795
- iframe,
1796
- origin: parsedUrl.origin,
1797
- });
1798
- cancelPendingHandshake = cancel ?? null;
1799
- // Inject the container rules once per containerId — repeated integrations
1800
- // were appending identical <style> tags, forcing CSSOM reparses.
1801
- const styleId = `metabox-integration-style-${containerId}`;
1802
- if (!document.getElementById(styleId)) {
1803
- const style = document.createElement('style');
1804
- style.id = styleId;
1805
- style.innerHTML = `
449
+ if (!configuratorId.trim()) throw new Error("integrateMetabox: configuratorId must be a non-empty string");
450
+ const iframeSrc = prepareIframeSrc(configuratorId, config);
451
+ let parsedUrl;
452
+ try {
453
+ parsedUrl = new URL(iframeSrc);
454
+ } catch {
455
+ throw new Error("integrateMetabox: Provided iframeSrc is not a valid URL");
456
+ }
457
+ if (parsedUrl.protocol !== "https:") throw new Error("integrateMetabox: iframeSrc must use HTTPS protocol");
458
+ if (!containerId.trim()) throw new Error("integrateMetabox: containerId must be a non-empty string");
459
+ const container = document.getElementById(containerId);
460
+ if (!container) throw new Error(`Container element with id ${containerId} not found`);
461
+ const existingIframe = document.getElementById("embeddedContent");
462
+ if (existingIframe) existingIframe.remove();
463
+ const iframe = document.createElement("iframe");
464
+ cancelPendingHandshake?.();
465
+ const cancel = Communicator.createInstance(apiReadyCallback, "host", config, {
466
+ iframe,
467
+ origin: parsedUrl.origin
468
+ });
469
+ cancelPendingHandshake = cancel ?? null;
470
+ const styleId = `metabox-integration-style-${containerId}`;
471
+ if (!document.getElementById(styleId)) {
472
+ const style = document.createElement("style");
473
+ style.id = styleId;
474
+ style.innerHTML = `
1806
475
  #${containerId} {
1807
476
  width: 100%;
1808
477
  height: 100%;
@@ -1810,75 +479,34 @@ function integrateMetabox(configuratorId, containerId, apiReadyCallback, config)
1810
479
  position: relative;
1811
480
  }
1812
481
  `;
1813
- document.head.appendChild(style);
1814
- }
1815
- iframe.setAttribute('allow', 'autoplay; fullscreen; encrypted-media');
1816
- iframe.setAttribute('referrerPolicy', 'no-referrer-when-downgrade');
1817
- iframe.setAttribute('id', 'embeddedContent');
1818
- iframe.style.border = '0';
1819
- iframe.style.width = '100%';
1820
- iframe.style.height = '100%';
1821
- iframe.style.overflow = 'hidden';
1822
- iframe.src = iframeSrc;
1823
- container.appendChild(iframe);
1824
- return cancel;
482
+ document.head.appendChild(style);
483
+ }
484
+ iframe.setAttribute("allow", iframePermissions());
485
+ iframe.setAttribute("referrerPolicy", "no-referrer-when-downgrade");
486
+ iframe.setAttribute("id", "embeddedContent");
487
+ iframe.style.border = "0";
488
+ iframe.style.width = "100%";
489
+ iframe.style.height = "100%";
490
+ iframe.style.overflow = "hidden";
491
+ iframe.src = iframeSrc;
492
+ container.appendChild(iframe);
493
+ return cancel;
1825
494
  }
1826
-
1827
- /**
1828
- * Saves an image by triggering a download.
1829
- *
1830
- * This function creates an anchor element, sets its `href` attribute to the provided image URL,
1831
- * and triggers a click event to initiate a download with the specified filename.
1832
- *
1833
- * ### What does it unlock?
1834
- * Main exported function to save images from the configurator. Converts base64 image data to actual image
1835
- * files and saves them to the local filesystem.
1836
- *
1837
- * ### Practical Application
1838
- * Exported utility function that converts base64 screenshot data (from screenshotReady event) to a downloadable
1839
- * image file. Handles the base64 → blob → browser download flow. Import directly from the API package.
1840
- *
1841
- * ### AI Coding Best Practices
1842
- * Pattern: `api.addEventListener('screenshotReady', (data) => { if(data) saveImage(data, 'config-screenshot.png'); })`.
1843
- * Filename extension should match the MimeType passed to GetScreenshot.
1844
- * Import: `import { saveImage } from '@3dsource/metabox-modular-configurator-api'`.
1845
- *
1846
- * Only the three data-URL formats the configurator actually produces are
1847
- * accepted (`image/png`, `image/jpeg`, `image/webp`). The documented usage above
1848
- * feeds this an event payload straight off the wire, and the body below sets
1849
- * `href` on an anchor and clicks it — so without the check any `data:` URL that
1850
- * reached a `screenshotReady` listener would land in the user's downloads.
1851
- * Anything else is reported and ignored.
1852
- *
1853
- * @param {string} imageUrl - The URL of the image to save.
1854
- * @param {string} filename - The name of the file to save.
1855
- */
1856
495
  function saveImage(imageUrl, filename) {
1857
- if (!isScreenshotDataUrl(imageUrl)) {
1858
- console.warn('Metabox: saveImage ignored a value that is not a configurator screenshot ' +
1859
- '(expected a base64 data URL of type image/png, image/jpeg or image/webp).');
1860
- return;
1861
- }
1862
- const a = document.createElement('a');
1863
- a.href = imageUrl;
1864
- a.download = filename;
1865
- document.body.appendChild(a);
1866
- a.click();
1867
- document.body.removeChild(a);
496
+ if (!isScreenshotDataUrl(imageUrl)) {
497
+ console.warn("Metabox: saveImage ignored a value that is not a configurator screenshot (expected a base64 data URL of type image/png, image/jpeg or image/webp).");
498
+ return;
499
+ }
500
+ const a = document.createElement("a");
501
+ a.href = imageUrl;
502
+ a.download = filename;
503
+ document.body.appendChild(a);
504
+ a.click();
505
+ document.body.removeChild(a);
1868
506
  }
1869
- /**
1870
- * A base64 data URL in one of the formats `GetScreenshot` can ask for. Matched
1871
- * as a whole string rather than parsed: `new URL()` accepts a `data:` URL but
1872
- * exposes nothing useful about its media type, and a prefix check would let
1873
- * anything trail behind the payload.
1874
- */
1875
507
  function isScreenshotDataUrl(value) {
1876
- return /^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/i.test(value);
508
+ return /^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/i.test(value);
1877
509
  }
1878
-
1879
- /**
1880
- * Generated bundle index. Do not edit.
1881
- */
1882
-
1883
510
  export { AppLoaded, AppLoaded_V3, ApplyZoom, BasicRouteUrl, CommandBase, Communicator, EventDispatcher, GetCallToActionInformation, GetCamera, GetPdf, GetScreenshot, HideMeasurement, InitShowcase, Metabox, MetaboxConfig, MetaboxDomain, MetaboxHost, MetaboxHost_V3, MetaboxModularConfiguratorActions, Metabox_V3, PauseShowcase, PlayShowcase, ResetCamera, ResetConfiguration, ResetUserInactivityTimer, ResumeStream, SetCamera, SetComponent, SetComponentMaterial, SetEnvironment, SetEnvironmentMaterial, SetMaterials, ShowEmbeddedMenu, ShowMeasurement, ShowOverlayInterface, StopShowcase, StopStream, UnrealCommand, VERSION, fromCommunicatorEvent, integrateMetabox, prepareIframeSrc, saveImage };
1884
- //# sourceMappingURL=3dsource-metabox-modular-configurator-api.mjs.map
511
+
512
+ //# sourceMappingURL=3dsource-metabox-modular-configurator-api.mjs.map