@ada-cx/messaging-sdk 1.3.3 → 1.3.6

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/README.md CHANGED
@@ -56,6 +56,10 @@ try {
56
56
  }
57
57
  ```
58
58
 
59
+ If both imports fail, `cause` holds the default-root typed error and readonly `fallbackCause` holds the fallback typed error.
60
+ Both errors retain their original cause chains.
61
+ An invalid fallback module uses the same error properties and preserves `sdk_module_invalid` and the fallback error message.
62
+
59
63
  ## One widget per page
60
64
 
61
65
  Only one messaging interface can run on a page, and `loadAdaMessaging`
@@ -106,6 +110,15 @@ are exported as types only. Get their implementations from
106
110
  the legacy `window.adaEmbed` contract; new integrations use
107
111
  `loadAdaMessaging`.
108
112
 
113
+ `window.adaSettings`, `new AdaMessagingClient(config)`, `createAdaEmbedInterface(initialSettings)`, and `adaEmbed.start(settings)` accept `crossWindowPersistence` as a boolean or `{ enabled: boolean }`.
114
+ The SDK uses the boolean value of `enabled`, so `{ enabled: false }` disables persistence.
115
+ For invalid values, the SDK logs a console warning once per page load.
116
+
117
+ Invalid overrides preserve the retained host setting or the `window.adaSettings` fallback.
118
+ Invalid constructor values preserve the `window.adaSettings` fallback.
119
+ Without either setting, persistence defaults to on.
120
+ The TypeScript setting remains `boolean`.
121
+
109
122
  ## Testing your integration
110
123
 
111
124
  The `./testing` entry provides an in-memory mock of the messaging interface.
@@ -164,8 +177,43 @@ await loadAdaMessaging(
164
177
  );
165
178
  ```
166
179
 
167
- Use `cdnBase` for staging validation only. Production pages must keep the
168
- default.
180
+ The preferred production root is `https://messaging-assets.ada.support/`.
181
+ For production pages whose CSP already allows `static.ada.support`, use
182
+ `cdnBase: "https://static.ada.support/messaging/"`.
183
+ The package exports this supported production root as `FALLBACK_MESSAGING_CDN_BASE`.
184
+
185
+ Without `cdnBase`, the loader automatically retries once from the static root
186
+ when the default import fails, including CSP and network failures.
187
+ If the default bootstrap rejects after manifest or runtime failures, it evicts its shared `window.__AdaMessagingSdkBootstrap` promise.
188
+ The static bootstrap can then resolve independently.
189
+ If resolution is pending or successful, bootstrap copies share the promise.
190
+ The retry preserves `pinBuildSha` and its `<sha>/sdk/index.js` path.
191
+ Successful unpinned fallback uses the static root for the manifest and frames.
192
+ An explicit `cdnBase` disables automatic fallback.
193
+ Module-invalid and validation errors retain their original codes and messages.
194
+ If both imports fail, `sdk_import_failed` names both attempted URLs.
195
+
196
+ After a successful fallback, the loader logs one warning per page, without debug logging.
197
+ The warning includes the original error as its second console argument.
198
+ A `TypeError` from the default import produces the fetch-failure warning:
199
+
200
+ ```text
201
+ [Ada] Loaded the Messaging SDK from https://static.ada.support/messaging/ because the default root https://messaging-assets.ada.support/ was blocked or unavailable. Add https://messaging-assets.ada.support to script-src, connect-src and frame-src, or pass cdnBase: "https://static.ada.support/messaging/".
202
+ ```
203
+
204
+ For a CSP block, update your host's policy as shown in the fetch-failure warning.
205
+
206
+ Other errors produce the evaluation-failure warning:
207
+
208
+ ```text
209
+ [Ada] Loaded the Messaging SDK from https://static.ada.support/messaging/ because the module at https://messaging-assets.ada.support/sdk.js failed to evaluate (Error: boom). This is an Ada-side problem, not your host's CSP. Report it to Ada.
210
+ ```
211
+
212
+ For an evaluation-failure warning, report the original error to Ada.
213
+ Network failures also produce the fetch-failure warning.
214
+ A module that throws `TypeError` during evaluation also produces the fetch-failure warning, so the classification does not prove a CSP block.
215
+
216
+ Successful loads from the requested root produce no fallback warning.
169
217
 
170
218
  ### Pin the CDN build
171
219
 
@@ -2,7 +2,7 @@ import type { AdaMessagingClientConfig } from "./client-types.js";
2
2
  /**
3
3
  * Reads `window.adaSettings` and maps recognised fields to
4
4
  * `AdaMessagingClientConfig`. All field access is defensive — unknown types
5
- * are silently ignored so that a mal-formed host page cannot crash the SDK.
5
+ * are ignored so that a mal-formed host page cannot crash the SDK.
6
6
  *
7
7
  * Priority rule: the constructor config always wins. This module only
8
8
  * supplies fallback values that the constructor has not explicitly set.
@@ -23,6 +23,7 @@ export declare function deriveLocalhostApiProxyBase(sdkUrl: string, pageHost?: s
23
23
  */
24
24
  export declare const SUPPORTED_THEME_STYLE_KEYS: readonly ["tintColor"];
25
25
  export declare function normalizeIdentityToken(value: unknown): string | undefined;
26
+ export declare function normalizeCrossWindowPersistence(value: unknown): boolean | undefined;
26
27
  /**
27
28
  * Normalize the custom app frame URL (`appUrl`), warning when a
28
29
  * supplied value is dropped. Core re-validates through the same shared helper
@@ -13,7 +13,7 @@ var UNSTAMPED_SHA_PATTERN = /^0{40}$/;
13
13
  * unstamped 40-zero placeholder ({@link isCdnBuildShaStamped} returns
14
14
  * `false`); only published tarballs carry a real SHA.
15
15
  */
16
- var CDN_BUILD_SHA = "7563635673f460d885fa6976033d7b09590d9a49";
16
+ var CDN_BUILD_SHA = "2765b9b100c4d9385cfe67d138e18170b1fadf35";
17
17
  /**
18
18
  * Whether `sha` (default {@link CDN_BUILD_SHA}) is a stamped full git commit
19
19
  * SHA rather than the unstamped repo placeholder.
@@ -83,18 +83,23 @@ function _defineProperty(e, r, t) {
83
83
  * the bootstrap at this root resolves the current rollout at load time.
84
84
  */
85
85
  var DEFAULT_MESSAGING_CDN_BASE = "https://messaging-assets.ada.support/";
86
+ var FALLBACK_MESSAGING_CDN_BASE = "https://static.ada.support/messaging/";
86
87
  var SDK_BOOTSTRAP_FILENAME = "sdk.js";
87
88
  var PINNED_SDK_ENTRY_PATH = "sdk/index.js";
88
89
  var PINNED_BUILD_SHA_PATTERN = /^[0-9a-f]{40}$/;
89
90
  var UNSTAMPED_BUILD_SHA_PATTERN = /^0{40}$/;
90
91
  /** Typed failure raised by {@link loadMessagingSdk} and {@link loadAdaMessaging}. */
