@3dsource/metabox-front-api 3.0.33 → 3.0.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,40 @@
1
+ # Changelog — @3dsource/metabox-front-api
2
+
3
+ Write free-form context in the **Unreleased** section before releasing. `release:package`
4
+ closes it into the version it publishes, and the package ships this file; the release note
5
+ in ClickUp opens with the text of every version that went live, followed by a structural
6
+ diff of the public `.d.ts`. Leaving it empty is fine: the diff still makes a complete note.
7
+ See `PUBLISH.md`.
8
+
9
+ ## Unreleased
10
+
11
+ ## 3.0.35 — 23 November 2026
12
+
13
+ `config.domain` written with a scheme now works: `https://staging.example.com` is used as is, where it used to become the host `https` and load nothing. An `http://` domain is rejected with the HTTPS error. The configurator id is URL-encoded, a `state` that is not URI-encoded no longer throws, and container ids such as React's `:r1:` get their size styles.
14
+
15
+ A listener or `apiReadyCallback` that throws no longer breaks the API: the other listeners still run and the handshake is not repeated. The error is still reported to `window.onerror`.
16
+
17
+ `Communicator.instance` is deprecated: it was never set. The examples in the type declarations use `integrateMetabox()` instead of the old `window.env3DSource.apiReady`, and the README now covers `pdfStatusChanged`, `ctaStatusChanged`, the cancel function returned by `integrateMetabox()` and cleanup. `llms.txt` links the Markdown API reference.
18
+
19
+ ## 3.0.34 — 10 November 2026
20
+
21
+ Every command now carries `userActivated`: true when it is sent within a few seconds of a real click or key press on the host page. Metabox records configurator analytics for embed API commands only when it is true, so commands a site sends on load (for example from `setupInitialState()`) are no longer counted as a shopper's choice. Nothing changes for the host code.
22
+
23
+ ## 3.0.33 — 7 October 2026
24
+
25
+ `integrateMetabox` adds the `tools` permission to the iframe in browsers that support WebMCP, so an in-browser AI agent on the host page can reach the configurator's agent tools. Other browsers keep the previous `allow` list.
26
+
27
+ New `configuratorNotFound` event: Metabox deployments with the updated contract send it when the configurator id does not exist, so a host that shows its own loading UI can stop waiting. Commands and methods are unchanged; older deployments do not send it.
28
+
29
+ The package now ships `llms.txt`, a short index for AI coding agents that points at the README sections and the type declarations (also served by jsDelivr next to the package).
30
+
31
+ ## 3.0.32 — 31 August 2026
32
+
33
+ ### Added
34
+
35
+ - `CtaStatus` (type) — Lifecycle of the workflow.
36
+ - `FromMetaboxMessagePayloads.ctaStatusChanged` — Dispatches as a GetCallToActionInformation() workflow starts, completes or fails. MetaBox handles the redirect itself; this only reports progress.
37
+ - `FromMetaboxMessagePayloads.pdfStatusChanged` — Dispatches as a GetPdf() render starts, finishes or fails. The document is delivered by the browser download either way; this only reports progress.
38
+ - `PdfStatus` (type) — Lifecycle of a render.
39
+
40
+ ---
package/README.md CHANGED
@@ -90,7 +90,7 @@ npm install @3dsource/metabox-front-api@latest --save
90
90
  **Import:**
91
91
 
92
92
  ```typescript
93
- import { integrateMetabox, Communicator, ConfiguratorEnvelope, SetProduct, SetProductMaterial, SetEnvironment, GetScreenshot, GetPdf, saveImage } from '@3dsource/metabox-front-api';
93
+ import { integrateMetabox, Communicator, type ConfiguratorEnvelope, SetProduct, SetProductMaterial, SetEnvironment, GetScreenshot, GetPdf, saveImage } from '@3dsource/metabox-front-api';
94
94
  ```
95
95
 
96
96
  ### CDN Installation (Quick Prototyping)
@@ -160,7 +160,7 @@ Ensure your HTML page has the following structure, where the Metabox Configurato
160
160
  #### TypeScript/Angular/React