91
92
  var MessagingSdkLoadError = class extends Error {
92
- constructor(message, code, cause) {
93
+ constructor(message, code, cause, fallbackCause) {
93
94
  super(message);
94
95
  _defineProperty(this, "code", void 0);
95
96
  this.name = "MessagingSdkLoadError";
96
97
  this.code = code;
97
98
  if (cause !== void 0) this.cause = cause;
99
+ if (fallbackCause !== void 0) Object.defineProperty(this, "fallbackCause", {
100
+ value: fallbackCause,
101
+ enumerable: true
102
+ });
98
103
  }
99
104
  };
100
105
  var defaultImportModule = (url) => import(
@@ -102,7 +107,9 @@ var defaultImportModule = (url) => import(
102
107
  /* @vite-ignore */
103
108
  url
104
109
  );
105
- var inFlightByImporter = /* @__PURE__ */ new WeakMap();
110
+ var loadsByImporter = /* @__PURE__ */ new WeakMap();
111
+ var FALLBACK_WARNING_KEY = Symbol.for("ada.messaging.sdk.fallbackWarning");
112
+ var warningScope = globalThis;
106
113
  var LOOPBACK_HOSTS = new Set([
107
114
  "localhost",
108
115
  "127.0.0.1",
@@ -163,12 +170,24 @@ async function importSdkModule(url, importModule) {
163
170
  if (!isMessagingSdkModule(loaded)) throw new MessagingSdkLoadError(`The module at ${url} does not expose the Ada Messaging SDK interface.`, "sdk_module_invalid");
164
171
  return loaded;
165
172
  }
173
+ function memoizeLoad(cache, url, load) {
174
+ const existing = cache.get(url);
175
+ if (existing) return existing;
176
+ const pending = load();
177
+ cache.set(url, pending);
178
+ pending.catch(() => {
179
+ if (cache.get(url) === pending) cache.delete(url);
180
+ });
181
+ return pending;
182
+ }
166
183
  /**
167
184
  * Load the Ada Messaging SDK module from Ada's CDN.
168
185
  *
169
186
  * The returned promise is memoized per resolved URL: concurrent and repeated
170
187
  * calls share one in-flight import. A failed load clears the memo so a later
171
- * call retries. Rejections are always {@link MessagingSdkLoadError}.
188
+ * call retries. Without `cdnBase`, an import failure at the default root is
189
+ * retried once from {@link FALLBACK_MESSAGING_CDN_BASE}. Rejections are always
190
+ * {@link MessagingSdkLoadError}.
172
191
  *
173
192
  * @example
174
193
  * const { createAdaEmbedInterface } = await loadMessagingSdk();
@@ -176,30 +195,49 @@ async function importSdkModule(url, importModule) {
176
195
  function loadMessagingSdk(options = {}) {
177
196
  const importModule = options.importModule ?? defaultImportModule;
178
197
  let url;
198
+ let fallbackUrl;
179
199
  try {
180
200
  url = resolveSdkBootstrapUrl(options.cdnBase, options.pinBuildSha);
201
+ if (options.cdnBase === void 0) fallbackUrl = resolveSdkBootstrapUrl(FALLBACK_MESSAGING_CDN_BASE, options.pinBuildSha);
181
202
  } catch (error) {
182
203
  return Promise.reject(error);
183
204
  }
184
- let inFlight = inFlightByImporter.get(importModule);
185
- if (!inFlight) {
186
- inFlight = /* @__PURE__ */ new Map();
187
- inFlightByImporter.set(importModule, inFlight);
188
- }
189
- const existing = inFlight.get(url);
190
- if (existing) return existing;
191
- const cache = inFlight;
192
- const pending = importSdkModule(url, importModule);
193
- cache.set(url, pending);
194
- pending.catch(() => {
195
- if (cache.get(url) === pending) cache.delete(url);
196
- });
197
- return pending;
205
+ const state = loadsByImporter.get(importModule) ?? {
206
+ imports: /* @__PURE__ */ new Map(),
207
+ defaultLoads: /* @__PURE__ */ new Map()
208
+ };
209
+ loadsByImporter.set(importModule, state);
210
+ const load = (entryUrl) => memoizeLoad(state.imports, entryUrl, () => importSdkModule(entryUrl, importModule));
211
+ if (fallbackUrl === void 0) return load(url);
212
+ const retryUrl = fallbackUrl;
213
+ return memoizeLoad(state.defaultLoads, url, () => load(url).catch(async (error) => {
214
+ if (!(error instanceof MessagingSdkLoadError) || error.code !== "sdk_import_failed") throw error;
215
+ let module;
216
+ try {
217
+ module = await load(retryUrl);
218
+ } catch (cause) {
219
+ if (!(cause instanceof MessagingSdkLoadError)) throw cause;
220
+ throw new MessagingSdkLoadError(cause.code === "sdk_import_failed" ? `The Ada Messaging SDK failed to load from both ${url} and ${retryUrl}.` : cause.message, cause.code, error, cause);
221
+ }
222
+ if (!warningScope[FALLBACK_WARNING_KEY]) {
223
+ warningScope[FALLBACK_WARNING_KEY] = true;
224
+ const cause = error.cause;
225
+ warnHost(cause instanceof TypeError ? `Loaded the Messaging SDK from ${FALLBACK_MESSAGING_CDN_BASE} because the default root ${DEFAULT_MESSAGING_CDN_BASE} was blocked or unavailable. Add https://messaging-assets.ada.support to script-src, connect-src and frame-src, or pass cdnBase: "${FALLBACK_MESSAGING_CDN_BASE}".` : `Loaded the Messaging SDK from ${FALLBACK_MESSAGING_CDN_BASE} because the module at ${url} failed to evaluate (${describeRejection(cause)}). This is an Ada-side problem, not your host's CSP. Report it to Ada.`, cause);
226
+ }
227
+ return module;
228
+ }));
198
229
  }
199
230
  var startedInterfaceByImporter = /* @__PURE__ */ new WeakMap();
200
- function warnHost(message) {
231
+ function describeRejection(cause) {
232
+ try {
233
+ return cause instanceof Error ? `${cause.name}: ${cause.message}` : String(cause);
234
+ } catch {
235
+ return "unknown error";
236
+ }
237
+ }
238
+ function warnHost(message, cause) {
201
239
  try {
202
- console.warn(`[Ada] ${message}`);
240
+ console.warn(`[Ada] ${message}`, ...cause === void 0 ? [] : [cause]);
203
241
  } catch {}
204
242
  }
205
243
  function isPlainObject(value) {
@@ -276,6 +314,7 @@ function loadAdaMessaging(settings, options = {}) {
276
314
  //#endregion
277
315
  exports.CDN_BUILD_SHA = CDN_BUILD_SHA;
278
316
  exports.DEFAULT_MESSAGING_CDN_BASE = DEFAULT_MESSAGING_CDN_BASE;
317
+ exports.FALLBACK_MESSAGING_CDN_BASE = FALLBACK_MESSAGING_CDN_BASE;
279
318
  exports.MessagingSdkLoadError = MessagingSdkLoadError;
280
319
  exports.isCdnBuildShaStamped = isCdnBuildShaStamped;
281
320
  exports.loadAdaMessaging = loadAdaMessaging;
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":[],"sources":["../../src/npm/build-info.ts","../../src/client/embed-lifecycle.ts","../../src/npm/loader.ts"],"sourcesContent":["// The repo copy carries the 40-zero placeholder; the publish workflow\n// (.github/workflows/messaging-publish-web-packages.yml) stamps the real\n// commit SHA into the built output via scripts/stamp-cdn-build-sha.mjs and\n// verifies the packed tarball before `npm publish`. Keep the placeholder as\n// a single 40-zero string literal: the stamp is a same-length text\n// replacement, so source maps stay valid.\nconst GIT_SHA_PATTERN = /^[0-9a-f]{40}$/;\nconst UNSTAMPED_SHA_PATTERN = /^0{40}$/;\n\n/**\n * Git commit SHA of the monorepo commit this npm version was published from.\n * The CDN pipeline deploys each main commit's runtime under an immutable\n * SHA root, so this value names the CDN build associated with this npm\n * version. Pass it as the `pinBuildSha` loader option to load exactly that\n * runtime build — not recommended for production (see the README).\n *\n * In the repository, and in any locally built copy, the value is the\n * unstamped 40-zero placeholder ({@link isCdnBuildShaStamped} returns\n * `false`); only published tarballs carry a real SHA.\n */\nexport const CDN_BUILD_SHA: string = \"7563635673f460d885fa6976033d7b09590d9a49\";\n\n/**\n * Whether `sha` (default {@link CDN_BUILD_SHA}) is a stamped full git commit\n * SHA rather than the unstamped repo placeholder.\n */\nexport function isCdnBuildShaStamped(sha: string = CDN_BUILD_SHA): boolean {\n\tconst normalized = sha.trim().toLowerCase();\n\treturn (\n\t\tGIT_SHA_PATTERN.test(normalized) && !UNSTAMPED_SHA_PATTERN.test(normalized)\n\t);\n}\n","/**\n * Lifecycle channel between `createAdaEmbedInterface` and the npm loader's\n * memo: a non-enumerable getter over closure state, so the loader never\n * mutates the public surface and `Object.freeze` on the facade still works.\n * `Symbol.for` because the loader and the CDN runtime are separate builds;\n * a runtime that predates the getter yields `undefined` — degrade gracefully.\n */\nexport const EMBED_LIFECYCLE_STOPPED = Symbol.for(\n\t\"ada-cx/messaging-sdk/embed-stopped\",\n);\n\n/** Read the facade's stopped flag; `undefined` when the runtime predates it. */\nexport function readEmbedStoppedFlag(ada: object): boolean | undefined {\n\tconst value = (ada as Record<symbol, unknown>)[EMBED_LIFECYCLE_STOPPED];\n\treturn typeof value === \"boolean\" ? value : undefined;\n}\n\n/** Define the getter at facade creation time, before any host freeze. */\nexport function defineEmbedStoppedFlag(\n\tada: object,\n\treadStopped: () => boolean,\n): void {\n\tObject.defineProperty(ada, EMBED_LIFECYCLE_STOPPED, {\n\t\tget: readStopped,\n\t\tenumerable: false,\n\t\tconfigurable: false,\n\t});\n}\n","import type { AdaMessagingClient } from \"../client/client\";\nimport type { AdaMessagingStartOptions } from \"../client/client-types\";\nimport type {\n\tAdaEmbedInterface,\n\tcreateAdaEmbedInterface,\n\tdispatchEmbedLoaderInitialActionQueue,\n\tdispatchEmbedLoaderInitialActionQueueForAtomicHandoff,\n} from \"../client/embed-interface\";\nimport { readEmbedStoppedFlag } from \"../client/embed-lifecycle\";\nimport type {\n\tmountAdaWebViewRuntime,\n\tresolveAdaWebViewRuntimeAssets,\n} from \"../mobile-webview-runtime\";\n\n/**\n * Production CDN root the loader resolves the SDK bootstrap from when no\n * `cdnBase` override is given. The npm package never pins a runtime version;\n * the bootstrap at this root resolves the current rollout at load time.\n */\nexport const DEFAULT_MESSAGING_CDN_BASE =\n\t\"https://messaging-assets.ada.support/\";\n\nconst SDK_BOOTSTRAP_FILENAME = \"sdk.js\";\n\n// The CDN pipeline deploys each main commit's runtime as an immutable\n// SHA-rooted entry (`<cdnBase>/<sha>/sdk/index.js`); the mutable `sdk.js`\n// bootstrap resolves the current rollout to one of those roots at load time.\n// A pin bypasses the bootstrap and imports one root directly.\nconst PINNED_SDK_ENTRY_PATH = \"sdk/index.js\";\n\n// Strict on purpose: the pin is interpolated into a CDN path, so only a full\n// lowercase 40-hex git SHA may pass (mirrors scripts/sdk.js's\n// VERSION_OVERRIDE_PATTERN security boundary, minus the short-SHA and pr-N\n// forms — the npm surface pins exactly what CDN_BUILD_SHA carries).\nconst PINNED_BUILD_SHA_PATTERN = /^[0-9a-f]{40}$/;\nconst UNSTAMPED_BUILD_SHA_PATTERN = /^0{40}$/;\n\n/** Why a {@link MessagingSdkLoadError} was raised. */\nexport type MessagingSdkLoadErrorCode =\n\t/**\n\t * The `cdnBase` option is not a valid `https:` URL (plain `http:` is\n\t * allowed only for loopback hosts).\n\t */\n\t| \"invalid_cdn_base\"\n\t/** The `pinBuildSha` option is not a full 40-character hex git SHA. */\n\t| \"invalid_build_sha\"\n\t/**\n\t * The `pinBuildSha` option is the unstamped 40-zero placeholder: this\n\t * copy of the package was built from the repository, not published, so\n\t * its `CDN_BUILD_SHA` names no CDN build.\n\t */\n\t| \"unstamped_build_sha\"\n\t/** The dynamic import of the CDN bootstrap failed (network, CSP, 404). */\n\t| \"sdk_import_failed\"\n\t/** The imported module does not expose the Ada Messaging SDK surface. */\n\t| \"sdk_module_invalid\";\n\n/** Typed failure raised by {@link loadMessagingSdk} and {@link loadAdaMessaging}. */\nexport class MessagingSdkLoadError extends Error {\n\treadonly code: MessagingSdkLoadErrorCode;\n\n\tconstructor(\n\t\tmessage: string,\n\t\tcode: MessagingSdkLoadErrorCode,\n\t\tcause?: unknown,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"MessagingSdkLoadError\";\n\t\tthis.code = code;\n\t\tif (cause !== undefined) {\n\t\t\tthis.cause = cause;\n\t\t}\n\t}\n}\n\n/**\n * The programmatic messaging interface {@link loadAdaMessaging} resolves. An\n * alias of the runtime's `AdaEmbedInterface`, which keeps that name because it\n * is also the legacy `window.adaEmbed` compat facade.\n */\nexport type AdaMessagingInterface = AdaEmbedInterface;\n\n/**\n * The public surface of the CDN-resolved SDK module, as loaded from\n * `<cdnBase>/sdk.js`. Types only — the implementation always comes from the\n * CDN at load time and is never part of this npm package.\n */\nexport interface MessagingSdkModule {\n\tAdaMessagingClient: typeof AdaMessagingClient;\n\tcreateAdaEmbedInterface: typeof createAdaEmbedInterface;\n\tdispatchEmbedLoaderInitialActionQueue: typeof dispatchEmbedLoaderInitialActionQueue;\n\tdispatchEmbedLoaderInitialActionQueueForAtomicHandoff: typeof dispatchEmbedLoaderInitialActionQueueForAtomicHandoff;\n\tmountAdaWebViewRuntime: typeof mountAdaWebViewRuntime;\n\tresolveAdaWebViewRuntimeAssets: typeof resolveAdaWebViewRuntimeAssets;\n}\n\ntype ImportSdkModule = (url: string) => Promise<unknown>;\n\nexport interface LoadMessagingSdkOptions {\n\t/**\n\t * CDN root to resolve `sdk.js` from. Must be an `https:` URL; plain\n\t * `http:` is accepted only for loopback hosts (`localhost`, `127.0.0.1`,\n\t * `[::1]`, `*.localhost`) during local development. Defaults to the\n\t * production root ({@link DEFAULT_MESSAGING_CDN_BASE}). Override it with\n\t * the Ada-provided asset host for a staging validation window only;\n\t * production pages must keep the default.\n\t */\n\tcdnBase?: string;\n\t/**\n\t * Full 40-character git commit SHA of a deployed CDN build. When set, the\n\t * loader skips the rollout bootstrap and imports that build's immutable\n\t * entry (`<cdnBase>/<sha>/sdk/index.js`) directly. Pass the package's\n\t * `CDN_BUILD_SHA` export to pin the build associated with this npm\n\t * version. NOT recommended for production: a pinned runtime misses Ada's\n\t * fixes and rollouts, and may predate server contract changes. Composes\n\t * with `cdnBase` for staged validation.\n\t */\n\tpinBuildSha?: string;\n\t/**\n\t * Import seam for unit tests. Defaults to a native dynamic `import()` of\n\t * the resolved bootstrap URL.\n\t */\n\timportModule?: ImportSdkModule;\n}\n\n// Both annotations are load-bearing: bundlers rewrite bare dynamic imports,\n// and this specifier must reach the browser untouched so the runtime always\n// resolves from Ada's CDN. The npm build for this entry is unminified so the\n// annotations survive into the published output.\nconst defaultImportModule: ImportSdkModule = (url) =>\n\timport(/* webpackIgnore: true */ /* @vite-ignore */ url);\n\n// Keyed by import seam so production memoizes on the module-level default\n// while each injected test seam gets an isolated cache.\nconst inFlightByImporter = new WeakMap<\n\tImportSdkModule,\n\tMap<string, Promise<MessagingSdkModule>>\n>();\n\n// Mirrors the loopback semantics of the shared `isLoopbackHost` /\n// `validateMessagingEndpoint` (shared/utils/src/url.ts) and the bridge\n// loader's copy (packages/bridge/src/npm/loader.ts). Inlined because the\n// published loader must stay dependency-free; keep the host set in sync.\nconst LOOPBACK_HOSTS = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\", \"::1\"]);\n\nfunction isLoopbackHostname(hostname: string): boolean {\n\tconst normalized = hostname.trim().toLowerCase();\n\t// `*.localhost` resolves to the loopback interface and is \"potentially\n\t// trustworthy\" per the Secure Contexts spec; no production host ends in\n\t// `.localhost`.\n\treturn LOOPBACK_HOSTS.has(normalized) || normalized.endsWith(\".localhost\");\n}\n\nfunction resolvePinnedBuildSha(pinBuildSha: string): string {\n\tconst sha = pinBuildSha.trim().toLowerCase();\n\tif (!PINNED_BUILD_SHA_PATTERN.test(sha)) {\n\t\tthrow new MessagingSdkLoadError(\n\t\t\t`The pinBuildSha option must be a full 40-character hex git SHA: \"${pinBuildSha}\".`,\n\t\t\t\"invalid_build_sha\",\n\t\t);\n\t}\n\tif (UNSTAMPED_BUILD_SHA_PATTERN.test(sha)) {\n\t\tthrow new MessagingSdkLoadError(\n\t\t\t\"The pinBuildSha option is the unstamped CDN_BUILD_SHA placeholder. Only the published npm package carries a stamped SHA; a repository or local build cannot pin a CDN build.\",\n\t\t\t\"unstamped_build_sha\",\n\t\t);\n\t}\n\treturn sha;\n}\n\n/**\n * The runtime this URL serves carries the SDK's security logic (endpoint\n * validation, session handling, the origin checks), so a cleartext transport\n * would let an on-path attacker replace it wholesale: `https:` is required,\n * with a loopback-only `http:` exception for local development.\n */\nfunction resolveSdkBootstrapUrl(\n\tcdnBase: string | undefined,\n\tpinBuildSha: string | undefined,\n): string {\n\tconst base = (cdnBase ?? DEFAULT_MESSAGING_CDN_BASE).trim();\n\t// Resolving against a base without a trailing slash would drop its last\n\t// path segment, so normalize before building the bootstrap URL.\n\tconst normalizedBase = base.endsWith(\"/\") ? base : `${base}/`;\n\tconst entryPath =\n\t\tpinBuildSha === undefined\n\t\t\t? SDK_BOOTSTRAP_FILENAME\n\t\t\t: `${resolvePinnedBuildSha(pinBuildSha)}/${PINNED_SDK_ENTRY_PATH}`;\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(entryPath, normalizedBase);\n\t} catch (cause) {\n\t\tthrow new MessagingSdkLoadError(\n\t\t\t`The cdnBase option is not a valid URL: \"${base}\".`,\n\t\t\t\"invalid_cdn_base\",\n\t\t\tcause,\n\t\t);\n\t}\n\tconst isHttps = url.protocol === \"https:\";\n\tconst isLoopbackHttp =\n\t\turl.protocol === \"http:\" && isLoopbackHostname(url.hostname);\n\tif (!isHttps && !isLoopbackHttp) {\n\t\tthrow new MessagingSdkLoadError(\n\t\t\t`The cdnBase option must use https (plain http is allowed only for loopback hosts): \"${base}\".`,\n\t\t\t\"invalid_cdn_base\",\n\t\t);\n\t}\n\treturn url.toString();\n}\n\n// A partial CDN module (mid-deploy, or a rolled-back build missing a newer\n// export) must fail here as a typed sdk_module_invalid error, not later as a\n// TypeError on the first missing call — so every export is checked. The\n// `satisfies` clause rejects names that are not interface members; the\n// exhaustiveness type below is what forces this list to grow with it.\nconst REQUIRED_SDK_EXPORTS = [\n\t\"AdaMessagingClient\",\n\t\"createAdaEmbedInterface\",\n\t\"dispatchEmbedLoaderInitialActionQueue\",\n\t\"dispatchEmbedLoaderInitialActionQueueForAtomicHandoff\",\n\t\"mountAdaWebViewRuntime\",\n\t\"resolveAdaWebViewRuntimeAssets\",\n] as const satisfies readonly (keyof MessagingSdkModule)[];\n\n// Compile-time exhaustiveness: adding a MessagingSdkModule member without\n// listing it in REQUIRED_SDK_EXPORTS turns this type into `never`, failing\n// the `true` assignment below.\ntype AllSdkExportsListed =\n\tExclude<\n\t\tkeyof MessagingSdkModule,\n\t\t(typeof REQUIRED_SDK_EXPORTS)[number]\n\t> extends never\n\t\t? true\n\t\t: never;\nconst _allSdkExportsListed: AllSdkExportsListed = true;\nvoid _allSdkExportsListed;\n\nfunction isMessagingSdkModule(value: unknown): value is MessagingSdkModule {\n\tif (typeof value !== \"object\" || value === null) {\n\t\treturn false;\n\t}\n\tconst candidate = value as Record<string, unknown>;\n\treturn REQUIRED_SDK_EXPORTS.every(\n\t\t(key) => typeof candidate[key] === \"function\",\n\t);\n}\n\nasync function importSdkModule(\n\turl: string,\n\timportModule: ImportSdkModule,\n): Promise<MessagingSdkModule> {\n\tlet loaded: unknown;\n\ttry {\n\t\tloaded = await importModule(url);\n\t} catch (cause) {\n\t\tthrow new MessagingSdkLoadError(\n\t\t\t`The Ada Messaging SDK failed to load from ${url}.`,\n\t\t\t\"sdk_import_failed\",\n\t\t\tcause,\n\t\t);\n\t}\n\tif (!isMessagingSdkModule(loaded)) {\n\t\tthrow new MessagingSdkLoadError(\n\t\t\t`The module at ${url} does not expose the Ada Messaging SDK interface.`,\n\t\t\t\"sdk_module_invalid\",\n\t\t);\n\t}\n\treturn loaded;\n}\n\n/**\n * Load the Ada Messaging SDK module from Ada's CDN.\n *\n * The returned promise is memoized per resolved URL: concurrent and repeated\n * calls share one in-flight import. A failed load clears the memo so a later\n * call retries. Rejections are always {@link MessagingSdkLoadError}.\n *\n * @example\n * const { createAdaEmbedInterface } = await loadMessagingSdk();\n */\nexport function loadMessagingSdk(\n\toptions: LoadMessagingSdkOptions = {},\n): Promise<MessagingSdkModule> {\n\tconst importModule = options.importModule ?? defaultImportModule;\n\tlet url: string;\n\ttry {\n\t\turl = resolveSdkBootstrapUrl(options.cdnBase, options.pinBuildSha);\n\t} catch (error) {\n\t\treturn Promise.reject(error);\n\t}\n\n\tlet inFlight = inFlightByImporter.get(importModule);\n\tif (!inFlight) {\n\t\tinFlight = new Map();\n\t\tinFlightByImporter.set(importModule, inFlight);\n\t}\n\tconst existing = inFlight.get(url);\n\tif (existing) {\n\t\treturn existing;\n\t}\n\n\tconst cache = inFlight;\n\tconst pending = importSdkModule(url, importModule);\n\tcache.set(url, pending);\n\tpending.catch(() => {\n\t\tif (cache.get(url) === pending) {\n\t\t\tcache.delete(url);\n\t\t}\n\t});\n\treturn pending;\n}\n\n// Keyed by import seam like the module memo above: production memoizes on\n// the module-level default while each injected test seam gets an isolated\n// cache. `ada` is set when the promise resolves, so the stopped-interface\n// diagnostic can consult the resolved facade without wrapping it.\ninterface StartedInterfaceMemo {\n\tpromise: Promise<AdaMessagingInterface>;\n\tsettings: AdaMessagingStartOptions;\n\tada?: AdaMessagingInterface;\n}\n\nconst startedInterfaceByImporter = new WeakMap<\n\tImportSdkModule,\n\tStartedInterfaceMemo\n>();\n\n// Ungated like the runtime logger's dropped-host-value channel: both call\n// sites fire only on host misuse, never on an ordinary page load.\nfunction warnHost(message: string): void {\n\ttry {\n\t\t// biome-ignore lint/suspicious/noConsole: the loader's sanctioned host-page diagnostic sink\n\t\tconsole.warn(`[Ada] ${message}`);\n\t} catch {\n\t\t// A host may replace console methods; diagnostics must not throw.\n\t}\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\tif (typeof value !== \"object\" || value === null) {\n\t\treturn false;\n\t}\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\n// Structural equality over the settings surface. Two functions compare equal:\n// fresh inline callbacks on a re-run (React Strict Mode effects) are not a\n// settings change worth a warning. Exotic objects compare by reference.\nfunction settingsEqual(a: unknown, b: unknown): boolean {\n\tif (Object.is(a, b)) {\n\t\treturn true;\n\t}\n\tif (typeof a === \"function\" && typeof b === \"function\") {\n\t\treturn true;\n\t}\n\tif (Array.isArray(a) && Array.isArray(b)) {\n\t\treturn (\n\t\t\ta.length === b.length &&\n\t\t\ta.every((item, index) => settingsEqual(item, b[index]))\n\t\t);\n\t}\n\tif (isPlainObject(a) && isPlainObject(b)) {\n\t\tconst aKeys = Object.keys(a);\n\t\tconst bKeys = new Set(Object.keys(b));\n\t\treturn (\n\t\t\taKeys.length === bKeys.size &&\n\t\t\taKeys.every((key) => bKeys.has(key) && settingsEqual(a[key], b[key]))\n\t\t);\n\t}\n\treturn false;\n}\n\n// Observes the facade's symbol-keyed lifecycle getter (embed-lifecycle.ts)\n// instead of wrapping stop/start, so the customer's interface is never\n// mutated; a pinned runtime that predates the getter yields no flag and the\n// stopped-interface diagnostic is skipped rather than guessed.\nfunction isInterfaceStopped(ada: AdaMessagingInterface): boolean {\n\treturn readEmbedStoppedFlag(ada) === true;\n}\n\nasync function startAdaMessaging(\n\tsettings: AdaMessagingStartOptions,\n\toptions: LoadMessagingSdkOptions,\n): Promise<AdaMessagingInterface> {\n\tconst sdkModule = await loadMessagingSdk(options);\n\tconst ada = sdkModule.createAdaEmbedInterface();\n\tawait ada.start(settings);\n\treturn ada;\n}\n\n/**\n * Load the SDK, create the messaging interface, and start the widget —\n * the npm-first equivalent of the script-tag + `window.adaSettings` setup.\n *\n * One widget per page: the returned promise is memoized, so repeated and\n * concurrent calls resolve to the same started interface and the first\n * call's settings win. A failed load or start clears the memo so a later\n * call retries. Manage the running widget through the returned interface:\n * `stop()` tears it down and a later `start(settings)` on the same interface\n * runs again. Calling {@link loadAdaMessaging} after `stop()` returns the\n * same stopped interface without restarting it. Both memo outcomes log a\n * console warning: ignored differing settings, and a resolved interface\n * whose widget was stopped.\n *\n * Never assigns the interface to `window` or any other global: the returned\n * reference is the only handle, so hold it in module scope. A reference in\n * module scope is reachable only by your own code, never by other scripts on\n * the page.\n *\n * @example\n * // module scope: your code keeps the only reference\n * const ada = await loadAdaMessaging({\n * handle: \"my-bot\",\n * enableProgrammaticControl: true,\n * });\n * await ada.sendMessage(\"Hello\");\n */\nexport function loadAdaMessaging(\n\tsettings: AdaMessagingStartOptions,\n\toptions: LoadMessagingSdkOptions = {},\n): Promise<AdaMessagingInterface> {\n\tconst importModule = options.importModule ?? defaultImportModule;\n\tconst existing = startedInterfaceByImporter.get(importModule);\n\tif (existing) {\n\t\tif (!settingsEqual(settings, existing.settings)) {\n\t\t\twarnHost(\n\t\t\t\t\"loadAdaMessaging() was already called: the new settings are ignored and the existing interface is returned. To apply new settings, call stop() then start(settings) on it.\",\n\t\t\t);\n\t\t}\n\t\tif (existing.ada && isInterfaceStopped(existing.ada)) {\n\t\t\twarnHost(\n\t\t\t\t\"loadAdaMessaging() resolved an interface whose widget was stopped and never restarts it. Call start(settings) on it to run the widget again.\",\n\t\t\t);\n\t\t}\n\t\treturn existing.promise;\n\t}\n\tconst memo: StartedInterfaceMemo = {\n\t\tpromise: startAdaMessaging(settings, options),\n\t\tsettings,\n\t};\n\tstartedInterfaceByImporter.set(importModule, memo);\n\tmemo.promise.then(\n\t\t(ada) => {\n\t\t\tmemo.ada = ada;\n\t\t},\n\t\t() => {\n\t\t\tif (startedInterfaceByImporter.get(importModule) === memo) {\n\t\t\t\tstartedInterf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S,mBAAmB,KAAqC;AAChE,QAAO,qBAAqB,IAAI,KAAK;;AAGtC,eAAe,kBACd,UACA,SACiC;CAEjC,MAAM,OADY,MAAM,iBAAiB,QAAQ,EAC3B,yBAAyB;AAC/C,OAAM,IAAI,MAAM,SAAS;AACzB,QAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BR,SAAgB,iBACf,UACA,UAAmC,EAAE,EACJ;CACjC,MAAM,eAAe,QAAQ,gBAAgB;CAC7C,MAAM,WAAW,2BAA2B,IAAI,aAAa;AAC7D,KAAI,UAAU;AACb,MAAI,CAAC,cAAc,UAAU,SAAS,SAAS,CAC9C,UACC,6KACA;AAEF,MAAI,SAAS,OAAO,mBAAmB,SAAS,IAAI,CACnD,UACC,+IACA;AAEF,SAAO,SAAS;;CAEjB,MAAM,OAA6B;EAClC,SAAS,kBAAkB,UAAU,QAAQ;EAC7C;EACA;AACD,4BAA2B,IAAI,cAAc,KAAK;AAClD,MAAK,QAAQ,MACX,QAAQ;AACR,OAAK,MAAM;UAEN;AACL,MAAI,2BAA2B,IAAI,aAAa,KAAK,KACpD,4BAA2B,OAAO,aAAa;GAGjD;AACD,QAAO,KAAK"}
1
+ {"version":3,"file":"index.cjs","names":[],"sources":["../../src/npm/build-info.ts","../../src/client/embed-lifecycle.ts","../../src/npm/loader.ts"],"sourcesContent":["// The repo copy carries the 40-zero placeholder; the publish workflow\n// (.github/workflows/messaging-publish-web-packages.yml) stamps the real\n// commit SHA into the built output via scripts/stamp-cdn-build-sha.mjs and\n// verifies the packed tarball before `npm publish`. Keep the placeholder as\n// a single 40-zero string literal: the stamp is a same-length text\n// replacement, so source maps stay valid.\nconst GIT_SHA_PATTERN = /^[0-9a-f]{40}$/;\nconst UNSTAMPED_SHA_PATTERN = /^0{40}$/;\n\n/**\n * Git commit SHA of the monorepo commit this npm version was published from.\n * The CDN pipeline deploys each main commit's runtime under an immutable\n * SHA root, so this value names the CDN build associated with this npm\n * version. Pass it as the `pinBuildSha` loader option to load exactly that\n * runtime build — not recommended for production (see the README).\n *\n * In the repository, and in any locally built copy, the value is the\n * unstamped 40-zero placeholder ({@link isCdnBuildShaStamped} returns\n * `false`); only published tarballs carry a real SHA.\n */\nexport const CDN_BUILD_SHA: string = \"2765b9b100c4d9385cfe67d138e18170b1fadf35\";\n\n/**\n * Whether `sha` (default {@link CDN_BUILD_SHA}) is a stamped full git commit\n * SHA rather than the unstamped repo placeholder.\n */\nexport function isCdnBuildShaStamped(sha: string = CDN_BUILD_SHA): boolean {\n\tconst normalized = sha.trim().toLowerCase();\n\treturn (\n\t\tGIT_SHA_PATTERN.test(normalized) && !UNSTAMPED_SHA_PATTERN.test(normalized)\n\t);\n}\n","/**\n * Lifecycle channel between `createAdaEmbedInterface` and the npm loader's\n * memo: a non-enumerable getter over closure state, so the loader never\n * mutates the public surface and `Object.freeze` on the facade still works.\n * `Symbol.for` because the loader and the CDN runtime are separate builds;\n * a runtime that predates the getter yields `undefined` — degrade gracefully.\n */\nexport const EMBED_LIFECYCLE_STOPPED = Symbol.for(\n\t\"ada-cx/messaging-sdk/embed-stopped\",\n);\n\n/** Read the facade's stopped flag; `undefined` when the runtime predates it. */\nexport function readEmbedStoppedFlag(ada: object): boolean | undefined {\n\tconst value = (ada as Record<symbol, unknown>)[EMBED_LIFECYCLE_STOPPED];\n\treturn typeof value === \"boolean\" ? value : undefined;\n}\n\n/** Define the getter at facade creation time, before any host freeze. */\nexport function defineEmbedStoppedFlag(\n\tada: object,\n\treadStopped: () => boolean,\n): void {\n\tObject.defineProperty(ada, EMBED_LIFECYCLE_STOPPED, {\n\t\tget: readStopped,\n\t\tenumerable: false,\n\t\tconfigurable: false,\n\t});\n}\n","import type { AdaMessagingClient } from \"../client/client\";\nimport type { AdaMessagingStartOptions } from \"../client/client-types\";\nimport type {\n\tAdaEmbedInterface,\n\tcreateAdaEmbedInterface,\n\tdispatchEmbedLoaderInitialActionQueue,\n\tdispatchEmbedLoaderInitialActionQueueForAtomicHandoff,\n} from \"../client/embed-interface\";\nimport { readEmbedStoppedFlag } from \"../client/embed-lifecycle\";\nimport type {\n\tmountAdaWebViewRuntime,\n\tresolveAdaWebViewRuntimeAssets,\n} from \"../mobile-webview-runtime\";\n\n/**\n * Production CDN root the loader resolves the SDK bootstrap from when no\n * `cdnBase` override is given. The npm package never pins a runtime version;\n * the bootstrap at this root resolves the current rollout at load time.\n */\nexport const DEFAULT_MESSAGING_CDN_BASE =\n\t\"https://messaging-assets.ada.support/\";\n\nexport const FALLBACK_MESSAGING_CDN_BASE =\n\t\"https://static.ada.support/messaging/\";\n\nconst SDK_BOOTSTRAP_FILENAME = \"sdk.js\";\n\n// The CDN pipeline deploys each main commit's runtime as an immutable\n// SHA-rooted entry (`<cdnBase>/<sha>/sdk/index.js`); the mutable `sdk.js`\n// bootstrap resolves the current rollout to one of those roots at load time.\n// A pin bypasses the bootstrap and imports one root directly.\nconst PINNED_SDK_ENTRY_PATH = \"sdk/index.js\";\n\n// Strict on purpose: the pin is interpolated into a CDN path, so only a full\n// lowercase 40-hex git SHA may pass (mirrors scripts/sdk.js's\n// VERSION_OVERRIDE_PATTERN security boundary, minus the short-SHA and pr-N\n// forms — the npm surface pins exactly what CDN_BUILD_SHA carries).\nconst PINNED_BUILD_SHA_PATTERN = /^[0-9a-f]{40}$/;\nconst UNSTAMPED_BUILD_SHA_PATTERN = /^0{40}$/;\n\n/** Why a {@link MessagingSdkLoadError} was raised. */\nexport type MessagingSdkLoadErrorCode =\n\t/**\n\t * The `cdnBase` option is not a valid `https:` URL (plain `http:` is\n\t * allowed only for loopback hosts).\n\t */\n\t| \"invalid_cdn_base\"\n\t/** The `pinBuildSha` option is not a full 40-character hex git SHA. */\n\t| \"invalid_build_sha\"\n\t/**\n\t * The `pinBuildSha` option is the unstamped 40-zero placeholder: this\n\t * copy of the package was built from the repository, not published, so\n\t * its `CDN_BUILD_SHA` names no CDN build.\n\t */\n\t| \"unstamped_build_sha\"\n\t/** The dynamic import of the CDN bootstrap failed (fetch or evaluation). */\n\t| \"sdk_import_failed\"\n\t/** The imported module does not expose the Ada Messaging SDK surface. */\n\t| \"sdk_module_invalid\";\n\n/** Typed failure raised by {@link loadMessagingSdk} and {@link loadAdaMessaging}. */\nexport class MessagingSdkLoadError extends Error {\n\treadonly code: MessagingSdkLoadErrorCode;\n\tdeclare readonly fallbackCause?: MessagingSdkLoadError;\n\n\tconstructor(\n\t\tmessage: string,\n\t\tcode: MessagingSdkLoadErrorCode,\n\t\tcause?: unknown,\n\t\tfallbackCause?: MessagingSdkLoadError,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"MessagingSdkLoadError\";\n\t\tthis.code = code;\n\t\tif (cause !== undefined) {\n\t\t\tthis.cause = cause;\n\t\t}\n\t\tif (fallbackCause !== undefined) {\n\t\t\tObject.defineProperty(this, \"fallbackCause\", {\n\t\t\t\tvalue: fallbackCause,\n\t\t\t\tenumerable: true,\n\t\t\t});\n\t\t}\n\t}\n}\n\n/**\n * The programmatic messaging interface {@link loadAdaMessaging} resolves. An\n * alias of the runtime's `AdaEmbedInterface`, which keeps that name because it\n * is also the legacy `window.adaEmbed` compat facade.\n */\nexport type AdaMessagingInterface = AdaEmbedInterface;\n\n/**\n * The public surface of the CDN-resolved SDK module, as loaded from\n * `<cdnBase>/sdk.js`. Types only — the implementation always comes from the\n * CDN at load time and is never part of this npm package.\n */\nexport interface MessagingSdkModule {\n\tAdaMessagingClient: typeof AdaMessagingClient;\n\tcreateAdaEmbedInterface: typeof createAdaEmbedInterface;\n\tdispatchEmbedLoaderInitialActionQueue: typeof dispatchEmbedLoaderInitialActionQueue;\n\tdispatchEmbedLoaderInitialActionQueueForAtomicHandoff: typeof dispatchEmbedLoaderInitialActionQueueForAtomicHandoff;\n\tmountAdaWebViewRuntime: typeof mountAdaWebViewRuntime;\n\tresolveAdaWebViewRuntimeAssets: typeof resolveAdaWebViewRuntimeAssets;\n}\n\ntype ImportSdkModule = (url: string) => Promise<unknown>;\n\nexport interface LoadMessagingSdkOptions {\n\t/**\n\t * CDN root to resolve `sdk.js` from. Must be an `https:` URL; plain\n\t * `http:` is accepted only for loopback hosts (`localhost`, `127.0.0.1`,\n\t * `[::1]`, `*.localhost`) during local development. Defaults to the\n\t * production root ({@link DEFAULT_MESSAGING_CDN_BASE}). An explicit value,\n\t * including {@link FALLBACK_MESSAGING_CDN_BASE}, disables the automatic\n\t * static-root fallback.\n\t */\n\tcdnBase?: string;\n\t/**\n\t * Full 40-character git commit SHA of a deployed CDN build. When set, the\n\t * loader skips the rollout bootstrap and imports that build's immutable\n\t * entry (`<cdnBase>/<sha>/sdk/index.js`) directly. Pass the package's\n\t * `CDN_BUILD_SHA` export to pin the build associated with this npm\n\t * version. NOT recommended for production: a pinned runtime misses Ada's\n\t * fixes and rollouts, and may predate server contract changes. Composes\n\t * with `cdnBase` for staged validation.\n\t */\n\tpinBuildSha?: string;\n\t/**\n\t * Import seam for unit tests. Defaults to a native dynamic `import()` of\n\t * the resolved bootstrap URL.\n\t */\n\timportModule?: ImportSdkModule;\n}\n\n// Both annotations are load-bearing: bundlers rewrite bare dynamic imports,\n// and this specifier must reach the browser untouched so the runtime always\n// resolves from Ada's CDN. The npm build for this entry is unminified so the\n// annotations survive into the published output.\nconst defaultImportModule: ImportSdkModule = (url) =>\n\timport(/* webpackIgnore: true */ /* @vite-ignore */ url);\n\n// Keyed by import seam so production memoizes on the module-level default\n// while each injected test seam gets an isolated cache.\ninterface SdkLoaderState {\n\timports: Map<string, Promise<MessagingSdkModule>>;\n\tdefaultLoads: Map<string, Promise<MessagingSdkModule>>;\n}\n\nconst loadsByImporter = new WeakMap<ImportSdkModule, SdkLoaderState>();\n\n// Share the warning across independently bundled copies of this loader.\nconst FALLBACK_WARNING_KEY = Symbol.for(\"ada.messaging.sdk.fallbackWarning\");\nconst warningScope = globalThis as typeof globalThis & {\n\t[FALLBACK_WARNING_KEY]?: boolean;\n};\n\n// Mirrors the loopback semantics of the shared `isLoopbackHost` /\n// `validateMessagingEndpoint` (shared/utils/src/url.ts) and the bridge\n// loader's copy (packages/bridge/src/npm/loader.ts). Inlined because the\n// published loader must stay dependency-free; keep the host set in sync.\nconst LOOPBACK_HOSTS = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\", \"::1\"]);\n\nfunction isLoopbackHostname(hostname: string): boolean {\n\tconst normalized = hostname.trim().toLowerCase();\n\t// `*.localhost` resolves to the loopback interface and is \"potentially\n\t// trustworthy\" per the Secure Contexts spec; no production host ends in\n\t// `.localhost`.\n\treturn LOOPBACK_HOSTS.has(normalized) || normalized.endsWith(\".localhost\");\n}\n\nfunction resolvePinnedBuildSha(pinBuildSha: string): string {\n\tconst sha = pinBuildSha.trim().toLowerCase();\n\tif (!PINNED_BUILD_SHA_PATTERN.test(sha)) {\n\t\tthrow new MessagingSdkLoadError(\n\t\t\t`The pinBuildSha option must be a full 40-character hex git SHA: \"${pinBuildSha}\".`,\n\t\t\t\"invalid_build_sha\",\n\t\t);\n\t}\n\tif (UNSTAMPED_BUILD_SHA_PATTERN.test(sha)) {\n\t\tthrow new MessagingSdkLoadError(\n\t\t\t\"The pinBuildSha option is the unstamped CDN_BUILD_SHA placeholder. Only the published npm package carries a stamped SHA; a repository or local build cannot pin a CDN build.\",\n\t\t\t\"unstamped_build_sha\",\n\t\t);\n\t}\n\treturn sha;\n}\n\n/**\n * The runtime this URL serves carries the SDK's security logic (endpoint\n * validation, session handling, the origin checks), so a cleartext transport\n * would let an on-path attacker replace it wholesale: `https:` is required,\n * with a loopback-only `http:` exception for local development.\n */\nfunction resolveSdkBootstrapUrl(\n\tcdnBase: string | undefined,\n\tpinBuildSha: string | undefined,\n): string {\n\tconst base = (cdnBase ?? DEFAULT_MESSAGING_CDN_BASE).trim();\n\t// Resolving against a base without a trailing slash would drop its last\n\t// path segment, so normalize before building the bootstrap URL.\n\tconst normalizedBase = base.endsWith(\"/\") ? base : `${base}/`;\n\tconst entryPath =\n\t\tpinBuildSha === undefined\n\t\t\t? SDK_BOOTSTRAP_FILENAME\n\t\t\t: `${resolvePinnedBuildSha(pinBuildSha)}/${PINNED_SDK_ENTRY_PATH}`;\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(entryPath, normalizedBase);\n\t} catch (cause) {\n\t\tthrow new MessagingSdkLoadError(\n\t\t\t`The cdnBase option is not a valid URL: \"${base}\".`,\n\t\t\t\"invalid_cdn_base\",\n\t\t\tcause,\n\t\t);\n\t}\n\tconst isHttps = url.protocol === \"https:\";\n\tconst isLoopbackHttp =\n\t\turl.protocol === \"http:\" && isLoopbackHostname(url.hostname);\n\tif (!isHttps && !isLoopbackHttp) {\n\t\tthrow new MessagingSdkLoadError(\n\t\t\t`The cdnBase option must use https (plain http is allowed only for loopback hosts): \"${base}\".`,\n\t\t\t\"invalid_cdn_base\",\n\t\t);\n\t}\n\treturn url.toString();\n}\n\n// A partial CDN module (mid-deploy, or a rolled-back build missing a newer\n// export) must fail here as a typed sdk_module_invalid error, not later as a\n// TypeError on the first missing call — so every export is checked. The\n// `satisfies` clause rejects names that are not interface members; the\n// exhaustiveness type below is what forces this list to grow with it.\nconst REQUIRED_SDK_EXPORTS = [\n\t\"AdaMessagingClient\",\n\t\"createAdaEmbedInterface\",\n\t\"dispatchEmbedLoaderInitialActionQueue\",\n\t\"dispatchEmbedLoaderInitialActionQueueForAtomicHandoff\",\n\t\"mountAdaWebViewRuntime\",\n\t\"resolveAdaWebViewRuntimeAssets\",\n] as const satisfies readonly (keyof MessagingSdkModule)[];\n\n// Compile-time exhaustiveness: adding a MessagingSdkModule member without\n// listing it in REQUIRED_SDK_EXPORTS turns this type into `never`, failing\n// the `true` assignment below.\ntype AllSdkExportsListed =\n\tExclude<\n\t\tkeyof MessagingSdkModule,\n\t\t(typeof REQUIRED_SDK_EXPORTS)[number]\n\t> extends never\n\t\t? true\n\t\t: never;\nconst _allSdkExportsListed: AllSdkExportsListed = true;\nvoid _allSdkExportsListed;\n\nfunction isMessagingSdkModule(value: unknown): value is MessagingSdkModule {\n\tif (typeof value !== \"object\" || value === null) {\n\t\treturn false;\n\t}\n\tconst candidate = value as Record<string, unknown>;\n\treturn REQUIRED_SDK_EXPORTS.every(\n\t\t(key) => typeof candidate[key] === \"function\",\n\t);\n}\n\nasync function importSdkModule(\n\turl: string,\n\timportModule: ImportSdkModule,\n): Promise<MessagingSdkModule> {\n\tlet loaded: unknown;\n\ttry {\n\t\tloaded = await importModule(url);\n\t} catch (cause) {\n\t\tthrow new MessagingSdkLoadError(\n\t\t\t`The Ada Messaging SDK failed to load from ${url}.`,\n\t\t\t\"sdk_import_failed\",\n\t\t\tcause,\n\t\t);\n\t}\n\tif (!isMessagingSdkModule(loaded)) {\n\t\tthrow new MessagingSdkLoadError(\n\t\t\t`The module at ${url} does not expose the Ada Messaging SDK interface.`,\n\t\t\t\"sdk_module_invalid\",\n\t\t);\n\t}\n\treturn loaded;\n}\n\nfunction memoizeLoad(\n\tcache: Map<string, Promise<MessagingSdkModule>>,\n\turl: string,\n\tload: () => Promise<MessagingSdkModule>,\n): Promise<MessagingSdkModule> {\n\tconst existing = cache.get(url);\n\tif (existing) {\n\t\treturn existing;\n\t}\n\tconst pending = load();\n\tcache.set(url, pending);\n\tpending.catch(() => {\n\t\tif (cache.get(url) === pending) {\n\t\t\tcache.delete(url);\n\t\t}\n\t});\n\treturn pending;\n}\n\n/**\n * Load the Ada Messaging SDK module from Ada's CDN.\n *\n * The returned promise is memoized per resolved URL: concurrent and repeated\n * calls share one in-flight import. A failed load clears the memo so a later\n * call retries. Without `cdnBase`, an import failure at the default root is\n * retried once from {@link FALLBACK_MESSAGING_CDN_BASE}. Rejections are always\n * {@link MessagingSdkLoadError}.\n *\n * @example\n * const { createAdaEmbedInterface } = await loadMessagingSdk();\n */\nexport function loadMessagingSdk(\n\toptions: LoadMessagingSdkOptions = {},\n): Promise<MessagingSdkModule> {\n\tconst importModule = options.importModule ?? defaultImportModule;\n\tlet url: string;\n\tlet fallbackUrl: string | undefined;\n\ttry {\n\t\turl = resolveSdkBootstrapUrl(options.cdnBase, options.pinBuildSha);\n\t\tif (options.cdnBase === undefined) {\n\t\t\tfallbackUrl = resolveSdkBootstrapUrl(\n\t\t\t\tFALLBACK_MESSAGING_CDN_BASE,\n\t\t\t\toptions.pinBuildSha,\n\t\t\t);\n\t\t}\n\t} catch (error) {\n\t\treturn Promise.reject(error);\n\t}\n\n\tconst state = loadsByImporter.get(importModule) ?? {\n\t\timports: new Map<string, Promise<MessagingSdkModule>>(),\n\t\tdefaultLoads: new Map<string, Promise<MessagingSdkModule>>(),\n\t};\n\tloadsByImporter.set(importModule, state);\n\tconst load = (entryUrl: string) =>\n\t\tmemoizeLoad(state.imports, entryUrl, () =>\n\t\t\timportSdkModule(entryUrl, importModule),\n\t\t);\n\tif (fallbackUrl === undefined) {\n\t\treturn load(url);\n\t}\n\n\tconst retryUrl = fallbackUrl;\n\t// Keep fallback outcomes separate so explicit-root callers share the import,\n\t// but never inherit another caller's permission to retry a different root.\n\treturn memoizeLoad(state.defaultLoads, url, () =>\n\t\tload(url).catch(async (error: unknown) => {\n\t\t\tif (\n\t\t\t\t!(error instanceof MessagingSdkLoadError) ||\n\t\t\t\terror.code !== \"sdk_import_failed\"\n\t\t\t) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\t// CSP rejects import() without a network request, so this retry adds no\n\t\t\t// user-visible delay; retrying a genuine network failure once is acceptable too.\n\t\t\tlet module: MessagingSdkModule;\n\t\t\ttry {\n\t\t\t\tmodule = await load(retryUrl);\n\t\t\t} catch (cause) {\n\t\t\t\tif (!(cause instanceof MessagingSdkLoadError)) {\n\t\t\t\t\tthrow cause;\n\t\t\t\t}\n\t\t\t\tthrow new MessagingSdkLoadError(\n\t\t\t\t\tcause.code === \"sdk_import_failed\"\n\t\t\t\t\t\t? `The Ada Messaging SDK failed to load from both ${url} and ${retryUrl}.`\n\t\t\t\t\t\t: cause.message,\n\t\t\t\t\tcause.code,\n\t\t\t\t\terror,\n\t\t\t\t\tcause,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!warningScope[FALLBACK_WARNING_KEY]) {\n\t\t\t\twarningScope[FALLBACK_WARNING_KEY] = true;\n\t\t\t\tconst cause = error.cause;\n\t\t\t\t// Browsers reject blocked, unreachable, or missing imports with TypeError.\n\t\t\t\t// An evaluation-time TypeError still looks like a fetch failure, as before;\n\t\t\t\t// this heuristic narrows diagnostic noise but cannot prove the cause.\n\t\t\t\twarnHost(\n\t\t\t\t\tcause instanceof TypeError\n\t\t\t\t\t\t? `Loaded the Messaging SDK from ${FALLBACK_MESSAGING_CDN_BASE} because the default root ${DEFAULT_MESSAGING_CDN_BASE} was blocked or unavailable. Add https://messaging-assets.ada.support to script-src, connect-src and frame-src, or pass cdnBase: \"${FALLBACK_MESSAGING_CDN_BASE}\".`\n\t\t\t\t\t\t: `Loaded the Messaging SDK from ${FALLBACK_MESSAGING_CDN_BASE} because the module at ${url} failed to evaluate (${describeRejection(cause)}). This is an Ada-side problem, not your host's CSP. Report it to Ada.`,\n\t\t\t\t\tcause,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn module;\n\t\t}),\n\t);\n}\n\n// Keyed by import seam like the module memo above: production memoizes on\n// the module-level default while each injected test seam gets an isolated\n// cache. `ada` is set when the promise resolves, so the stopped-interface\n// diagnostic can consult the resolved facade without wrapping it.\ninterface StartedInterfaceMemo {\n\tpromise: Promise<AdaMessagingInterface>;\n\tsettings: AdaMessagingStartOptions;\n\tada?: AdaMessagingInterface;\n}\n\nconst startedInterfaceByImporter = new WeakMap<\n\tImportSdkModule,\n\tStartedInterfaceMemo\n>();\n\n// A rejection can be any value, including one that throws on String(); a\n// diagnostic must never turn a successful fallback into a rejected load.\nfunction describeRejection(cause: unknown): string {\n\ttry {\n\t\treturn cause instanceof Error\n\t\t\t? `${cause.name}: ${cause.message}`\n\t\t\t: String(cause);\n\t} catch {\n\t\treturn \"unknown error\";\n\t}\n}\n\n// Ungated like the runtime logger's dropped-host-value channel so host\n// configuration diagnostics remain visible without debug logging.\nfunction warnHost(message: string, cause?: unknown): void {\n\ttry {\n\t\t// biome-ignore lint/suspicious/noConsole: the loader's sanctioned host-page diagnostic sink\n\t\tconsole.warn(`[Ada] ${message}`, ...(cause === undefined ? [] : [cause]));\n\t} catch {\n\t\t// A host may replace console methods; diagnostics must not throw.\n\t}\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\tif (typeof value !== \"object\" || value === null) {\n\t\treturn false;\n\t}\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\n// Structural equality over the settings surface. Two functions compare equal:\n// fresh inline callbacks on a re-run (React Strict Mode effects) are not a\n// settings change worth a warning. Exotic objects compare by reference.\nfunction settingsEqual(a: unknown, b: unknown): boolean {\n\tif (Object.is(a, b)) {\n\t\treturn true;\n\t}\n\tif (typeof a === \"function\" && typeof b === \"function\") {\n\t\treturn true;\n\t}\n\tif (Array.isArray(a) && Array.isArray(b)) {\n\t\treturn (\n\t\t\ta.length === b.length &&\n\t\t\ta.every((item, index) => settingsEqual(item, b[index]))\n\t\t);\n\t}\n\tif (isPlainObject(a) && isPlainObject(b)) {\n\t\tconst aKeys = Object.keys(a);\n\t\tconst bKeys = new Set(Object.keys(b));\n\t\treturn (\n\t\t\taKeys.length === bKeys.size &&\n\t\t\taKeys.every((key) => bKeys.has(key) && settingsEqual(a[key], b[key]))\n\t\t);\n\t}\n\treturn false;\n}\n\n// Observes the facade's symbol-keyed lifecycle getter (embed-lifecycle.ts)\n// instead of wrapping stop/start, so the customer's interface is never\n// mutated; a pinned runtime that predates the getter yields no flag and the\n// stopped-interface diagnostic is skipped rather than guessed.\nfunction isInterfaceStopped(ada: AdaMessagingInterface): boolean {\n\treturn readEmbedStoppedFlag(ada) === true;\n}\n\nasync function startAdaMessaging(\n\tsettings: AdaMessagingStartOptions,\n\toptions: LoadMessagingSdkOptions,\n): Promise<AdaMessagingInterface> {\n\tconst sdkModule = await loadMessagingSdk(options);\n\tconst ada = sdkModule.createAdaEmbedInterface();\n\tawait ada.start(settings);\n\treturn ada;\n}\n\n/**\n * Load the SDK, create the messaging interface, and start the widget —\n * the npm-first equivalent of the script-tag + `window.adaSettings` setup.\n *\n * One widget per page: the returned promise is memoized, so repeated and\n * concurrent calls resolve to the same started interface and the first\n * call's settings win. A failed load or start clears the memo so a later\n * call retries. Manage the running widget through the returned interface:\n * `stop()` tears it down and a later `start(settings)` on the same interface\n * runs again. Calling {@link loadAdaMessaging} after `stop()` returns the\n * same stopped interface without restarting it. Both memo outcomes log a\n * console warning: ignored differing settings, and a resolved interface\n * whose widget was stopped.\n *\n * Never assigns the interface to `window` or any other global: the returned\n * reference is the only handle, so hold it in module scope. A reference in\n * module scope is reachable only by your own code, never by other scripts on\n * the page.\n *\n * @example\n * // module scope: your code keeps the only reference\n * const ada = await loadAdaMessaging({\n * handle: \"my-bot\",\n * enableProgrammaticControl: true,\n * });\n * await ada.sendMessage(\"Hello\");\n */\nexport function loadAdaMessaging(\n\tsettings: AdaMessagingStartOptions,\n\toptions: LoadMessagingSdkOptions = {},\n): Promise<AdaMessagingInterface> {\n\tconst importModule = options.importModule ?? defaultImportModule;\n\tconst existing = startedInterfaceByImporter.get(importModule);\n\tif (existing) {\n\t\tif (!settingsEqual(settings, existing.settings)) {\n\t\t\twarnHost(\n\t\t\t\t\"loadAdaMessaging() was already called: the new settings are ignored and the existing interface is returned. To apply new settings, call stop() then start(settings) on it.\",\n\t\t\t);\n\t\t}\n\t\tif (existing.ada && isInterfaceStopped(existing.ada)) {\n\t\t\twarnHost(\n\t\t\t\t\"loadAdaMessaging() resolved an interface whose widget was stopped and never restarts it. Call start(settings) on it to run the widget again.\",\n\t\t\t);\n\t\t}\n\t\treturn existing.promise;\n\t}\n\tconst memo: StartedInterfaceMemo = {\n\t\tpromise: startAdaMessaging(settings, options),\n\t\tsettings,\n\t};\n\tstartedInterfaceByImporter.set(importModule, memo);\n\tmemo.promise.then(\n\t\t(ada) => {\n\t\t\tmemo.ada = ada;\n\t\t},\n\t\t() => {\n\t\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KAAK,CAAC;;AAGvE,QAAO;;AAOR,SAAS,mBAAmB,KAAqC;AAChE,QAAO,qBAAqB,IAAI,KAAK;;AAGtC,eAAe,kBACd,UACA,SACiC;CAEjC,MAAM,OADY,MAAM,iBAAiB,QAAQ,EAC3B,yBAAyB;AAC/C,OAAM,IAAI,MAAM,SAAS;AACzB,QAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BR,SAAgB,iBACf,UACA,UAAmC,EAAE,EACJ;CACjC,MAAM,eAAe,QAAQ,gBAAgB;CAC7C,MAAM,WAAW,2BAA2B,IAAI,aAAa;AAC7D,KAAI,UAAU;AACb,MAAI,CAAC,cAAc,UAAU,SAAS,SAAS,CAC9C,UACC,6KACA;AAEF,MAAI,SAAS,OAAO,mBAAmB,SAAS,IAAI,CACnD,UACC,+IACA;AAEF,SAAO,SAAS;;CAEjB,MAAM,OAA6B;EAClC,SAAS,kBAAkB,UAAU,QAAQ;EAC7C;EACA;AACD,4BAA2B,IAAI,cAAc,KAAK;AAClD,MAAK,QAAQ,MACX,QAAQ;AACR,OAAK,MAAM;UAEN;AACL,MAAI,2BAA2B,IAAI,aAAa,KAAK,KACpD,4BAA2B,OAAO,aAAa;GAGjD;AACD,QAAO,KAAK"}
@@ -12,4 +12,4 @@ import type { mountAdaWebViewRuntime, resolveAdaWebViewRuntimeAssets, } from "..
12
12
  export type { mountAdaWebViewRuntime, resolveAdaWebViewRuntimeAssets };
13
13
  export { CDN_BUILD_SHA, isCdnBuildShaStamped } from "./build-info.cjs";
14
14
  export type { AdaMessagingInterface, LoadMessagingSdkOptions, MessagingSdkLoadErrorCode, MessagingSdkModule, } from "./loader.cjs";
15
- export { DEFAULT_MESSAGING_CDN_BASE, loadAdaMessaging, loadMessagingSdk, MessagingSdkLoadError, } from "./loader.cjs";
15
+ export { DEFAULT_MESSAGING_CDN_BASE, FALLBACK_MESSAGING_CDN_BASE, loadAdaMessaging, loadMessagingSdk, MessagingSdkLoadError, } from "./loader.cjs";
@@ -6,4 +6,4 @@ export type { FrameChannel, FrameChild, FrameMessage, FrameName, FrameToSdkEvent
6
6
  export type { mountAdaWebViewRuntime, resolveAdaWebViewRuntimeAssets, } from "../mobile-webview-runtime.js";
7
7
  export { CDN_BUILD_SHA, isCdnBuildShaStamped } from "./build-info.js";
8
8
  export type { AdaMessagingInterface, LoadMessagingSdkOptions, MessagingSdkLoadErrorCode, MessagingSdkModule, } from "./loader.js";
9
- export { DEFAULT_MESSAGING_CDN_BASE, loadAdaMessaging, loadMessagingSdk, MessagingSdkLoadError, } from "./loader.js";
9
+ export { DEFAULT_MESSAGING_CDN_BASE, FALLBACK_MESSAGING_CDN_BASE, loadAdaMessaging, loadMessagingSdk, MessagingSdkLoadError, } from "./loader.js";
package/dist/npm/index.js CHANGED
@@ -12,7 +12,7 @@ var UNSTAMPED_SHA_PATTERN = /^0{40}$/;
12
12
  * unstamped 40-zero placeholder ({@link isCdnBuildShaStamped} returns
13
13
  * `false`); only published tarballs carry a real SHA.
14
14
  */
15
- var CDN_BUILD_SHA = "7563635673f460d885fa6976033d7b09590d9a49";
15
+ var CDN_BUILD_SHA = "2765b9b100c4d9385cfe67d138e18170b1fadf35";
16
16
  /**
17
17
  * Whether `sha` (default {@link CDN_BUILD_SHA}) is a stamped full git commit
18
18
  * SHA rather than the unstamped repo placeholder.
@@ -82,18 +82,23 @@ function _defineProperty(e, r, t) {
82
82
  * the bootstrap at this root resolves the current rollout at load time.
83
83
  */
84
84
  var DEFAULT_MESSAGING_CDN_BASE = "https://messaging-assets.ada.support/";
85
+ var FALLBACK_MESSAGING_CDN_BASE = "https://static.ada.support/messaging/";
85
86
  var SDK_BOOTSTRAP_FILENAME = "sdk.js";
86
87
  var PINNED_SDK_ENTRY_PATH = "sdk/index.js";
87
88
  var PINNED_BUILD_SHA_PATTERN = /^[0-9a-f]{40}$/;
88
89
  var UNSTAMPED_BUILD_SHA_PATTERN = /^0{40}$/;
89
90
  /** Typed failure raised by {@link loadMessagingSdk} and {@link loadAdaMessaging}. */
90
91
  var MessagingSdkLoadError = class extends Error {
91
- constructor(message, code, cause) {
92
+ constructor(message, code, cause, fallbackCause) {
92
93
  super(message);
93
94
  _defineProperty(this, "code", void 0);
94
95
  this.name = "MessagingSdkLoadError";
95
96
  this.code = code;
96
97
  if (cause !== void 0) this.cause = cause;
98
+ if (fallbackCause !== void 0) Object.defineProperty(this, "fallbackCause", {
99
+ value: fallbackCause,
100
+ enumerable: true
101
+ });
97
102
  }
98
103
  };
99
104
  var defaultImportModule = (url) => import(
@@ -101,7 +106,9 @@ var defaultImportModule = (url) => import(
101
106
  /* @vite-ignore */
102
107
  url
103
108
  );
104
- var inFlightByImporter = /* @__PURE__ */ new WeakMap();
109
+ var loadsByImporter = /* @__PURE__ */ new WeakMap();
110
+ var FALLBACK_WARNING_KEY = Symbol.for("ada.messaging.sdk.fallbackWarning");
111
+ var warningScope = globalThis;
105
112
  var LOOPBACK_HOSTS = new Set([
106
113
  "localhost",
107
114
  "127.0.0.1",
@@ -162,12 +169,24 @@ async function importSdkModule(url, importModule) {
162
169
  if (!isMessagingSdkModule(loaded)) throw new MessagingSdkLoadError(`The module at ${url} does not expose the Ada Messaging SDK interface.`, "sdk_module_invalid");
163
170
  return loaded;
164
171
  }
172
+ function memoizeLoad(cache, url, load) {
173
+ const existing = cache.get(url);
174
+ if (existing) return existing;
175
+ const pending = load();
176
+ cache.set(url, pending);
177
+ pending.catch(() => {
178
+ if (cache.get(url) === pending) cache.delete(url);
179
+ });
180
+ return pending;
181
+ }
165
182
  /**
166
183
  * Load the Ada Messaging SDK module from Ada's CDN.
167
184
  *
168
185
  * The returned promise is memoized per resolved URL: concurrent and repeated
169
186
  * calls share one in-flight import. A failed load clears the memo so a later
170
- * call retries. Rejections are always {@link MessagingSdkLoadError}.
187
+ * call retries. Without `cdnBase`, an import failure at the default root is
188
+ * retried once from {@link FALLBACK_MESSAGING_CDN_BASE}. Rejections are always
189
+ * {@link MessagingSdkLoadError}.
171
190
  *
172
191
  * @example
173
192
  * const { createAdaEmbedInterface } = await loadMessagingSdk();
@@ -175,30 +194,49 @@ async function importSdkModule(url, importModule) {
175
194
  function loadMessagingSdk(options = {}) {
176
195
  const importModule = options.importModule ?? defaultImportModule;
177
196
  let url;
197
+ let fallbackUrl;
178
198
  try {
179
199
  url = resolveSdkBootstrapUrl(options.cdnBase, options.pinBuildSha);
200
+ if (options.cdnBase === void 0) fallbackUrl = resolveSdkBootstrapUrl(FALLBACK_MESSAGING_CDN_BASE, options.pinBuildSha);
180
201
  } catch (error) {
181
202
  return Promise.reject(error);
182
203
  }
183
- let inFlight = inFlightByImporter.get(importModule);
184
- if (!inFlight) {
185
- inFlight = /* @__PURE__ */ new Map();
186
- inFlightByImporter.set(importModule, inFlight);
187
- }
188
- const existing = inFlight.get(url);
189
- if (existing) return existing;
190
- const cache = inFlight;
191
- const pending = importSdkModule(url, importModule);
192
- cache.set(url, pending);
193
- pending.catch(() => {
194
- if (cache.get(url) === pending) cache.delete(url);
195
- });
196
- return pending;
204
+ const state = loadsByImporter.get(importModule) ?? {
205
+ imports: /* @__PURE__ */ new Map(),
206
+ defaultLoads: /* @__PURE__ */ new Map()
207
+ };
208
+ loadsByImporter.set(importModule, state);
209
+ const load = (entryUrl) => memoizeLoad(state.imports, entryUrl, () => importSdkModule(entryUrl, importModule));
210
+ if (fallbackUrl === void 0) return load(url);
211
+ const retryUrl = fallbackUrl;
212
+ return memoizeLoad(state.defaultLoads, url, () => load(url).catch(async (error) => {
213
+ if (!(error instanceof MessagingSdkLoadError) || error.code !== "sdk_import_failed") throw error;
214
+ let module;
215
+ try {
216
+ module = await load(retryUrl);
217
+ } catch (cause) {
218
+ if (!(cause instanceof MessagingSdkLoadError)) throw cause;
219
+ throw new MessagingSdkLoadError(cause.code === "sdk_import_failed" ? `The Ada Messaging SDK failed to load from both ${url} and ${retryUrl}.` : cause.message, cause.code, error, cause);
220
+ }
221
+ if (!warningScope[FALLBACK_WARNING_KEY]) {
222
+ warningScope[FALLBACK_WARNING_KEY] = true;
223
+ const cause = error.cause;
224
+ warnHost(cause instanceof TypeError ? `Loaded the Messaging SDK from ${FALLBACK_MESSAGING_CDN_BASE} because the default root ${DEFAULT_MESSAGING_CDN_BASE} was blocked or unavailable. Add https://messaging-assets.ada.support to script-src, connect-src and frame-src, or pass cdnBase: "${FALLBACK_MESSAGING_CDN_BASE}".` : `Loaded the Messaging SDK from ${FALLBACK_MESSAGING_CDN_BASE} because the module at ${url} failed to evaluate (${describeRejection(cause)}). This is an Ada-side problem, not your host's CSP. Report it to Ada.`, cause);
225
+ }
226
+ return module;
227
+ }));
197
228
  }
198
229
  var startedInterfaceByImporter = /* @__PURE__ */ new WeakMap();
199
- function warnHost(message) {
230
+ function describeRejection(cause) {
231
+ try {
232
+ return cause instanceof Error ? `${cause.name}: ${cause.message}` : String(cause);
233
+ } catch {
234
+ return "unknown error";
235
+ }
236
+ }
237
+ function warnHost(message, cause) {
200
238
  try {
201
- console.warn(`[Ada] ${message}`);
239
+ console.warn(`[Ada] ${message}`, ...cause === void 0 ? [] : [cause]);
202
240
  } catch {}
203
241
  }
204
242
  function isPlainObject(value) {
@@ -273,6 +311,6 @@ function loadAdaMessaging(settings, options = {}) {
273
311
  return memo.promise;
274
312
  }
275
313
  //#endregion
276
- export { CDN_BUILD_SHA, DEFAULT_MESSAGING_CDN_BASE, MessagingSdkLoadError, isCdnBuildShaStamped, loadAdaMessaging, loadMessagingSdk };
314
+ export { CDN_BUILD_SHA, DEFAULT_MESSAGING_CDN_BASE, FALLBACK_MESSAGING_CDN_BASE, MessagingSdkLoadError, isCdnBuildShaStamped, loadAdaMessaging, loadMessagingSdk };
277
315
 
278
316
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/npm/build-info.ts","../../src/client/embed-lifecycle.ts","../../src/npm/loader.ts"],"sourcesContent":["// The repo copy carries the 40-zero placeholder; the publish workflow\n// (.github/workflows/messaging-publish-web-packages.yml) stamps the real\n// commit SHA into the built output via scripts/stamp-cdn-build-sha.mjs and\n// verifies the packed tarball before `npm publish`. Keep the placeholder as\n// a single 40-zero string literal: the stamp is a same-length text\n// replacement, so source maps stay valid.\nconst GIT_SHA_PATTERN = /^[0-9a-f]{40}$/;\nconst UNSTAMPED_SHA_PATTERN = /^0{40}$/;\n\n/**\n * Git commit SHA of the monorepo commit this npm version was published from.\n * The CDN pipeline deploys each main commit's runtime under an immutable\n * SHA root, so this value names the CDN build associated with this npm\n * version. Pass it as the `pinBuildSha` loader option to load exactly that\n * runtime build — not recommended for production (see the README).\n *\n * In the repository, and in any locally built copy, the value is the\n * unstamped 40-zero placeholder ({@link isCdnBuildShaStamped} returns\n * `false`); only published tarballs carry a real SHA.\n */\nexport const CDN_BUILD_SHA: string = \"7563635673f460d885fa6976033d7b09590d9a49\";\n\n/**\n * Whether `sha` (default {@link CDN_BUILD_SHA}) is a stamped full git commit\n * SHA rather than the unstamped repo placeholder.\n */\nexport function isCdnBuildShaStamped(sha: string = CDN_BUILD_SHA): boolean {\n\tconst normalized = sha.trim().toLowerCase();\n\treturn (\n\t\tGIT_SHA_PATTERN.test(normalized) && !UNSTAMPED_SHA_PATTERN.test(normalized)\n\t);\n}\n","/**\n * Lifecycle channel between `createAdaEmbedInterface` and the npm loader's\n * memo: a non-enumerable getter over closure state, so the loader never\n * mutates the public surface and `Object.freeze` on the facade still works.\n * `Symbol.for` because the loader and the CDN runtime are separate builds;\n * a runtime that predates the getter yields `undefined` — degrade gracefully.\n */\nexport const EMBED_LIFECYCLE_STOPPED = Symbol.for(\n\t\"ada-cx/messaging-sdk/embed-stopped\",\n);\n\n/** Read the facade's stopped flag; `undefined` when the runtime predates it. */\nexport function readEmbedStoppedFlag(ada: object): boolean | undefined {\n\tconst value = (ada as Record<symbol, unknown>)[EMBED_LIFECYCLE_STOPPED];\n\treturn typeof value === \"boolean\" ? value : undefined;\n}\n\n/** Define the getter at facade creation time, before any host freeze. */\nexport function defineEmbedStoppedFlag(\n\tada: object,\n\treadStopped: () => boolean,\n): void {\n\tObject.defineProperty(ada, EMBED_LIFECYCLE_STOPPED, {\n\t\tget: readStopped,\n\t\tenumerable: false,\n\t\tconfigurable: false,\n\t});\n}\n","import type { AdaMessagingClient } from \"../client/client\";\nimport type { AdaMessagingStartOptions } from \"../client/client-types\";\nimport type {\n\tAdaEmbedInterface,\n\tcreateAdaEmbedInterface,\n\tdispatchEmbedLoaderInitialActionQueue,\n\tdispatchEmbedLoaderInitialActionQueueForAtomicHandoff,\n} from \"../client/embed-interface\";\nimport { readEmbedStoppedFlag } from \"../client/embed-lifecycle\";\nimport type {\n\tmountAdaWebViewRuntime,\n\tresolveAdaWebViewRuntimeAssets,\n} from \"../mobile-webview-runtime\";\n\n/**\n * Production CDN root the loader resolves the SDK bootstrap from when no\n * `cdnBase` override is given. The npm package never pins a runtime version;\n * the bootstrap at this root resolves the current rollout at load time.\n */\nexport const DEFAULT_MESSAGING_CDN_BASE =\n\t\"https://messaging-assets.ada.support/\";\n\nconst SDK_BOOTSTRAP_FILENAME = \"sdk.js\";\n\n// The CDN pipeline deploys each main commit's runtime as an immutable\n// SHA-rooted entry (`<cdnBase>/<sha>/sdk/index.js`); the mutable `sdk.js`\n// bootstrap resolves the current rollout to one of those roots at load time.\n// A pin bypasses the bootstrap and imports one root directly.\nconst PINNED_SDK_ENTRY_PATH = \"sdk/index.js\";\n\n// Strict on purpose: the pin is interpolated into a CDN path, so only a full\n// lowercase 40-hex git SHA may pass (mirrors scripts/sdk.js's\n// VERSION_OVERRIDE_PATTERN security boundary, minus the short-SHA and pr-N\n// forms — the npm surface pins exactly what CDN_BUILD_SHA carries).\nconst PINNED_BUILD_SHA_PATTERN = /^[0-9a-f]{40}$/;\nconst UNSTAMPED_BUILD_SHA_PATTERN = /^0{40}$/;\n\n/** Why a {@link MessagingSdkLoadError} was raised. */\nexport type MessagingSdkLoadErrorCode =\n\t/**\n\t * The `cdnBase` option is not a valid `https:` URL (plain `http:` is\n\t * allowed only for loopback hosts).\n\t */\n\t| \"invalid_cdn_base\"\n\t/** The `pinBuildSha` option is not a full 40-character hex git SHA. */\n\t| \"invalid_build_sha\"\n\t/**\n\t * The `pinBuildSha` option is the unstamped 40-zero placeholder: this\n\t * copy of the package was built from the repository, not published, so\n\t * its `CDN_BUILD_SHA` names no CDN build.\n\t */\n\t| \"unstamped_build_sha\"\n\t/** The dynamic import of the CDN bootstrap failed (network, CSP, 404). */\n\t| \"sdk_import_failed\"\n\t/** The imported module does not expose the Ada Messaging SDK surface. */\n\t| \"sdk_module_invalid\";\n\n/** Typed failure raised by {@link loadMessagingSdk} and {@link loadAdaMessaging}. */\nexport class MessagingSdkLoadError extends Error {\n\treadonly code: MessagingSdkLoadErrorCode;\n\n\tconstructor(\n\t\tmessage: string,\n\t\tcode: MessagingSdkLoadErrorCode,\n\t\tcause?: unknown,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"MessagingSdkLoadError\";\n\t\tthis.code = code;\n\t\tif (cause !== undefined) {\n\t\t\tthis.cause = cause;\n\t\t}\n\t}\n}\n\n/**\n * The programmatic messaging interface {@link loadAdaMessaging} resolves. An\n * alias of the runtime's `AdaEmbedInterface`, which keeps that name because it\n * is also the legacy `window.adaEmbed` compat facade.\n */\nexport type AdaMessagingInterface = AdaEmbedInterface;\n\n/**\n * The public surface of the CDN-resolved SDK module, as loaded from\n * `<cdnBase>/sdk.js`. Types only — the implementation always comes from the\n * CDN at load time and is never part of this npm package.\n */\nexport interface MessagingSdkModule {\n\tAdaMessagingClient: typeof AdaMessagingClient;\n\tcreateAdaEmbedInterface: typeof createAdaEmbedInterface;\n\tdispatchEmbedLoaderInitialActionQueue: typeof dispatchEmbedLoaderInitialActionQueue;\n\tdispatchEmbedLoaderInitialActionQueueForAtomicHandoff: typeof dispatchEmbedLoaderInitialActionQueueForAtomicHandoff;\n\tmountAdaWebViewRuntime: typeof mountAdaWebViewRuntime;\n\tresolveAdaWebViewRuntimeAssets: typeof resolveAdaWebViewRuntimeAssets;\n}\n\ntype ImportSdkModule = (url: string) => Promise<unknown>;\n\nexport interface LoadMessagingSdkOptions {\n\t/**\n\t * CDN root to resolve `sdk.js` from. Must be an `https:` URL; plain\n\t * `http:` is accepted only for loopback hosts (`localhost`, `127.0.0.1`,\n\t * `[::1]`, `*.localhost`) during local development. Defaults to the\n\t * production root ({@link DEFAULT_MESSAGING_CDN_BASE}). Override it with\n\t * the Ada-provided asset host for a staging validation window only;\n\t * production pages must keep the default.\n\t */\n\tcdnBase?: string;\n\t/**\n\t * Full 40-character git commit SHA of a deployed CDN build. When set, the\n\t * loader skips the rollout bootstrap and imports that build's immutable\n\t * entry (`<cdnBase>/<sha>/sdk/index.js`) directly. Pass the package's\n\t * `CDN_BUILD_SHA` export to pin the build associated with this npm\n\t * version. NOT recommended for production: a pinned runtime misses Ada's\n\t * fixes and rollouts, and may predate server contract changes. Composes\n\t * with `cdnBase` for staged validation.\n\t */\n\tpinBuildSha?: string;\n\t/**\n\t * Import seam for unit tests. Defaults to a native dynamic `import()` of\n\t * the resolved bootstrap URL.\n\t */\n\timportModule?: ImportSdkModule;\n}\n\n// Both annotations are load-bearing: bundlers rewrite bare dynamic imports,\n// and this specifier must reach the browser untouched so the runtime always\n// resolves from Ada's CDN. The npm build for this entry is unminified so the\n// annotations survive into the published output.\nconst defaultImportModule: ImportSdkModule = (url) =>\n\timport(/* webpackIgnore: true */ /* @vite-ignore */ url);\n\n// Keyed by import seam so production memoizes on the module-level default\n// while each injected test seam gets an isolated cache.\nconst inFlightByImporter = new WeakMap<\n\tImportSdkModule,\n\tMap<string, Promise<MessagingSdkModule>>\n>();\n\n// Mirrors the loopback semantics of the shared `isLoopbackHost` /\n// `validateMessagingEndpoint` (shared/utils/src/url.ts) and the bridge\n// loader's copy (packages/bridge/src/npm/loader.ts). Inlined because the\n// published loader must stay dependency-free; keep the host set in sync.\nconst LOOPBACK_HOSTS = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\", \"::1\"]);\n\nfunction isLoopbackHostname(hostname: string): boolean {\n\tconst normalized = hostname.trim().toLowerCase();\n\t// `*.localhost` resolves to the loopback interface and is \"potentially\n\t// trustworthy\" per the Secure Contexts spec; no production host ends in\n\t// `.localhost`.\n\treturn LOOPBACK_HOSTS.has(normalized) || normalized.endsWith(\".localhost\");\n}\n\nfunction resolvePinnedBuildSha(pinBuildSha: string): string {\n\tconst sha = pinBuildSha.trim().toLowerCase();\n\tif (!PINNED_BUILD_SHA_PATTERN.test(sha)) {\n\t\tthrow new MessagingSdkLoadError(\n\t\t\t`The pinBuildSha option must be a full 40-character hex git SHA: \"${pinBuildSha}\".`,\n\t\t\t\"invalid_build_sha\",\n\t\t);\n\t}\n\tif (UNSTAMPED_BUILD_SHA_PATTERN.test(sha)) {\n\t\tthrow new MessagingSdkLoadError(\n\t\t\t\"The pinBuildSha option is the unstamped CDN_BUILD_SHA placeholder. Only the published npm package carries a stamped SHA; a repository or local build cannot pin a CDN build.\",\n\t\t\t\"unstamped_build_sha\",\n\t\t);\n\t}\n\treturn sha;\n}\n\n/**\n * The runtime this URL serves carries the SDK's security logic (endpoint\n * validation, session handling, the origin checks), so a cleartext transport\n * would let an on-path attacker replace it wholesale: `https:` is required,\n * with a loopback-only `http:` exception for local development.\n */\nfunction resolveSdkBootstrapUrl(\n\tcdnBase: string | undefined,\n\tpinBuildSha: string | undefined,\n): string {\n\tconst base = (cdnBase ?? DEFAULT_MESSAGING_CDN_BASE).trim();\n\t// Resolving against a base without a trailing slash would drop its last\n\t// path segment, so normalize before building the bootstrap URL.\n\tconst normalizedBase = base.endsWith(\"/\") ? base : `${base}/`;\n\tconst entryPath =\n\t\tpinBuildSha === undefined\n\t\t\t? SDK_BOOTSTRAP_FILENAME\n\t\t\t: `${resolvePinnedBuildSha(pinBuildSha)}/${PINNED_SDK_ENTRY_PATH}`;\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(entryPath, normalizedBase);\n\t} catch (cause) {\n\t\tthrow new MessagingSdkLoadError(\n\t\t\t`The cdnBase option is not a valid URL: \"${base}\".`,\n\t\t\t\"invalid_cdn_base\",\n\t\t\tcause,\n\t\t);\n\t}\n\tconst isHttps = url.protocol === \"https:\";\n\tconst isLoopbackHttp =\n\t\turl.protocol === \"http:\" && isLoopbackHostname(url.hostname);\n\tif (!isHttps && !isLoopbackHttp) {\n\t\tthrow new MessagingSdkLoadError(\n\t\t\t`The cdnBase option must use https (plain http is allowed only for loopback hosts): \"${base}\".`,\n\t\t\t\"invalid_cdn_base\",\n\t\t);\n\t}\n\treturn url.toString();\n}\n\n// A partial CDN module (mid-deploy, or a rolled-back build missing a newer\n// export) must fail here as a typed sdk_module_invalid error, not later as a\n// TypeError on the first missing call — so every export is checked. The\n// `satisfies` clause rejects names that are not interface members; the\n// exhaustiveness type below is what forces this list to grow with it.\nconst REQUIRED_SDK_EXPORTS = [\n\t\"AdaMessagingClient\",\n\t\"createAdaEmbedInterface\",\n\t\"dispatchEmbedLoaderInitialActionQueue\",\n\t\"dispatchEmbedLoaderInitialActionQueueForAtomicHandoff\",\n\t\"mountAdaWebViewRuntime\",\n\t\"resolveAdaWebViewRuntimeAssets\",\n] as const satisfies readonly (keyof MessagingSdkModule)[];\n\n// Compile-time exhaustiveness: adding a MessagingSdkModule member without\n// listing it in REQUIRED_SDK_EXPORTS turns this type into `never`, failing\n// the `true` assignment below.\ntype AllSdkExportsListed =\n\tExclude<\n\t\tkeyof MessagingSdkModule,\n\t\t(typeof REQUIRED_SDK_EXPORTS)[number]\n\t> extends never\n\t\t? true\n\t\t: never;\nconst _allSdkExportsListed: AllSdkExportsListed = true;\nvoid _allSdkExportsListed;\n\nfunction isMessagingSdkModule(value: unknown): value is MessagingSdkModule {\n\tif (typeof value !== \"object\" || value === null) {\n\t\treturn false;\n\t}\n\tconst candidate = value as Record<string, unknown>;\n\treturn REQUIRED_SDK_EXPORTS.every(\n\t\t(key) => typeof candidate[key] === \"function\",\n\t);\n}\n\nasync function importSdkModule(\n\turl: string,\n\timportModule: ImportSdkModule,\n): Promise<MessagingSdkModule> {\n\tlet loaded: unknown;\n\ttry {\n\t\tloaded = await importModule(url);\n\t} catch (cause) {\n\t\tthrow new MessagingSdkLoadError(\n\t\t\t`The Ada Messaging SDK failed to load from ${url}.`,\n\t\t\t\"sdk_import_failed\",\n\t\t\tcause,\n\t\t);\n\t}\n\tif (!isMessagingSdkModule(loaded)) {\n\t\tthrow new MessagingSdkLoadError(\n\t\t\t`The module at ${url} does not expose the Ada Messaging SDK interface.`,\n\t\t\t\"sdk_module_invalid\",\n\t\t);\n\t}\n\treturn loaded;\n}\n\n/**\n * Load the Ada Messaging SDK module from Ada's CDN.\n *\n * The returned promise is memoized per resolved URL: concurrent and repeated\n * calls share one in-flight import. A failed load clears the memo so a later\n * call retries. Rejections are always {@link MessagingSdkLoadError}.\n *\n * @example\n * const { createAdaEmbedInterface } = await loadMessagingSdk();\n */\nexport function loadMessagingSdk(\n\toptions: LoadMessagingSdkOptions = {},\n): Promise<MessagingSdkModule> {\n\tconst importModule = options.importModule ?? defaultImportModule;\n\tlet url: string;\n\ttry {\n\t\turl = resolveSdkBootstrapUrl(options.cdnBase, options.pinBuildSha);\n\t} catch (error) {\n\t\treturn Promise.reject(error);\n\t}\n\n\tlet inFlight = inFlightByImporter.get(importModule);\n\tif (!inFlight) {\n\t\tinFlight = new Map();\n\t\tinFlightByImporter.set(importModule, inFlight);\n\t}\n\tconst existing = inFlight.get(url);\n\tif (existing) {\n\t\treturn existing;\n\t}\n\n\tconst cache = inFlight;\n\tconst pending = importSdkModule(url, importModule);\n\tcache.set(url, pending);\n\tpending.catch(() => {\n\t\tif (cache.get(url) === pending) {\n\t\t\tcache.delete(url);\n\t\t}\n\t});\n\treturn pending;\n}\n\n// Keyed by import seam like the module memo above: production memoizes on\n// the module-level default while each injected test seam gets an isolated\n// cache. `ada` is set when the promise resolves, so the stopped-interface\n// diagnostic can consult the resolved facade without wrapping it.\ninterface StartedInterfaceMemo {\n\tpromise: Promise<AdaMessagingInterface>;\n\tsettings: AdaMessagingStartOptions;\n\tada?: AdaMessagingInterface;\n}\n\nconst startedInterfaceByImporter = new WeakMap<\n\tImportSdkModule,\n\tStartedInterfaceMemo\n>();\n\n// Ungated like the runtime logger's dropped-host-value channel: both call\n// sites fire only on host misuse, never on an ordinary page load.\nfunction warnHost(message: string): void {\n\ttry {\n\t\t// biome-ignore lint/suspicious/noConsole: the loader's sanctioned host-page diagnostic sink\n\t\tconsole.warn(`[Ada] ${message}`);\n\t} catch {\n\t\t// A host may replace console methods; diagnostics must not throw.\n\t}\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\tif (typeof value !== \"object\" || value === null) {\n\t\treturn false;\n\t}\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\n// Structural equality over the settings surface. Two functions compare equal:\n// fresh inline callbacks on a re-run (React Strict Mode effects) are not a\n// settings change worth a warning. Exotic objects compare by reference.\nfunction settingsEqual(a: unknown, b: unknown): boolean {\n\tif (Object.is(a, b)) {\n\t\treturn true;\n\t}\n\tif (typeof a === \"function\" && typeof b === \"function\") {\n\t\treturn true;\n\t}\n\tif (Array.isArray(a) && Array.isArray(b)) {\n\t\treturn (\n\t\t\ta.length === b.length &&\n\t\t\ta.every((item, index) => settingsEqual(item, b[index]))\n\t\t);\n\t}\n\tif (isPlainObject(a) && isPlainObject(b)) {\n\t\tconst aKeys = Object.keys(a);\n\t\tconst bKeys = new Set(Object.keys(b));\n\t\treturn (\n\t\t\taKeys.length === bKeys.size &&\n\t\t\taKeys.every((key) => bKeys.has(key) && settingsEqual(a[key], b[key]))\n\t\t);\n\t}\n\treturn false;\n}\n\n// Observes the facade's symbol-keyed lifecycle getter (embed-lifecycle.ts)\n// instead of wrapping stop/start, so the customer's interface is never\n// mutated; a pinned runtime that predates the getter yields no flag and the\n// stopped-interface diagnostic is skipped rather than guessed.\nfunction isInterfaceStopped(ada: AdaMessagingInterface): boolean {\n\treturn readEmbedStoppedFlag(ada) === true;\n}\n\nasync function startAdaMessaging(\n\tsettings: AdaMessagingStartOptions,\n\toptions: LoadMessagingSdkOptions,\n): Promise<AdaMessagingInterface> {\n\tconst sdkModule = await loadMessagingSdk(options);\n\tconst ada = sdkModule.createAdaEmbedInterface();\n\tawait ada.start(settings);\n\treturn ada;\n}\n\n/**\n * Load the SDK, create the messaging interface, and start the widget —\n * the npm-first equivalent of the script-tag + `window.adaSettings` setup.\n *\n * One widget per page: the returned promise is memoized, so repeated and\n * concurrent calls resolve to the same started interface and the first\n * call's settings win. A failed load or start clears the memo so a later\n * call retries. Manage the running widget through the returned interface:\n * `stop()` tears it down and a later `start(settings)` on the same interface\n * runs again. Calling {@link loadAdaMessaging} after `stop()` returns the\n * same stopped interface without restarting it. Both memo outcomes log a\n * console warning: ignored differing settings, and a resolved interface\n * whose widget was stopped.\n *\n * Never assigns the interface to `window` or any other global: the returned\n * reference is the only handle, so hold it in module scope. A reference in\n * module scope is reachable only by your own code, never by other scripts on\n * the page.\n *\n * @example\n * // module scope: your code keeps the only reference\n * const ada = await loadAdaMessaging({\n * handle: \"my-bot\",\n * enableProgrammaticControl: true,\n * });\n * await ada.sendMessage(\"Hello\");\n */\nexport function loadAdaMessaging(\n\tsettings: AdaMessagingStartOptions,\n\toptions: LoadMessagingSdkOptions = {},\n): Promise<AdaMessagingInterface> {\n\tconst importModule = options.importModule ?? defaultImportModule;\n\tconst existing = startedInterfaceByImporter.get(importModule);\n\tif (existing) {\n\t\tif (!settingsEqual(settings, existing.settings)) {\n\t\t\twarnHost(\n\t\t\t\t\"loadAdaMessaging() was already called: the new settings are ignored and the existing interface is returned. To apply new settings, call stop() then start(settings) on it.\",\n\t\t\t);\n\t\t}\n\t\tif (existing.ada && isInterfaceStopped(existing.ada)) {\n\t\t\twarnHost(\n\t\t\t\t\"loadAdaMessaging() resolved an interface whose widget was stopped and never restarts it. Call start(settings) on it to run the widget again.\",\n\t\t\t);\n\t\t}\n\t\treturn existing.promise;\n\t}\n\tconst memo: StartedInterfaceMemo = {\n\t\tpromise: startAdaMessaging(settings, options),\n\t\tsettings,\n\t};\n\tstartedInterfaceByImporter.set(importModule, memo);\n\tmemo.promise.then(\n\t\t(ada) => {\n\t\t\tmemo.ada = ada;\n\t\t},\n\t\t() => {\n\t\t\tif (startedInterfaceByImporter.get(importModule) === memo) {\n\t\t\t\tstartedInterfaceByImporter.delete(importModule);\n\t\t\t}\n\t\t},\n\t);\n\treturn memo.promise;\n}\n"],"mappings":";AAMA,IAAM,kBAAkB;AACxB,IAAM,wBAAwB;;;;;;;;;;;;AAa9B,IAAa,gBAAwB;;;;;AAMrC,SAAgB,qBAAqB,MAAc,eAAwB;CAC1E,MAAM,aAAa,IAAI,MAAM,CAAC,aAAa;AAC3C,QACC,gBAAgB,KAAK,WAAW,IAAI,CAAC,sBAAsB,KAAK,WAAW;;;;;;;;;;;ACtB7E,IAAa,0BAA0B,OAAO,IAC7C,qCACA;;AAGD,SAAgB,qBAAqB,KAAkC;CACtE,MAAM,QAAS,IAAgC;AAC/C,QAAO,OAAO,UAAU,YAAY,QAAQ,KAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACK7C,IAAa,6BACZ;AAED,IAAM,yBAAyB;AAM/B,IAAM,wBAAwB;AAM9B,IAAM,2BAA2B;AACjC,IAAM,8BAA8B;;AAuBpC,IAAa,wBAAb,cAA2C,MAAM;CAGhD,YACC,SACA,MACA,OACC;AACD,QAAM,QAAQ;wBAPf,QAAA,KAAA,EAAS;AAQR,OAAK,OAAO;AACZ,OAAK,OAAO;AACZ,MAAI,UAAU,KAAA,EACb,MAAK,QAAQ;;;AA2DhB,IAAM,uBAAwC,QAC7C;;;CAAoD;;AAIrD,IAAM,qCAAqB,IAAI,SAG5B;AAMH,IAAM,iBAAiB,IAAI,IAAI;CAAC;CAAa;CAAa;CAAS;CAAM,CAAC;AAE1E,SAAS,mBAAmB,UAA2B;CACtD,MAAM,aAAa,SAAS,MAAM,CAAC,aAAa;AAIh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OAAO,KAAK,EAAE;EAC5B,MAAM,QAAQ,IAAI,IAAI,OAAO,KAAK,EAAE,CAAC;AACrC,SACC,MAAM,WAAW,MAAM,QACvB,MAAM,OAAO,QAAQ,MAAM,IAAI,IAAI,IAAI,cAAc,EAAE,MAAM,EAAE,KAAK,CAAC;;AAGvE,QAAO;;AAOR,SAAS,mBAAmB,KAAqC;AAChE,QAAO,qBAAqB,IAAI,KAAK;;AAGtC,eAAe,kBACd,UACA,SACiC;CAEjC,MAAM,OADY,MAAM,iBAAiB,QAAQ,EAC3B,yBAAyB;AAC/C,OAAM,IAAI,MAAM,SAAS;AACzB,QAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BR,SAAgB,iBACf,UACA,UAAmC,EAAE,EACJ;CACjC,MAAM,eAAe,QAAQ,gBAAgB;CAC7C,MAAM,WAAW,2BAA2B,IAAI,aAAa;AAC7D,KAAI,UAAU;AACb,MAAI,CAAC,cAAc,UAAU,SAAS,SAAS,CAC9C,UACC,6KACA;AAEF,MAAI,SAAS,OAAO,mBAAmB,SAAS,IAAI,CACnD,UACC,+IACA;AAEF,SAAO,SAAS;;CAEjB,MAAM,OAA6B;EAClC,SAAS,kBAAkB,UAAU,QAAQ;EAC7C;EACA;AACD,4BAA2B,IAAI,cAAc,KAAK;AAClD,MAAK,QAAQ,MACX,QAAQ;AACR,OAAK,MAAM;UAEN;AACL,MAAI,2BAA2B,IAAI,aAAa,KAAK,KACpD,4BAA2B,OAAO,aAAa;GAGjD;AACD,QAAO,KAAK"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/npm/build-info.ts","../../src/client/embed-lifecycle.ts","../../src/npm/loader.ts"],"sourcesContent":["// The repo copy carries the 40-zero placeholder; the publish workflow\n// (.github/workflows/messaging-publish-web-packages.yml) stamps the real\n// commit SHA into the built output via scripts/stamp-cdn-build-sha.mjs and\n// verifies the packed tarball before `npm publish`. Keep the placeholder as\n// a single 40-zero string literal: the stamp is a same-length text\n// replacement, so source maps stay valid.\nconst GIT_SHA_PATTERN = /^[0-9a-f]{40}$/;\nconst UNSTAMPED_SHA_PATTERN = /^0{40}$/;\n\n/**\n * Git commit SHA of the monorepo commit this npm version was published from.\n * The CDN pipeline deploys each main commit's runtime under an immutable\n * SHA root, so this value names the CDN build associated with this npm\n * version. Pass it as the `pinBuildSha` loader option to load exactly that\n * runtime build — not recommended for production (see the README).\n *\n * In the repository, and in any locally built copy, the value is the\n * unstamped 40-zero placeholder ({@link isCdnBuildShaStamped} returns\n * `false`); only published tarballs carry a real SHA.\n */\nexport const CDN_BUILD_SHA: string = \"2765b9b100c4d9385cfe67d138e18170b1fadf35\";\n\n/**\n * Whether `sha` (default {@link CDN_BUILD_SHA}) is a stamped full git commit\n * SHA rather than the unstamped repo placeholder.\n */\nexport function isCdnBuildShaStamped(sha: string = CDN_BUILD_SHA): boolean {\n\tconst normalized = sha.trim().toLowerCase();\n\treturn (\n\t\tGIT_SHA_PATTERN.test(normalized) && !UNSTAMPED_SHA_PATTERN.test(normalized)\n\t);\n}\n","/**\n * Lifecycle channel between `createAdaEmbedInterface` and the npm loader's\n * memo: a non-enumerable getter over closure state, so the loader never\n * mutates the public surface and `Object.freeze` on the facade still works.\n * `Symbol.for` because the loader and the CDN runtime are separate builds;\n * a runtime that predates the getter yields `undefined` — degrade gracefully.\n */\nexport const EMBED_LIFECYCLE_STOPPED = Symbol.for(\n\t\"ada-cx/messaging-sdk/embed-stopped\",\n);\n\n/** Read the facade's stopped flag; `undefined` when the runtime predates it. */\nexport function readEmbedStoppedFlag(ada: object): boolean | undefined {\n\tconst value = (ada as Record<symbol, unknown>)[EMBED_LIFECYCLE_STOPPED];\n\treturn typeof value === \"boolean\" ? value : undefined;\n}\n\n/** Define the getter at facade creation time, before any host freeze. */\nexport function defineEmbedStoppedFlag(\n\tada: object,\n\treadStopped: () => boolean,\n): void {\n\tObject.defineProperty(ada, EMBED_LIFECYCLE_STOPPED, {\n\t\tget: readStopped,\n\t\tenumerable: false,\n\t\tconfigurable: false,\n\t});\n}\n","import type { AdaMessagingClient } from \"../client/client\";\nimport type { AdaMessagingStartOptions } from \"../client/client-types\";\nimport type {\n\tAdaEmbedInterface,\n\tcreateAdaEmbedInterface,\n\tdispatchEmbedLoaderInitialActionQueue,\n\tdispatchEmbedLoaderInitialActionQueueForAtomicHandoff,\n} from \"../client/embed-interface\";\nimport { readEmbedStoppedFlag } from \"../client/embed-lifecycle\";\nimport type {\n\tmountAdaWebViewRuntime,\n\tresolveAdaWebViewRuntimeAssets,\n} from \"../mobile-webview-runtime\";\n\n/**\n * Production CDN root the loader resolves the SDK bootstrap from when no\n * `cdnBase` override is given. The npm package never pins a runtime version;\n * the bootstrap at this root resolves the current rollout at load time.\n */\nexport const DEFAULT_MESSAGING_CDN_BASE =\n\t\"https://messaging-assets.ada.support/\";\n\nexport const FALLBACK_MESSAGING_CDN_BASE =\n\t\"https://static.ada.support/messaging/\";\n\nconst SDK_BOOTSTRAP_FILENAME = \"sdk.js\";\n\n// The CDN pipeline deploys each main commit's runtime as an immutable\n// SHA-rooted entry (`<cdnBase>/<sha>/sdk/index.js`); the mutable `sdk.js`\n// bootstrap resolves the current rollout to one of those roots at load time.\n// A pin bypasses the bootstrap and imports one root directly.\nconst PINNED_SDK_ENTRY_PATH = \"sdk/index.js\";\n\n// Strict on purpose: the pin is interpolated into a CDN path, so only a full\n// lowercase 40-hex git SHA may pass (mirrors scripts/sdk.js's\n// VERSION_OVERRIDE_PATTERN security boundary, minus the short-SHA and pr-N\n// forms — the npm surface pins exactly what CDN_BUILD_SHA carries).\nconst PINNED_BUILD_SHA_PATTERN = /^[0-9a-f]{40}$/;\nconst UNSTAMPED_BUILD_SHA_PATTERN = /^0{40}$/;\n\n/** Why a {@link MessagingSdkLoadError} was raised. */\nexport type MessagingSdkLoadErrorCode =\n\t/**\n\t * The `cdnBase` option is not a valid `https:` URL (plain `http:` is\n\t * allowed only for loopback hosts).\n\t */\n\t| \"invalid_cdn_base\"\n\t/** The `pinBuildSha` option is not a full 40-character hex git SHA. */\n\t| \"invalid_build_sha\"\n\t/**\n\t * The `pinBuildSha` option is the unstamped 40-zero placeholder: this\n\t * copy of the package was built from the repository, not published, so\n\t * its `CDN_BUILD_SHA` names no CDN build.\n\t */\n\t| \"unstamped_build_sha\"\n\t/** The dynamic import of the CDN bootstrap failed (fetch or evaluation). */\n\t| \"sdk_import_failed\"\n\t/** The imported module does not expose the Ada Messaging SDK surface. */\n\t| \"sdk_module_invalid\";\n\n/** Typed failure raised by {@link loadMessagingSdk} and {@link loadAdaMessaging}. */\nexport class MessagingSdkLoadError extends Error {\n\treadonly code: MessagingSdkLoadErrorCode;\n\tdeclare readonly fallbackCause?: MessagingSdkLoadError;\n\n\tconstructor(\n\t\tmessage: string,\n\t\tcode: MessagingSdkLoadErrorCode,\n\t\tcause?: unknown,\n\t\tfallbackCause?: MessagingSdkLoadError,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"MessagingSdkLoadError\";\n\t\tthis.code = code;\n\t\tif (cause !== undefined) {\n\t\t\tthis.cause = cause;\n\t\t}\n\t\tif (fallbackCause !== undefined) {\n\t\t\tObject.defineProperty(this, \"fallbackCause\", {\n\t\t\t\tvalue: fallbackCause,\n\t\t\t\tenumerable: true,\n\t\t\t});\n\t\t}\n\t}\n}\n\n/**\n * The programmatic messaging interface {@link loadAdaMessaging} resolves. An\n * alias of the runtime's `AdaEmbedInterface`, which keeps that name because it\n * is also the legacy `window.adaEmbed` compat facade.\n */\nexport type AdaMessagingInterface = AdaEmbedInterface;\n\n/**\n * The public surface of the CDN-resolved SDK module, as loaded from\n * `<cdnBase>/sdk.js`. Types only — the implementation always comes from the\n * CDN at load time and is never part of this npm package.\n */\nexport interface MessagingSdkModule {\n\tAdaMessagingClient: typeof AdaMessagingClient;\n\tcreateAdaEmbedInterface: typeof createAdaEmbedInterface;\n\tdispatchEmbedLoaderInitialActionQueue: typeof dispatchEmbedLoaderInitialActionQueue;\n\tdispatchEmbedLoaderInitialActionQueueForAtomicHandoff: typeof dispatchEmbedLoaderInitialActionQueueForAtomicHandoff;\n\tmountAdaWebViewRuntime: typeof mountAdaWebViewRuntime;\n\tresolveAdaWebViewRuntimeAssets: typeof resolveAdaWebViewRuntimeAssets;\n}\n\ntype ImportSdkModule = (url: string) => Promise<unknown>;\n\nexport interface LoadMessagingSdkOptions {\n\t/**\n\t * CDN root to resolve `sdk.js` from. Must be an `https:` URL; plain\n\t * `http:` is accepted only for loopback hosts (`localhost`, `127.0.0.1`,\n\t * `[::1]`, `*.localhost`) during local development. Defaults to the\n\t * production root ({@link DEFAULT_MESSAGING_CDN_BASE}). An explicit value,\n\t * including {@link FALLBACK_MESSAGING_CDN_BASE}, disables the automatic\n\t * static-root fallback.\n\t */\n\tcdnBase?: string;\n\t/**\n\t * Full 40-character git commit SHA of a deployed CDN build. When set, the\n\t * loader skips the rollout bootstrap and imports that build's immutable\n\t * entry (`<cdnBase>/<sha>/sdk/index.js`) directly. Pass the package's\n\t * `CDN_BUILD_SHA` export to pin the build associated with this npm\n\t * version. NOT recommended for production: a pinned runtime misses Ada's\n\t * fixes and rollouts, and may predate server contract changes. Composes\n\t * with `cdnBase` for staged validation.\n\t */\n\tpinBuildSha?: string;\n\t/**\n\t * Import seam for unit tests. Defaults to a native dynamic `import()` of\n\t * the resolved bootstrap URL.\n\t */\n\timportModule?: ImportSdkModule;\n}\n\n// Both annotations are load-bearing: bundlers rewrite bare dynamic imports,\n// and this specifier must reach the browser untouched so the runtime always\n// resolves from Ada's CDN. The npm build for this entry is unminified so the\n// annotations survive into the published output.\nconst defaultImportModule: ImportSdkModule = (url) =>\n\timport(/* webpackIgnore: true */ /* @vite-ignore */ url);\n\n// Keyed by import seam so production memoizes on the module-level default\n// while each injected test seam gets an isolated cache.\ninterface SdkLoaderState {\n\timports: Map<string, Promise<MessagingSdkModule>>;\n\tdefaultLoads: Map<string, Promise<MessagingSdkModule>>;\n}\n\nconst loadsByImporter = new WeakMap<ImportSdkModule, SdkLoaderState>();\n\n// Share the warning across independently bundled copies of this loader.\nconst FALLBACK_WARNING_KEY = Symbol.for(\"ada.messaging.sdk.fallbackWarning\");\nconst warningScope = globalThis as typeof globalThis & {\n\t[FALLBACK_WARNING_KEY]?: boolean;\n};\n\n// Mirrors the loopback semantics of the shared `isLoopbackHost` /\n// `validateMessagingEndpoint` (shared/utils/src/url.ts) and the bridge\n// loader's copy (packages/bridge/src/npm/loader.ts). Inlined because the\n// published loader must stay dependency-free; keep the host set in sync.\nconst LOOPBACK_HOSTS = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\", \"::1\"]);\n\nfunction isLoopbackHostname(hostname: string): boolean {\n\tconst normalized = hostname.trim().toLowerCase();\n\t// `*.localhost` resolves to the loopback interface and is \"potentially\n\t// trustworthy\" per the Secure Contexts spec; no production host ends in\n\t// `.localhost`.\n\treturn LOOPBACK_HOSTS.has(normalized) || normalized.endsWith(\".localhost\");\n}\n\nfunction resolvePinnedBuildSha(pinBuildSha: string): string {\n\tconst sha = pinBuildSha.trim().toLowerCase();\n\tif (!PINNED_BUILD_SHA_PATTERN.test(sha)) {\n\t\tthrow new MessagingSdkLoadError(\n\t\t\t`The pinBuildSha option must be a full 40-character hex git SHA: \"${pinBuildSha}\".`,\n\t\t\t\"invalid_build_sha\",\n\t\t);\n\t}\n\tif (UNSTAMPED_BUILD_SHA_PATTERN.test(sha)) {\n\t\tthrow new MessagingSdkLoadError(\n\t\t\t\"The pinBuildSha option is the unstamped CDN_BUILD_SHA placeholder. Only the published npm package carries a stamped SHA; a repository or local build cannot pin a CDN build.\",\n\t\t\t\"unstamped_build_sha\",\n\t\t);\n\t}\n\treturn sha;\n}\n\n/**\n * The runtime this URL serves carries the SDK's security logic (endpoint\n * validation, session handling, the origin checks), so a cleartext transport\n * would let an on-path attacker replace it wholesale: `https:` is required,\n * with a loopback-only `http:` exception for local development.\n */\nfunction resolveSdkBootstrapUrl(\n\tcdnBase: string | undefined,\n\tpinBuildSha: string | undefined,\n): string {\n\tconst base = (cdnBase ?? DEFAULT_MESSAGING_CDN_BASE).trim();\n\t// Resolving against a base without a trailing slash would drop its last\n\t// path segment, so normalize before building the bootstrap URL.\n\tconst normalizedBase = base.endsWith(\"/\") ? base : `${base}/`;\n\tconst entryPath =\n\t\tpinBuildSha === undefined\n\t\t\t? SDK_BOOTSTRAP_FILENAME\n\t\t\t: `${resolvePinnedBuildSha(pinBuildSha)}/${PINNED_SDK_ENTRY_PATH}`;\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(entryPath, normalizedBase);\n\t} catch (cause) {\n\t\tthrow new MessagingSdkLoadError(\n\t\t\t`The cdnBase option is not a valid URL: \"${base}\".`,\n\t\t\t\"invalid_cdn_base\",\n\t\t\tcause,\n\t\t);\n\t}\n\tconst isHttps = url.protocol === \"https:\";\n\tconst isLoopbackHttp =\n\t\turl.protocol === \"http:\" && isLoopbackHostname(url.hostname);\n\tif (!isHttps && !isLoopbackHttp) {\n\t\tthrow new MessagingSdkLoadError(\n\t\t\t`The cdnBase option must use https (plain http is allowed only for loopback hosts): \"${base}\".`,\n\t\t\t\"invalid_cdn_base\",\n\t\t);\n\t}\n\treturn url.toString();\n}\n\n// A partial CDN module (mid-deploy, or a rolled-back build missing a newer\n// export) must fail here as a typed sdk_module_invalid error, not later as a\n// TypeError on the first missing call — so every export is checked. The\n// `satisfies` clause rejects names that are not interface members; the\n// exhaustiveness type below is what forces this list to grow with it.\nconst REQUIRED_SDK_EXPORTS = [\n\t\"AdaMessagingClient\",\n\t\"createAdaEmbedInterface\",\n\t\"dispatchEmbedLoaderInitialActionQueue\",\n\t\"dispatchEmbedLoaderInitialActionQueueForAtomicHandoff\",\n\t\"mountAdaWebViewRuntime\",\n\t\"resolveAdaWebViewRuntimeAssets\",\n] as const satisfies readonly (keyof MessagingSdkModule)[];\n\n// Compile-time exhaustiveness: adding a MessagingSdkModule member without\n// listing it in REQUIRED_SDK_EXPORTS turns this type into `never`, failing\n// the `true` assignment below.\ntype AllSdkExportsListed =\n\tExclude<\n\t\tkeyof MessagingSdkModule,\n\t\t(typeof REQUIRED_SDK_EXPORTS)[number]\n\t> extends never\n\t\t? true\n\t\t: never;\nconst _allSdkExportsListed: AllSdkExportsListed = true;\nvoid _allSdkExportsListed;\n\nfunction isMessagingSdkModule(value: unknown): value is MessagingSdkModule {\n\tif (typeof value !== \"object\" || value === null) {\n\t\treturn false;\n\t}\n\tconst candidate = value as Record<string, unknown>;\n\treturn REQUIRED_SDK_EXPORTS.every(\n\t\t(key) => typeof candidate[key] === \"function\",\n\t);\n}\n\nasync function importSdkModule(\n\turl: string,\n\timportModule: ImportSdkModule,\n): Promise<MessagingSdkModule> {\n\tlet loaded: unknown;\n\ttry {\n\t\tloaded = await importModule(url);\n\t} catch (cause) {\n\t\tthrow new MessagingSdkLoadError(\n\t\t\t`The Ada Messaging SDK failed to load from ${url}.`,\n\t\t\t\"sdk_import_failed\",\n\t\t\tcause,\n\t\t);\n\t}\n\tif (!isMessagingSdkModule(loaded)) {\n\t\tthrow new MessagingSdkLoadError(\n\t\t\t`The module at ${url} does not expose the Ada Messaging SDK interface.`,\n\t\t\t\"sdk_module_invalid\",\n\t\t);\n\t}\n\treturn loaded;\n}\n\nfunction memoizeLoad(\n\tcache: Map<string, Promise<MessagingSdkModule>>,\n\turl: string,\n\tload: () => Promise<MessagingSdkModule>,\n): Promise<MessagingSdkModule> {\n\tconst existing = cache.get(url);\n\tif (existing) {\n\t\treturn existing;\n\t}\n\tconst pending = load();\n\tcache.set(url, pending);\n\tpending.catch(() => {\n\t\tif (cache.get(url) === pending) {\n\t\t\tcache.delete(url);\n\t\t}\n\t});\n\treturn pending;\n}\n\n/**\n * Load the Ada Messaging SDK module from Ada's CDN.\n *\n * The returned promise is memoized per resolved URL: concurrent and repeated\n * calls share one in-flight import. A failed load clears the memo so a later\n * call retries. Without `cdnBase`, an import failure at the default root is\n * retried once from {@link FALLBACK_MESSAGING_CDN_BASE}. Rejections are always\n * {@link MessagingSdkLoadError}.\n *\n * @example\n * const { createAdaEmbedInterface } = await loadMessagingSdk();\n */\nexport function loadMessagingSdk(\n\toptions: LoadMessagingSdkOptions = {},\n): Promise<MessagingSdkModule> {\n\tconst importModule = options.importModule ?? defaultImportModule;\n\tlet url: string;\n\tlet fallbackUrl: string | undefined;\n\ttry {\n\t\turl = resolveSdkBootstrapUrl(options.cdnBase, options.pinBuildSha);\n\t\tif (options.cdnBase === undefined) {\n\t\t\tfallbackUrl = resolveSdkBootstrapUrl(\n\t\t\t\tFALLBACK_MESSAGING_CDN_BASE,\n\t\t\t\toptions.pinBuildSha,\n\t\t\t);\n\t\t}\n\t} catch (error) {\n\t\treturn Promise.reject(error);\n\t}\n\n\tconst state = loadsByImporter.get(importModule) ?? {\n\t\timports: new Map<string, Promise<MessagingSdkModule>>(),\n\t\tdefaultLoads: new Map<string, Promise<MessagingSdkModule>>(),\n\t};\n\tloadsByImporter.set(importModule, state);\n\tconst load = (entryUrl: string) =>\n\t\tmemoizeLoad(state.imports, entryUrl, () =>\n\t\t\timportSdkModule(entryUrl, importModule),\n\t\t);\n\tif (fallbackUrl === undefined) {\n\t\treturn load(url);\n\t}\n\n\tconst retryUrl = fallbackUrl;\n\t// Keep fallback outcomes separate so explicit-root callers share the import,\n\t// but never inherit another caller's permission to retry a different root.\n\treturn memoizeLoad(state.defaultLoads, url, () =>\n\t\tload(url).catch(async (error: unknown) => {\n\t\t\tif (\n\t\t\t\t!(error instanceof MessagingSdkLoadError) ||\n\t\t\t\terror.code !== \"sdk_import_failed\"\n\t\t\t) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\t// CSP rejects import() without a network request, so this retry adds no\n\t\t\t// user-visible delay; retrying a genuine network failure once is acceptable too.\n\t\t\tlet module: MessagingSdkModule;\n\t\t\ttry {\n\t\t\t\tmodule = await load(retryUrl);\n\t\t\t} catch (cause) {\n\t\t\t\tif (!(cause instanceof MessagingSdkLoadError)) {\n\t\t\t\t\tthrow cause;\n\t\t\t\t}\n\t\t\t\tthrow new MessagingSdkLoadError(\n\t\t\t\t\tcause.code === \"sdk_import_failed\"\n\t\t\t\t\t\t? `The Ada Messaging SDK failed to load from both ${url} and ${retryUrl}.`\n\t\t\t\t\t\t: cause.message,\n\t\t\t\t\tcause.code,\n\t\t\t\t\terror,\n\t\t\t\t\tcause,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!warningScope[FALLBACK_WARNING_KEY]) {\n\t\t\t\twarningScope[FALLBACK_WARNING_KEY] = true;\n\t\t\t\tconst cause = error.cause;\n\t\t\t\t// Browsers reject blocked, unreachable, or missing imports with TypeError.\n\t\t\t\t// An evaluation-time TypeError still looks like a fetch failure, as before;\n\t\t\t\t// this heuristic narrows diagnostic noise but cannot prove the cause.\n\t\t\t\twarnHost(\n\t\t\t\t\tcause instanceof TypeError\n\t\t\t\t\t\t? `Loaded the Messaging SDK from ${FALLBACK_MESSAGING_CDN_BASE} because the default root ${DEFAULT_MESSAGING_CDN_BASE} was blocked or unavailable. Add https://messaging-assets.ada.support to script-src, connect-src and frame-src, or pass cdnBase: \"${FALLBACK_MESSAGING_CDN_BASE}\".`\n\t\t\t\t\t\t: `Loaded the Messaging SDK from ${FALLBACK_MESSAGING_CDN_BASE} because the module at ${url} failed to evaluate (${describeRejection(cause)}). This is an Ada-side problem, not your host's CSP. Report it to Ada.`,\n\t\t\t\t\tcause,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn module;\n\t\t}),\n\t);\n}\n\n// Keyed by import seam like the module memo above: production memoizes on\n// the module-level default while each injected test seam gets an isolated\n// cache. `ada` is set when the promise resolves, so the stopped-interface\n// diagnostic can consult the resolved facade without wrapping it.\ninterface StartedInterfaceMemo {\n\tpromise: Promise<AdaMessagingInterface>;\n\tsettings: AdaMessagingStartOptions;\n\tada?: AdaMessagingInterface;\n}\n\nconst startedInterfaceByImporter = new WeakMap<\n\tImportSdkModule,\n\tStartedInterfaceMemo\n>();\n\n// A rejection can be any value, including one that throws on String(); a\n// diagnostic must never turn a successful fallback into a rejected load.\nfunction describeRejection(cause: unknown): string {\n\ttry {\n\t\treturn cause instanceof Error\n\t\t\t? `${cause.name}: ${cause.message}`\n\t\t\t: String(cause);\n\t} catch {\n\t\treturn \"unknown error\";\n\t}\n}\n\n// Ungated like the runtime logger's dropped-host-value channel so host\n// configuration diagnostics remain visible without debug logging.\nfunction warnHost(message: string, cause?: unknown): void {\n\ttry {\n\t\t// biome-ignore lint/suspicious/noConsole: the loader's sanctioned host-page diagnostic sink\n\t\tconsole.warn(`[Ada] ${message}`, ...(cause === undefined ? [] : [cause]));\n\t} catch {\n\t\t// A host may replace console methods; diagnostics must not throw.\n\t}\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\tif (typeof value !== \"object\" || value === null) {\n\t\treturn false;\n\t}\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\n// Structural equality over the settings surface. Two functions compare equal:\n// fresh inline callbacks on a re-run (React Strict Mode effects) are not a\n// settings change worth a warning. Exotic objects compare by reference.\nfunction settingsEqual(a: unknown, b: unknown): boolean {\n\tif (Object.is(a, b)) {\n\t\treturn true;\n\t}\n\tif (typeof a === \"function\" && typeof b === \"function\") {\n\t\treturn true;\n\t}\n\tif (Array.isArray(a) && Array.isArray(b)) {\n\t\treturn (\n\t\t\ta.length === b.length &&\n\t\t\ta.every((item, index) => settingsEqual(item, b[index]))\n\t\t);\n\t}\n\tif (isPlainObject(a) && isPlainObject(b)) {\n\t\tconst aKeys = Object.keys(a);\n\t\tconst bKeys = new Set(Object.keys(b));\n\t\treturn (\n\t\t\taKeys.length === bKeys.size &&\n\t\t\taKeys.every((key) => bKeys.has(key) && settingsEqual(a[key], b[key]))\n\t\t);\n\t}\n\treturn false;\n}\n\n// Observes the facade's symbol-keyed lifecycle getter (embed-lifecycle.ts)\n// instead of wrapping stop/start, so the customer's interface is never\n// mutated; a pinned runtime that predates the getter yields no flag and the\n// stopped-interface diagnostic is skipped rather than guessed.\nfunction isInterfaceStopped(ada: AdaMessagingInterface): boolean {\n\treturn readEmbedStoppedFlag(ada) === true;\n}\n\nasync function startAdaMessaging(\n\tsettings: AdaMessagingStartOptions,\n\toptions: LoadMessagingSdkOptions,\n): Promise<AdaMessagingInterface> {\n\tconst sdkModule = await loadMessagingSdk(options);\n\tconst ada = sdkModule.createAdaEmbedInterface();\n\tawait ada.start(settings);\n\treturn ada;\n}\n\n/**\n * Load the SDK, create the messaging interface, and start the widget —\n * the npm-first equivalent of the script-tag + `window.adaSettings` setup.\n *\n * One widget per page: the returned promise is memoized, so repeated and\n * concurrent calls resolve to the same started interface and the first\n * call's settings win. A failed load or start clears the memo so a later\n * call retries. Manage the running widget through the returned interface:\n * `stop()` tears it down and a later `start(settings)` on the same interface\n * runs again. Calling {@link loadAdaMessaging} after `stop()` returns the\n * same stopped interface without restarting it. Both memo outcomes log a\n * console warning: ignored differing settings, and a resolved interface\n * whose widget was stopped.\n *\n * Never assigns the interface to `window` or any other global: the returned\n * reference is the only handle, so hold it in module scope. A reference in\n * module scope is reachable only by your own code, never by other scripts on\n * the page.\n *\n * @example\n * // module scope: your code keeps the only reference\n * const ada = await loadAdaMessaging({\n * handle: \"my-bot\",\n * enableProgrammaticControl: true,\n * });\n * await ada.sendMessage(\"Hello\");\n */\nexport function loadAdaMessaging(\n\tsettings: AdaMessagingStartOptions,\n\toptions: LoadMessagingSdkOptions = {},\n): Promise<AdaMessagingInterface> {\n\tconst importModule = options.importModule ?? defaultImportModule;\n\tconst existing = startedInterfaceByImporter.get(importModule);\n\tif (existing) {\n\t\tif (!settingsEqual(settings, existing.settings)) {\n\t\t\twarnHost(\n\t\t\t\t\"loadAdaMessaging() was already called: the new settings are ignored and the existing interface is returned. To apply new settings, call stop() then start(settings) on it.\",\n\t\t\t);\n\t\t}\n\t\tif (existing.ada && isInterfaceStopped(existing.ada)) {\n\t\t\twarnHost(\n\t\t\t\t\"loadAdaMessaging() resolved an interface whose widget was stopped and never restarts it. Call start(settings) on it to run the widget again.\",\n\t\t\t);\n\t\t}\n\t\treturn existing.promise;\n\t}\n\tconst memo: StartedInterfaceMemo = {\n\t\tpromise: startAdaMessaging(settings, options),\n\t\tsettings,\n\t};\n\tstartedInterfaceByImporter.set(importModule, memo);\n\tmemo.promise.then(\n\t\t(ada) => {\n\t\t\tmemo.ada = ada;\n\t\t},\n\t\t() => {\n\t\t\tif (startedInterfaceByImporter.get(importModule) === memo) {\n\t\t\t\tstartedInterfaceByImporter.delete(importModule);\n\t\t\t}\n\t\t},\n\t);\n\treturn memo.promise;\n}\n"],"mappings":";AAMA,IAAM,kBAAkB;AACxB,IAAM,wBAAwB;;;;;;;;;;;;AAa9B,IAAa,gBAAwB;;;;;AAMrC,SAAgB,qBAAqB,MAAc,eAAwB;CAC1E,MAAM,aAAa,IAAI,MAAM,CAAC,aAAa;AAC3C,QACC,gBAAgB,KAAK,WAAW,IAAI,CAAC,sBAAsB,KAAK,WAAW;;;;;;;;;;;ACtB7E,IAAa,0BAA0B,OAAO,IAC7C,qCACA;;AAGD,SAAgB,qBAAqB,KAAkC;CACtE,MAAM,QAAS,IAAgC;AAC/C,QAAO,OAAO,UAAU,YAAY,QAAQ,KAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACK7C,IAAa,6BACZ;AAED,IAAa,8BACZ;AAED,IAAM,yBAAyB;AAM/B,IAAM,wBAAwB;AAM9B,IAAM,2BAA2B;AACjC,IAAM,8BAA8B;;AAuBpC,IAAa,wBAAb,cAA2C,MAAM;CAIhD,YACC,SACA,MACA,OACA,eACC;AACD,QAAM,QAAQ;wBATf,QAAA,KAAA,EAAS;AAUR,OAAK,OAAO;AACZ,OAAK,OAAO;AACZ,MAAI,UAAU,KAAA,EACb,MAAK,QAAQ;AAEd,MAAI,kBAAkB,KAAA,EACrB,QAAO,eAAe,MAAM,iBAAiB;GAC5C,OAAO;GACP,YAAY;GACZ,CAAC;;;AA2DL,IAAM,uBAAwC,QAC7C;;;CAAoD;;AASrD,IAAM,kC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c,EAAE,EAAE;EACzC,MAAM,QAAQ,OAAO,KAAK,EAAE;EAC5B,MAAM,QAAQ,IAAI,IAAI,OAAO,KAAK,EAAE,CAAC;AACrC,SACC,MAAM,WAAW,MAAM,QACvB,MAAM,OAAO,QAAQ,MAAM,IAAI,IAAI,IAAI,cAAc,EAAE,MAAM,EAAE,KAAK,CAAC;;AAGvE,QAAO;;AAOR,SAAS,mBAAmB,KAAqC;AAChE,QAAO,qBAAqB,IAAI,KAAK;;AAGtC,eAAe,kBACd,UACA,SACiC;CAEjC,MAAM,OADY,MAAM,iBAAiB,QAAQ,EAC3B,yBAAyB;AAC/C,OAAM,IAAI,MAAM,SAAS;AACzB,QAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BR,SAAgB,iBACf,UACA,UAAmC,EAAE,EACJ;CACjC,MAAM,eAAe,QAAQ,gBAAgB;CAC7C,MAAM,WAAW,2BAA2B,IAAI,aAAa;AAC7D,KAAI,UAAU;AACb,MAAI,CAAC,cAAc,UAAU,SAAS,SAAS,CAC9C,UACC,6KACA;AAEF,MAAI,SAAS,OAAO,mBAAmB,SAAS,IAAI,CACnD,UACC,+IACA;AAEF,SAAO,SAAS;;CAEjB,MAAM,OAA6B;EAClC,SAAS,kBAAkB,UAAU,QAAQ;EAC7C;EACA;AACD,4BAA2B,IAAI,cAAc,KAAK;AAClD,MAAK,QAAQ,MACX,QAAQ;AACR,OAAK,MAAM;UAEN;AACL,MAAI,2BAA2B,IAAI,aAAa,KAAK,KACpD,4BAA2B,OAAO,aAAa;GAGjD;AACD,QAAO,KAAK"}
@@ -8,6 +8,7 @@ import type { mountAdaWebViewRuntime, resolveAdaWebViewRuntimeAssets } from "../
8
8
  * the bootstrap at this root resolves the current rollout at load time.
9
9
  */
10
10
  export declare const DEFAULT_MESSAGING_CDN_BASE = "https://messaging-assets.ada.support/";
11
+ export declare const FALLBACK_MESSAGING_CDN_BASE = "https://static.ada.support/messaging/";
11
12
  /** Why a {@link MessagingSdkLoadError} was raised. */
12
13
  export type MessagingSdkLoadErrorCode =
13
14
  /**
@@ -23,14 +24,15 @@ export type MessagingSdkLoadErrorCode =
23
24
  * its `CDN_BUILD_SHA` names no CDN build.
24
25
  */
25
26
  | "unstamped_build_sha"
26
- /** The dynamic import of the CDN bootstrap failed (network, CSP, 404). */
27
+ /** The dynamic import of the CDN bootstrap failed (fetch or evaluation). */
27
28
  | "sdk_import_failed"
28
29
  /** The imported module does not expose the Ada Messaging SDK surface. */
29
30
  | "sdk_module_invalid";
30
31
  /** Typed failure raised by {@link loadMessagingSdk} and {@link loadAdaMessaging}. */
31
32
  export declare class MessagingSdkLoadError extends Error {
32
33
  readonly code: MessagingSdkLoadErrorCode;
33
- constructor(message: string, code: MessagingSdkLoadErrorCode, cause?: unknown);
34
+ readonly fallbackCause?: MessagingSdkLoadError;
35
+ constructor(message: string, code: MessagingSdkLoadErrorCode, cause?: unknown, fallbackCause?: MessagingSdkLoadError);
34
36
  }
35
37
  /**
36
38
  * The programmatic messaging interface {@link loadAdaMessaging} resolves. An
@@ -57,9 +59,9 @@ export interface LoadMessagingSdkOptions {
57
59
  * CDN root to resolve `sdk.js` from. Must be an `https:` URL; plain
58
60
  * `http:` is accepted only for loopback hosts (`localhost`, `127.0.0.1`,
59
61
  * `[::1]`, `*.localhost`) during local development. Defaults to the
60
- * production root ({@link DEFAULT_MESSAGING_CDN_BASE}). Override it with
61
- * the Ada-provided asset host for a staging validation window only;
62
- * production pages must keep the default.
62
+ * production root ({@link DEFAULT_MESSAGING_CDN_BASE}). An explicit value,
63
+ * including {@link FALLBACK_MESSAGING_CDN_BASE}, disables the automatic
64
+ * static-root fallback.
63
65
  */
64
66
  cdnBase?: string;
65
67
  /**
@@ -83,7 +85,9 @@ export interface LoadMessagingSdkOptions {
83
85
  *
84
86
  * The returned promise is memoized per resolved URL: concurrent and repeated
85
87
  * calls share one in-flight import. A failed load clears the memo so a later
86
- * call retries. Rejections are always {@link MessagingSdkLoadError}.
88
+ * call retries. Without `cdnBase`, an import failure at the default root is
89
+ * retried once from {@link FALLBACK_MESSAGING_CDN_BASE}. Rejections are always
90
+ * {@link MessagingSdkLoadError}.
87
91
  *
88
92
  * @example
89
93
  * const { createAdaEmbedInterface } = await loadMessagingSdk();
@@ -8,6 +8,7 @@ import type { mountAdaWebViewRuntime, resolveAdaWebViewRuntimeAssets } from "../
8
8
  * the bootstrap at this root resolves the current rollout at load time.
9
9
  */
10
10
  export declare const DEFAULT_MESSAGING_CDN_BASE = "https://messaging-assets.ada.support/";
11
+ export declare const FALLBACK_MESSAGING_CDN_BASE = "https://static.ada.support/messaging/";
11
12
  /** Why a {@link MessagingSdkLoadError} was raised. */
12
13
  export type MessagingSdkLoadErrorCode =
13
14
  /**
@@ -23,14 +24,15 @@ export type MessagingSdkLoadErrorCode =
23
24
  * its `CDN_BUILD_SHA` names no CDN build.
24
25
  */
25
26
  | "unstamped_build_sha"
26
- /** The dynamic import of the CDN bootstrap failed (network, CSP, 404). */
27
+ /** The dynamic import of the CDN bootstrap failed (fetch or evaluation). */
27
28
  | "sdk_import_failed"
28
29
  /** The imported module does not expose the Ada Messaging SDK surface. */
29
30
  | "sdk_module_invalid";
30
31
  /** Typed failure raised by {@link loadMessagingSdk} and {@link loadAdaMessaging}. */
31
32
  export declare class MessagingSdkLoadError extends Error {
32
33
  readonly code: MessagingSdkLoadErrorCode;
33
- constructor(message: string, code: MessagingSdkLoadErrorCode, cause?: unknown);
34
+ readonly fallbackCause?: MessagingSdkLoadError;
35
+ constructor(message: string, code: MessagingSdkLoadErrorCode, cause?: unknown, fallbackCause?: MessagingSdkLoadError);
34
36
  }
35
37
  /**
36
38
  * The programmatic messaging interface {@link loadAdaMessaging} resolves. An
@@ -57,9 +59,9 @@ export interface LoadMessagingSdkOptions {
57
59
  * CDN root to resolve `sdk.js` from. Must be an `https:` URL; plain
58
60
  * `http:` is accepted only for loopback hosts (`localhost`, `127.0.0.1`,
59
61
  * `[::1]`, `*.localhost`) during local development. Defaults to the
60
- * production root ({@link DEFAULT_MESSAGING_CDN_BASE}). Override it with
61
- * the Ada-provided asset host for a staging validation window only;
62
- * production pages must keep the default.
62
+ * production root ({@link DEFAULT_MESSAGING_CDN_BASE}). An explicit value,
63
+ * including {@link FALLBACK_MESSAGING_CDN_BASE}, disables the automatic
64
+ * static-root fallback.
63
65
  */
64
66
  cdnBase?: string;
65
67
  /**
@@ -83,7 +85,9 @@ export interface LoadMessagingSdkOptions {
83
85
  *
84
86
  * The returned promise is memoized per resolved URL: concurrent and repeated
85
87
  * calls share one in-flight import. A failed load clears the memo so a later
86
- * call retries. Rejections are always {@link MessagingSdkLoadError}.
88
+ * call retries. Without `cdnBase`, an import failure at the default root is
89
+ * retried once from {@link FALLBACK_MESSAGING_CDN_BASE}. Rejections are always
90
+ * {@link MessagingSdkLoadError}.
87
91
  *
88
92
  * @example
89
93
  * const { createAdaEmbedInterface } = await loadMessagingSdk();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ada-cx/messaging-sdk",
3
- "version": "1.3.3",
3
+ "version": "1.3.6",
4
4
  "description": "TypeScript types, test mocks, and a thin CDN loader for the Ada Messaging SDK. The runtime always resolves from Ada's CDN and is never bundled into this package.",
5
5
  "homepage": "https://docs.ada.cx",
6
6
  "keywords": [