161
161
 
162
162
  ```typescript
163
- import { integrateMetabox, Communicator, ConfiguratorEnvelope, SetProduct, SetProductMaterial, SetEnvironment, GetScreenshot, ShowEmbeddedMenu, ShowOverlayInterface, saveImage, type MimeType } from '@3dsource/metabox-front-api';
163
+ import { integrateMetabox, Communicator, type ConfiguratorEnvelope, SetProduct, SetProductMaterial, SetEnvironment, GetScreenshot, ShowEmbeddedMenu, ShowOverlayInterface, saveImage, type MimeType } from '@3dsource/metabox-front-api';
164
164
 
165
165
  class MetaboxIntegrator {
166
166
  private api: Communicator | null = null;
@@ -315,9 +315,11 @@ Embeds the Metabox configurator iframe and establishes communication channel.
315
315
  **Signature:**
316
316
 
317
317
  ```typescript
318
- function integrateMetabox(configuratorId: string, containerId: string, apiReadyCallback: (api: Communicator) => void, config?: IntegrateMetaboxConfig): void;
318
+ function integrateMetabox(configuratorId: string, containerId: string, apiReadyCallback: (api: Communicator) => void, config?: IntegrateMetaboxConfig): () => void;
319
319
  ```
320
320
 
321
+ **Returns:** a function that stops waiting for the configurator to load. Calling it is optional — a later `integrateMetabox()` call cancels a pending one on its own — but call it on teardown (component destroy, route change) so the handshake listener does not outlive the page. See [Cleanup](#cleanup).
322
+
321
323
  **Parameters:**
322
324
 
323
325
  | Parameter | Type | Required | Default | Description |
@@ -325,7 +327,7 @@ function integrateMetabox(configuratorId: string, containerId: string, apiReadyC
325
327
  | `configuratorId` | `string` | ✅ | - | Configurator UUID (not full URL) |
326
328
  | `containerId` | `string` | ✅ | - | DOM container element ID |
327
329
  | `apiReadyCallback` | `function` | ✅ | - | Callback invoked when API is ready |
328
- | `config` | `IntegrateMetaboxConfig` | ❌ | `{}` | Additional configuration options |
330
+ | `config` | `IntegrateMetaboxConfig` | ❌ | - | Additional configuration options |
329
331
 
330
332
  **Config Options (`IntegrateMetaboxConfig`):**
331
333
 
@@ -543,11 +545,11 @@ api.sendCommandToMetabox(new ResetUserInactivityTimer());
543
545
 
544
546
  #### Export & Media
545
547
 
546
- | Command | Parameters | Description | Event Triggered |
547
- | ---------------------------- | --------------------------------------------------- | -------------------- | ---------------------- |
548
- | `GetScreenshot` | `mimeType: MimeType, size?: {x: number, y: number}` | Render screenshot | `screenshotReady` |
549
- | `GetPdf` | None | Generate PDF export | Server-side (no event) |
550
- | `GetCallToActionInformation` | None | Trigger CTA workflow | Backend redirect |
548
+ | Command | Parameters | Description | Event Triggered |
549
+ | ---------------------------- | --------------------------------------------------- | -------------------- | ------------------ |
550
+ | `GetScreenshot` | `mimeType: MimeType, size?: {x: number, y: number}` | Render screenshot | `screenshotReady` |
551
+ | `GetPdf` | None | Generate PDF export | `pdfStatusChanged` |
552
+ | `GetCallToActionInformation` | None | Trigger CTA workflow | `ctaStatusChanged` |
551
553
 
552
554
  **Screenshot Example:**
553
555
 
@@ -555,7 +557,9 @@ api.sendCommandToMetabox(new ResetUserInactivityTimer());
555
557
  api.sendCommandToMetabox(new GetScreenshot('image/png', { x: 1920, y: 1080 }));
556
558
 
557
559
  api.addEventListener('screenshotReady', (imageData) => {
558
- saveImage(imageData, 'product.png');
560
+ if (imageData) {
561
+ saveImage(imageData, 'product.png');
562
+ }
559
563
  });
560
564
  ```
561
565
 
@@ -579,6 +583,8 @@ Event-driven architecture for reactive state management. Register listeners via
579
583
  | `loadingStatusChanged` | `{ percents: number; loaderVisible: boolean }` | Loading progress or overlay changed | Show custom loading progress bar |
580
584
  | `userInactivityDetected` | `{ remainingSecondsToDisconnect: number; countdownVisible: boolean }` | AFK countdown started or updated | Show "Stay connected?" prompt |
581
585
  | `configuratorNotFound` | `true` | The configurator id does not exist | Show an error instead of waiting |
586
+ | `pdfStatusChanged` | `PdfStatus` (`'started' \| 'ready' \| 'failed'`) | GetPdf render progress | Disable export button, show failure |
587
+ | `ctaStatusChanged` | `CtaStatus` (`'started' \| 'ready' \| 'failed'`) | CTA workflow progress | Disable CTA button, show failure |
582
588
 
583
589
  #### Event Examples
584
590
 
@@ -657,21 +663,43 @@ api.addEventListener('loadingStatusChanged', ({ percents, loaderVisible }) => {
657
663
  **AFK Inactivity Countdown:**
658
664
 
659
665
  ```typescript
660
- import { ResetUserInactivityTimer } from '@3dsource/metabox-front-api';
666
+ import { integrateMetabox, ResetUserInactivityTimer } from '@3dsource/metabox-front-api';
667
+
668
+ integrateMetabox('configurator-id', 'embed3DSource', (api) => {
669
+ api.addEventListener('userInactivityDetected', ({ remainingSecondsToDisconnect, countdownVisible }) => {
670
+ const dialog = document.getElementById('afk-dialog');
671
+ const countdown = document.getElementById('afk-countdown');
661
672
 
662
- api.addEventListener('userInactivityDetected', ({ remainingSecondsToDisconnect, countdownVisible }) => {
663
- const dialog = document.getElementById('afk-dialog');
664
- const countdown = document.getElementById('afk-countdown');
673
+ if (dialog) dialog.style.display = countdownVisible ? 'flex' : 'none';
674
+ if (countdown) countdown.textContent = String(remainingSecondsToDisconnect);
675
+ });
665
676
 
666
- if (dialog) dialog.style.display = countdownVisible ? 'flex' : 'none';
667
- if (countdown) countdown.textContent = String(remainingSecondsToDisconnect);
677
+ document.getElementById('stay-connected-btn')?.addEventListener('click', () => {
678
+ api.sendCommandToMetabox(new ResetUserInactivityTimer());
679
+ });
668
680
  });
681
+ ```
682
+
683
+ #### Cleanup
684
+
685
+ There is no single `destroy()` for application code. On teardown:
669
686
 
670
- document.getElementById('stay-connected-btn')?.addEventListener('click', () => {
671
- api.sendCommandToMetabox(new ResetUserInactivityTimer());
687
+ ```typescript
688
+ const cancel = integrateMetabox(configuratorId, containerId, (api) => {
689
+ api.addEventListener('configuratorDataUpdated', onData);
690
+ apiRef = api;
672
691
  });
692
+
693
+ // later, on component destroy / route change
694
+ cancel(); // stops waiting if the configurator has not loaded yet
695
+ apiRef?.removeEventListener('configuratorDataUpdated', onData); // same function reference
673
696
  ```
674
697
 
698
+ - `removeEventListener(event, handler)` needs the same function reference you passed to `addEventListener`.
699
+ - With `fromCommunicatorEvent`, unsubscribe the RxJS subscription (`takeUntil`, `takeUntilDestroyed`).
700
+ - `Communicator.clearAll()` removes every listener of every instance on the page — use it only when the page owns the only configurator.
701
+ - Calling `integrateMetabox()` again replaces the iframe (`#embeddedContent`). Keep the `api` from the latest call; an old handle warns in the console.
702
+
675
703
  ### Utility Functions
676
704
 
677
705
  #### `saveImage(imageUrl: string, filename: string): void`
@@ -704,23 +732,23 @@ Creates a temporary anchor element with `download` attribute to trigger browser
704
732
  warning instead of being downloaded, since this function is fed event payloads
705
733
  straight off the postMessage channel.
706
734
 
707
- #### `fromCommunicatorEvent(target: Communicator, eventName: string): Observable`
735
+ #### `fromCommunicatorEvent(target: Communicator, eventName: FromMetaBoxApiEvents): Observable<FromMetaboxMessagePayloads[eventName]>`
708
736
 
709
737
  RxJS wrapper for Communicator events. Works like RxJS `fromEvent` — creates a typed Observable that emits each time the specified event fires. Alternative to `api.addEventListener()`.
710
738
 
711
739
  **Parameters:**
712
740
 
713
- | Parameter | Type | Description |
714
- | ----------- | -------------- | -------------------------------------------- |
715
- | `target` | `Communicator` | The Communicator instance to listen on |
716
- | `eventName` | `string` | Event name (e.g., `configuratorDataUpdated`) |
741
+ | Parameter | Type | Description |
742
+ | ----------- | ---------------------- | ---------------------------------------------------------------------- |
743
+ | `target` | `Communicator` | The Communicator instance to listen on |
744
+ | `eventName` | `FromMetaBoxApiEvents` | One of the event names listed in [Available Events](#available-events) |
717
745
 
718
746
  **Returns:** `Observable<T>` — typed Observable matching the event payload.
719
747
 
720
748
  **Example:**
721
749
 
722
750
  ```typescript
723
- import { fromCommunicatorEvent } from '@3dsource/metabox-front-api';
751
+ import { fromCommunicatorEvent, integrateMetabox, saveImage } from '@3dsource/metabox-front-api';
724
752
 
725
753
  integrateMetabox('configurator-id', 'embed3DSource', (api) => {
726
754
  fromCommunicatorEvent(api, 'configuratorDataUpdated').subscribe((data) => {
@@ -964,6 +992,7 @@ A complete HTML example showing how to integrate the Metabox configurator with v
964
992
 
965
993
  // Listen for screenshot completion
966
994
  api.addEventListener('screenshotReady', (imageData) => {
995
+ if (!imageData) return;
967
996
  console.log('Screenshot captured successfully');
968
997
  // Save the image with a timestamp
969
998
  saveImage(imageData, `configurator-screenshot-${Date.now()}.png`);
@@ -1033,7 +1062,7 @@ A complete HTML example showing how to integrate the Metabox configurator with v
1033
1062
 
1034
1063
  ```tsx
1035
1064
  import React, { useEffect, useRef, useState, useCallback } from 'react';
1036
- import { integrateMetabox, Communicator, ConfiguratorEnvelope, SetProduct, SetProductMaterial, GetScreenshot, saveImage } from '@3dsource/metabox-front-api';
1065
+ import { integrateMetabox, Communicator, type ConfiguratorEnvelope, SetProduct, SetProductMaterial, GetScreenshot, saveImage } from '@3dsource/metabox-front-api';
1037
1066
 
1038
1067
  interface MetaboxConfiguratorProps {
1039
1068
  configuratorId: string;
@@ -1070,20 +1099,28 @@ const MetaboxConfigurator: React.FC<MetaboxConfiguratorProps> = ({ configuratorI
1070
1099
  [onError],
1071
1100
  );
1072
1101
 
1073
- // Initialize configurator
1102
+ // Keep the latest callbacks without re-running the integration effect:
1103
+ // inline props would otherwise re-embed the configurator on every render.
1104
+ const callbacks = useRef({ onStateChange, handleError });
1105
+ useEffect(() => {
1106
+ callbacks.current = { onStateChange, handleError };
1107
+ });
1108
+
1109
+ // Initialize configurator once per configuratorId
1074
1110
  useEffect(() => {
1075
1111
  if (!containerRef.current) return;
1076
1112
 
1077
1113
  let mounted = true;
1114
+ let cancel: (() => void) | undefined;
1078
1115
 
1079
- const initializeConfigurator = async () => {
1116
+ const initializeConfigurator = () => {
1080
1117
  try {
1081
1118
  setState((prev) => ({ ...prev, isLoading: true, error: null }));
1082
1119
 
1083
1120
  // Set the container ID
1084
1121
  containerRef.current!.id = containerId.current;
1085
1122
 
1086
- integrateMetabox(configuratorId, containerId.current, (apiInstance) => {
1123
+ cancel = integrateMetabox(configuratorId, containerId.current, (apiInstance) => {
1087
1124
  if (!mounted) return; // Component was unmounted
1088
1125
 
1089
1126
  try {
@@ -1093,12 +1130,12 @@ const MetaboxConfigurator: React.FC<MetaboxConfiguratorProps> = ({ configuratorI
1093
1130
  // Set up event listeners with proper typing
1094
1131
  apiInstance.addEventListener('configuratorDataUpdated', (data: ConfiguratorEnvelope) => {
1095
1132
  if (mounted) {
1096
- onStateChange?.(data);
1133
+ callbacks.current.onStateChange?.(data);
1097
1134
  }
1098
1135
  });
1099
1136
 
1100
- apiInstance.addEventListener('screenshotReady', (imageData: string) => {
1101
- if (mounted) {
1137
+ apiInstance.addEventListener('screenshotReady', (imageData: string | null) => {
1138
+ if (mounted && imageData) {
1102
1139
  console.log('Screenshot captured successfully');
1103
1140
  saveImage(imageData, `configurator-screenshot-${Date.now()}.png`);
1104
1141
  }
@@ -1107,28 +1144,26 @@ const MetaboxConfigurator: React.FC<MetaboxConfiguratorProps> = ({ configuratorI
1107
1144
  console.log('React Metabox Configurator initialized successfully');
1108
1145
  } catch (error) {
1109
1146
  if (mounted) {
1110
- handleError(`Failed to set up API: ${error instanceof Error ? error.message : String(error)}`);
1147
+ callbacks.current.handleError(`Failed to set up API: ${error instanceof Error ? error.message : String(error)}`);
1111
1148
  }
1112
1149
  }
1113
1150
  });
1114
1151
  } catch (error) {
1115
1152
  if (mounted) {
1116
- handleError(`Failed to initialize configurator: ${error instanceof Error ? error.message : String(error)}`);
1153
+ callbacks.current.handleError(`Failed to initialize configurator: ${error instanceof Error ? error.message : String(error)}`);
1117
1154
  }
1118
1155
  }
1119
1156
  };
1120
1157
 
1121
1158
  initializeConfigurator();
1122
1159
 
1123
- // Cleanup function
1160
+ // Cleanup: stop waiting for a handshake that has not happened yet.
1161
+ // Listeners registered above check `mounted`, so they go quiet after unmount.
1124
1162
  return () => {
1125
1163
  mounted = false;
1126
- if (api) {
1127
- // Clean up any event listeners if the API provides cleanup methods
1128
- console.log('Cleaning up Metabox Configurator');
1129
- }
1164
+ cancel?.();
1130
1165
  };
1131
- }, [configuratorId, onStateChange, handleError, api]);
1166
+ }, [configuratorId]);
1132
1167
 
1133
1168
  // Command methods with error handling
1134
1169
  const changeProduct = useCallback(
@@ -1336,8 +1371,8 @@ export default MetaboxConfigurator;
1336
1371
 
1337
1372
  ```typescript
1338
1373
  // metabox-configurator.component.ts
1339
- import { Component, input, OnInit, output, signal } from '@angular/core';
1340
- import { Communicator, ConfiguratorEnvelope, GetCallToActionInformation, GetPdf, GetScreenshot, InitShowcase, integrateMetabox, PauseShowcase, PlayShowcase, saveImage, SetProductMaterial, SetProduct, ShowEmbeddedMenu, ShowOverlayInterface, StopShowcase } from '@3dsource/metabox-front-api';
1374
+ import { afterNextRender, Component, DestroyRef, inject, input, output, signal } from '@angular/core';
1375
+ import { Communicator, type ConfiguratorEnvelope, GetCallToActionInformation, GetPdf, GetScreenshot, InitShowcase, integrateMetabox, PauseShowcase, PlayShowcase, saveImage, SetProductMaterial, SetProduct, ShowEmbeddedMenu, ShowOverlayInterface, StopShowcase } from '@3dsource/metabox-front-api';
1341
1376
 
1342
1377
  interface ConfiguratorState {
1343
1378
  isLoading: boolean;
@@ -1533,7 +1568,7 @@ interface ConfiguratorState {
1533
1568
  `,
1534
1569
  ],
1535
1570
  })
1536
- export class MetaboxConfiguratorComponent implements OnInit {
1571
+ export class MetaboxConfiguratorComponent {
1537
1572
  configuratorId = input.required<string>();
1538
1573
  stateChange = output<ConfiguratorEnvelope>();
1539
1574
  errorFired = output<string>();
@@ -1544,9 +1579,12 @@ export class MetaboxConfiguratorComponent implements OnInit {
1544
1579
  });
1545
1580
  containerId = signal(`metabox-container-${Math.random().toString(36).substring(2, 9)}`);
1546
1581
  private api: Communicator | null = null;
1582
+ private cancelIntegration?: () => void;
1547
1583
 
1548
- ngOnInit(): void {
1549
- this.initializeConfigurator();
1584
+ constructor() {
1585
+ // The container is in this component's own template, so it exists only after the first render.
1586
+ afterNextRender(() => this.initializeConfigurator());
1587
+ inject(DestroyRef).onDestroy(() => this.cancelIntegration?.());
1550
1588
  }
1551
1589
 
1552
1590
  // Public methods for external control
@@ -1692,7 +1730,7 @@ export class MetaboxConfiguratorComponent implements OnInit {
1692
1730
  try {
1693
1731
  this.updateState({ isLoading: true, error: null });
1694
1732
 
1695
- integrateMetabox(this.configuratorId(), this.containerId(), (apiInstance) => {
1733
+ this.cancelIntegration = integrateMetabox(this.configuratorId(), this.containerId(), (apiInstance) => {
1696
1734
  try {
1697
1735
  this.api = apiInstance;
1698
1736
  this.updateState({ isLoading: false, isApiReady: true });
@@ -1759,7 +1797,7 @@ export class MetaboxConfiguratorComponent implements OnInit {
1759
1797
  ```typescript
1760
1798
  // app.component.ts
1761
1799
  import { Component } from '@angular/core';
1762
- import { ConfiguratorEnvelope } from '@3dsource/metabox-front-api';
1800
+ import { type ConfiguratorEnvelope } from '@3dsource/metabox-front-api';
1763
1801
 
1764
1802
  @Component({
1765
1803
  selector: 'app-root',
@@ -1797,7 +1835,7 @@ export class AppComponent {
1797
1835
  **To Use This Component:**
1798
1836
 
1799
1837
  1. Install the package: `npm install @3dsource/metabox-front-api@latest`
1800
- 2. Import the component in your Angular module
1838
+ 2. Add the standalone component to the `imports` of the component that uses it
1801
1839
  3. Replace `'configurator-id'` with your actual configurator ID
1802
1840
  4. Replace placeholder IDs with your real product, material, and slot IDs
1803
1841
  5. Customize the styling by modifying the component styles
@@ -1812,13 +1850,13 @@ export class AppComponent {
1812
1850
 
1813
1851
  **Root Causes & Solutions:**
1814
1852
 
1815
- | Issue | Diagnostic | Solution |
1816
- | --------------------------- | ------------------------------------ | --------------------------------------------------------- |
1817
- | Invalid configurator ID | Browser console shows 404 errors | Verify configurator ID in Metabox admin |
1818
- | Container not found | `Error: Container element not found` | Ensure element exists before calling `integrateMetabox()` |
1819
- | HTTP instead of HTTPS | Mixed content warnings | Use HTTPS or test on localhost |
1820
- | Container has no dimensions | Invisible iframe (0x0) | Set explicit width/height on container element |
1821
- | CORS/iframe blocking | X-Frame-Options errors | Check domain allowlist in Metabox settings |
1853
+ | Issue | Diagnostic | Solution |
1854
+ | --------------------------- | ------------------------------------------------- | --------------------------------------------------------- |
1855
+ | Invalid configurator ID | Browser console shows 404 errors | Verify configurator ID in Metabox admin |
1856
+ | Container not found | `Error: Container element with id <id> not found` | Ensure element exists before calling `integrateMetabox()` |
1857
+ | HTTP instead of HTTPS | Mixed content warnings | Use HTTPS or test on localhost |
1858
+ | Container has no dimensions | Invisible iframe (0x0) | Set explicit width/height on container element |
1859
+ | CORS/iframe blocking | X-Frame-Options errors | Check domain allowlist in Metabox settings |
1822
1860
 
1823
1861
  **Diagnostic Code:**
1824
1862
 
@@ -1884,7 +1922,7 @@ If you're still experiencing issues:
1884
1922
  - **Debounce rapid commands.** Avoid sending too many commands in quick succession — debounce material or product changes (e.g., 300 ms).
1885
1923
  - **Responsive container.** Set the configurator container to responsive dimensions (`width: 100%; height: 100%;`) and adjust with media queries for mobile.
1886
1924
  - **Events work in all modes.** `configuratorDataUpdated`, `screenshotReady`, and other events fire in both default and standalone mode — use them to keep your UI synchronized.
1887
- - **Wait for API ready.** Only send commands inside the `apiReadyCallback`. Commands sent before initialization are silently ignored.
1925
+ - **Wait for API ready.** Only send commands inside the `apiReadyCallback` — the `api` handle does not exist before it fires.
1888
1926
  - **Validate IDs from events.** Use the `configuratorDataUpdated` event payload to discover valid product, material, and slot IDs rather than hardcoding them.
1889
1927
  - **HTTPS is required.** The iframe URL enforces HTTPS. HTTP URLs will be rejected. Use `localhost` for local development.
1890
1928
  - **Pin CDN versions in production.** Replace `@latest` with a specific version to avoid unexpected breaking changes.
@@ -241,6 +241,10 @@ var ResetUserInactivityTimer = class extends CommandBase {
241
241
  this.data = { action: MetaboxBasicConfiguratorActions.resetUserInactivityTimer };
242
242
  }
243
243
  };
244
+ function reportListenerError(error) {
245
+ if (typeof globalThis.reportError === "function") globalThis.reportError(error);
246
+ else console.error(error);
247
+ }
244
248
  var EventDispatcher = class {
245
249
  constructor() {
246
250
  this.listeners = [];
@@ -260,7 +264,11 @@ var EventDispatcher = class {
260
264
  const len = listeners.length;
261
265
  for (let i = 0; i < len; i++) {
262
266
  const listener = listeners[i];
263
- if (listener.messageType === messageType) listener.callback(data);
267
+ if (listener.messageType === messageType) try {
268
+ listener.callback(data);
269
+ } catch (error) {
270
+ reportListenerError(error);
271
+ }
264
272
  }
265
273
  return this;
266
274
  }
@@ -272,12 +280,12 @@ var EventDispatcher = class {
272
280
  const Metabox = "metabox";
273
281
  const MetaboxHost = "metaboxHost";
274
282
  const AppLoaded = "appLoaded";
283
+ const MetaboxDomain = "metabox.3dsource.com";
275
284
  const Metabox_V3 = "metabox_v3";
276
285
  const MetaboxHost_V3 = "metaboxHost_v3";
277
286
  const AppLoaded_V3 = "appLoaded_v3";
278
- const MetaboxDomain = "metabox.3dsource.com";
279
287
  const BasicRouteUrl = "metabox-configurator/basic";
280
- const VERSION = "3.0.33";
288
+ const VERSION = "3.0.35";
281
289
  const EmbeddedContentId = "embeddedContent";
282
290
  function isTargetableOrigin(origin) {
283
291
  if (!origin || origin === "*" || origin === "null") return false;
@@ -343,11 +351,11 @@ var Communicator = class Communicator extends EventDispatcher {
343
351
  }
344
352
  return;
345
353
  }
354
+ window.removeEventListener("message", startHandler);
346
355
  apiReadyCallback(new Communicator(message.envelope.payload, environment, config, {
347
356
  iframe,
348
357
  origin: Communicator.resolveHandshakeOrigin(event, connection)
349
358
  }));
350
- window.removeEventListener("message", startHandler);
351
359
  };
352
360
  window.addEventListener("message", startHandler);
353
361
  return () => window.removeEventListener("message", startHandler);
@@ -382,7 +390,8 @@ var Communicator = class Communicator extends EventDispatcher {
382
390
  envelope: { ...data },
383
391
  payload: { ...data },
384
392
  target: iframe?.contentWindow ? "child" : "metabox",
385
- apiVersion: VERSION
393
+ apiVersion: VERSION,
394
+ userActivated: navigator.userActivation?.isActive ?? false
386
395
  };
387
396
  if (!iframe?.contentWindow) {
388
397
  console.warn("Metabox IFrame not found or not ready. Message sends to the same window");
@@ -427,12 +436,12 @@ var Communicator = class Communicator extends EventDispatcher {
427
436
  }
428
437
  };
429
438
  const prepareIframeSrc = (configuratorId, config) => {
430
- const base = `https://${config?.domain || "metabox.3dsource.com"}/${BasicRouteUrl}/${configuratorId}`;
439
+ const base = `${toOrigin(config?.domain || "metabox.3dsource.com")}/${BasicRouteUrl}/${encodeURIComponent(configuratorId)}`;
431
440
  const params = new URLSearchParams();
432
441
  if (config?.introImage) params.set("introImage", config.introImage);
433
442
  if (config?.introVideo) params.set("introVideo", config.introVideo);
434
443
  if (config?.loadingImage) params.set("loadingImage", config.loadingImage);
435
- if (config?.state) params.set("state", decodeURIComponent(config.state));
444
+ if (config?.state) params.set("state", decodeOnce(config.state));
436
445
  if (config?.showLoadingProgress !== void 0) params.set("showLoadingProgress", String(config.showLoadingProgress));
437
446
  if (config?.showResumeStreamPopup !== void 0) params.set("showResumeStreamPopup", String(config.showResumeStreamPopup));
438
447
  if (config?.showUserInactivityTimer !== void 0) params.set("showUserInactivityTimer", String(config.showUserInactivityTimer));
@@ -441,6 +450,16 @@ const prepareIframeSrc = (configuratorId, config) => {
441
450
  const query = params.toString();
442
451
  return query ? `${base}?${query}` : base;
443
452
  };
453
+ function toOrigin(domain) {
454
+ return /^[a-z][a-z\d+.-]*:\/\//i.test(domain) ? domain.replace(/\/+$/, "") : `https://${domain}`;
455
+ }
456
+ function decodeOnce(state) {
457
+ try {
458
+ return decodeURIComponent(state);
459
+ } catch {
460
+ return state;
461
+ }
462
+ }
444
463
  let cancelPendingHandshake = null;
445
464
  const BASE_PERMISSIONS = "autoplay; fullscreen; encrypted-media";
446
465
  const iframePermissions = () => "modelContext" in document || "modelContext" in navigator ? `${BASE_PERMISSIONS}; tools` : BASE_PERMISSIONS;
@@ -471,7 +490,7 @@ function integrateMetabox(configuratorId, containerId, apiReadyCallback, config)
471
490
  const style = document.createElement("style");
472
491
  style.id = styleId;
473
492
  style.innerHTML = `
474
- #${containerId} {
493
+ #${CSS.escape(containerId)} {
475
494
  width: 100%;
476
495
  height: 100%;
477
496
  overflow: hidden;