@dataships/launcher 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
1
  {
2
- "launcher.js": "sha384-G6itJsfiMshc5Sdg9NdFuI8cJxq4WCMsU19gsN9NxviUC7rxTApGRZ8lgvqXY5aG",
3
- "modules/alia-0.2.0.js": "sha384-jW/3r9fyQjBcLKnIiLSbASojfBstddKdOxHnOUtnHRvJBbaMuD3yDJprA0GaLkQv"
2
+ "launcher.js": "sha384-KeYYDjz7cg+4rVIV/Mat2Xc3PVfcrV/yvTdEBixpKnfM6rpqYrTdEQ1NuZ7nNa1X",
3
+ "modules/alia-0.3.1.js": "sha384-IJI/bSn1LfESc4P54YhWMyFJ1ijB0KH+26AfjMvWFI4sai6DDNYSmcOaeas2LviK"
4
4
  }
package/dist/launcher.js CHANGED
@@ -42,6 +42,23 @@
42
42
  return { datashipsSessionId, token, elements: refs };
43
43
  };
44
44
  var elementsOfType = (data, type) => data.elements.filter((element) => element.type === type);
45
+ var maxAgeMsOf = (response) => {
46
+ const directives = (response.headers.get("Cache-Control") ?? "").toLowerCase().split(",").map((directive) => directive.trim());
47
+ if (directives.includes("no-store") || directives.includes("no-cache"))
48
+ return 0;
49
+ for (const directive of directives) {
50
+ const seconds = /^max-age\s*=\s*"?(\d+)"?$/.exec(directive)?.[1];
51
+ if (seconds !== void 0) return Number(seconds) * 1e3;
52
+ }
53
+ return 0;
54
+ };
55
+ var outcomeOf = async (response) => {
56
+ if (response.status === 403) return { status: "refused" };
57
+ if (response.status !== 200) return { status: "failed" };
58
+ const data = parseElements(await response.json());
59
+ if (!data) return { status: "failed" };
60
+ return data.elements.length === 0 ? { status: "refused" } : { status: "ok", data };
61
+ };
45
62
  var fetchElements = async (fetchFn, baseUrl, publicKey) => {
46
63
  try {
47
64
  const response = await fetchFn(`${baseUrl}${ELEMENTS_PATH}`, {
@@ -49,13 +66,12 @@
49
66
  headers: { "x-api-key": publicKey },
50
67
  credentials: "omit"
51
68
  });
52
- if (response.status === 403) return { status: "refused" };
53
- if (response.status !== 200) return { status: "failed" };
54
- const data = parseElements(await response.json());
55
- if (!data) return { status: "failed" };
56
- return data.elements.length === 0 ? { status: "refused" } : { status: "ok", data };
69
+ return {
70
+ outcome: await outcomeOf(response),
71
+ maxAgeMs: maxAgeMsOf(response)
72
+ };
57
73
  } catch {
58
- return { status: "failed" };
74
+ return { outcome: { status: "failed" }, maxAgeMs: 0 };
59
75
  }
60
76
  };
61
77
 
@@ -77,18 +93,21 @@
77
93
  const entry = JSON.parse(raw);
78
94
  if (typeof entry.at !== "number" || now < entry.at || now - entry.at >= CACHE_TTL_MS)
79
95
  return null;
80
- if (entry.status === "refused") return { status: "refused" };
96
+ const at = entry.at;
97
+ const receivedAt = typeof entry.receivedAt === "number" && entry.receivedAt <= at ? entry.receivedAt : at;
98
+ if (entry.status === "refused")
99
+ return { answer: { status: "refused" }, at, receivedAt };
81
100
  const data = entry.status === "ok" ? parseElements(entry.data) : null;
82
- return data && data.elements.length > 0 ? { status: "ok", data } : null;
101
+ return data && data.elements.length > 0 ? { answer: { status: "ok", data }, at, receivedAt } : null;
83
102
  } catch {
84
103
  return null;
85
104
  }
86
105
  }
87
- write(answer, now) {
106
+ write(answer, now, receivedAt = now) {
88
107
  try {
89
108
  __privateGet(this, _win).sessionStorage.setItem(
90
109
  __privateGet(this, _key),
91
- JSON.stringify({ at: now, ...answer })
110
+ JSON.stringify({ at: now, receivedAt, ...answer })
92
111
  );
93
112
  } catch {
94
113
  }
@@ -147,11 +166,98 @@
147
166
  var MODULES = [
148
167
  {
149
168
  type: "ALIA_FORM",
150
- file: `modules/alia-${"0.2.0"}.js`,
169
+ file: `modules/alia-${"0.3.1"}.js`,
151
170
  watch: watchAlia
152
171
  }
153
172
  ];
154
173
 
174
+ // src/token.ts
175
+ var TOKEN_TTL_MS = 30 * 60 * 1e3;
176
+ var REFRESH_MARGIN_MS = 2 * 60 * 1e3;
177
+ var REFRESH_RETRY_DELAY_MS = 1e3;
178
+ var TOKEN_REFRESH_PATH = "/v1/elements/token/refresh";
179
+ var RefreshError = class extends Error {
180
+ constructor(message, transient) {
181
+ super(message);
182
+ this.transient = transient;
183
+ }
184
+ };
185
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
186
+ var createElementsToken = (options) => {
187
+ let token = options.token;
188
+ let receivedAt = options.receivedAt;
189
+ let stale = false;
190
+ let refreshing = null;
191
+ const needsRefresh = (now) => stale || now < receivedAt || now - receivedAt >= TOKEN_TTL_MS - REFRESH_MARGIN_MS;
192
+ const stillValid = (now) => !stale && now >= receivedAt && now - receivedAt < TOKEN_TTL_MS;
193
+ const wait = options.wait ?? sleep;
194
+ const attempt = async () => {
195
+ const sentAt = options.now();
196
+ const fresh = await requestToken(options, token);
197
+ token = fresh;
198
+ receivedAt = sentAt;
199
+ stale = false;
200
+ return fresh;
201
+ };
202
+ const refresh = async () => {
203
+ try {
204
+ return await attempt();
205
+ } catch (error) {
206
+ if (stillValid(options.now())) return token;
207
+ stale = true;
208
+ if (!(error instanceof RefreshError && error.transient)) throw error;
209
+ }
210
+ await wait(REFRESH_RETRY_DELAY_MS);
211
+ try {
212
+ return await attempt();
213
+ } catch (error) {
214
+ stale = true;
215
+ throw error;
216
+ }
217
+ };
218
+ return {
219
+ getToken: () => {
220
+ if (refreshing) return refreshing;
221
+ if (!needsRefresh(options.now())) return Promise.resolve(token);
222
+ refreshing = refresh().finally(() => {
223
+ refreshing = null;
224
+ });
225
+ return refreshing;
226
+ },
227
+ onUnauthorized: () => {
228
+ stale = true;
229
+ }
230
+ };
231
+ };
232
+ var requestToken = async ({ fetch, baseUrl, publicKey, datashipsSessionId }, held) => {
233
+ let response;
234
+ try {
235
+ response = await fetch(`${baseUrl}${TOKEN_REFRESH_PATH}`, {
236
+ method: "POST",
237
+ headers: {
238
+ "x-api-key": publicKey,
239
+ "Content-Type": "application/json",
240
+ Authorization: `Bearer ${held}`
241
+ },
242
+ credentials: "omit",
243
+ body: JSON.stringify({ datashipsSessionId })
244
+ });
245
+ } catch {
246
+ throw new RefreshError("token refresh failed (network)", true);
247
+ }
248
+ if (response.status !== 200) {
249
+ throw new RefreshError(
250
+ `token refresh failed (${response.status})`,
251
+ response.status >= 500
252
+ );
253
+ }
254
+ const body = await response.json().catch(() => null);
255
+ if (typeof body?.token !== "string" || body.token.length === 0) {
256
+ throw new RefreshError("token refresh returned no token", false);
257
+ }
258
+ return body.token;
259
+ };
260
+
155
261
  // src/boot.ts
156
262
  var defaultImport = (url) => import(
157
263
  /* @vite-ignore */
@@ -169,7 +275,7 @@
169
275
  if (!config) return;
170
276
  const guard = win;
171
277
  if (guard.__datashipsLauncher) return;
172
- guard.__datashipsLauncher = { version: "0.2.0" };
278
+ guard.__datashipsLauncher = { version: "0.3.1" };
173
279
  const modules = env.modules ?? MODULES;
174
280
  const importModule = env.importModule ?? defaultImport;
175
281
  const load = (definition, context, beforeStart) => startModule(importModule, config, definition, context, beforeStart);
@@ -178,7 +284,7 @@
178
284
  publicKey: config.publicKey,
179
285
  baseUrl: config.baseUrl,
180
286
  preview: true,
181
- token: null,
287
+ auth: null,
182
288
  datashipsSessionId: null,
183
289
  elements: [],
184
290
  events: []
@@ -190,7 +296,23 @@
190
296
  definition,
191
297
  watch: definition.watch(win)
192
298
  }));
193
- const outcome = await resolveElements(env, config);
299
+ const fetchFn = env.fetch ?? ((url, init) => env.window.fetch(url, init));
300
+ const now = env.now ?? Date.now;
301
+ const { outcome, receivedAt } = await resolveElements(
302
+ env.window,
303
+ fetchFn,
304
+ now,
305
+ config
306
+ );
307
+ const auth = outcome.status === "ok" ? createElementsToken({
308
+ fetch: fetchFn,
309
+ baseUrl: config.baseUrl,
310
+ publicKey: config.publicKey,
311
+ datashipsSessionId: outcome.data.datashipsSessionId,
312
+ token: outcome.data.token,
313
+ receivedAt,
314
+ now
315
+ }) : null;
194
316
  for (const { definition, watch } of watched) {
195
317
  const elements = outcome.status === "ok" ? elementsOfType(outcome.data, definition.type).map(
196
318
  ({ id, channels }) => ({ id, channels })
@@ -203,7 +325,7 @@
203
325
  publicKey: config.publicKey,
204
326
  baseUrl: config.baseUrl,
205
327
  preview: false,
206
- token: outcome.data.token,
328
+ auth,
207
329
  datashipsSessionId: outcome.data.datashipsSessionId,
208
330
  elements,
209
331
  events: watch.events
@@ -211,19 +333,19 @@
211
333
  void watch.present.then(() => load(definition, context, watch.stop));
212
334
  }
213
335
  };
214
- var resolveElements = async (env, config) => {
215
- const now = env.now ?? Date.now;
216
- const cache = new ElementsCache(env.window, config.publicKey);
336
+ var resolveElements = async (win, fetchFn, now, config) => {
337
+ const cache = new ElementsCache(win, config.publicKey);
217
338
  const cached = cache.read(now());
218
- if (cached) return cached;
219
- const fetchFn = env.fetch ?? ((url, init) => env.window.fetch(url, init));
220
- const outcome = await fetchElements(
339
+ if (cached) return { outcome: cached.answer, receivedAt: cached.receivedAt };
340
+ const sentAt = now();
341
+ const { outcome, maxAgeMs } = await fetchElements(
221
342
  fetchFn,
222
343
  config.baseUrl,
223
344
  config.publicKey
224
345
  );
225
- if (outcome.status !== "failed") cache.write(outcome, now());
226
- return outcome;
346
+ const receivedAt = sentAt - maxAgeMs;
347
+ if (outcome.status !== "failed") cache.write(outcome, sentAt, receivedAt);
348
+ return { outcome, receivedAt };
227
349
  };
228
350
  var startModule = async (importModule, config, definition, context, beforeStart) => {
229
351
  try {
@@ -1,4 +1,4 @@
1
- // node_modules/@dataships/sdk/dist/index.js
1
+ // node_modules/@dataships/elements/node_modules/@dataships/sdk/dist/index.js
2
2
  var __typeError = (msg) => {
3
3
  throw TypeError(msg);
4
4
  };
@@ -600,7 +600,7 @@ post_fn = async function(args) {
600
600
  });
601
601
  };
602
602
 
603
- // node_modules/@dataships/sdk/dist/adapters/custom-platform-checkout/index.js
603
+ // node_modules/@dataships/elements/node_modules/@dataships/sdk/dist/adapters/custom-platform-checkout/index.js
604
604
  var __typeError2 = (msg) => {
605
605
  throw TypeError(msg);
606
606
  };
@@ -952,7 +952,7 @@ resolveSessionId_fn = function() {
952
952
  };
953
953
  var isCollectionStep = (value) => value === "CHECKOUT_INFORMATION" || value === "THANK_YOU" || value === "ORDER_STATUS";
954
954
 
955
- // node_modules/@dataships/sdk/dist/adapters/custom-platform-signup/index.js
955
+ // node_modules/@dataships/elements/node_modules/@dataships/sdk/dist/adapters/custom-platform-signup/index.js
956
956
  var __typeError3 = (msg) => {
957
957
  throw TypeError(msg);
958
958
  };
@@ -1346,6 +1346,14 @@ var BASE_STYLES = (
1346
1346
  /* The modal has its own background, so it must not take the page's text styles. */
1347
1347
  :host([data-host-styled]) .modal { color: var(--ds-color-text, #111827); font-size: 1rem; text-align: start; }
1348
1348
 
1349
+ .preview-badge {
1350
+ justify-self: center;
1351
+ margin: 0;
1352
+ padding: 0.15em 0.6em;
1353
+ font-size: var(--ds-font-size, inherit);
1354
+ border-radius: var(--ds-border-radius, 6px);
1355
+ }
1356
+
1349
1357
  .modal {
1350
1358
  max-width: min(560px, 90vw);
1351
1359
  padding: 0;
@@ -1367,7 +1375,7 @@ var BASE_STYLES = (
1367
1375
  `
1368
1376
  );
1369
1377
  var WORDS = {
1370
- en: { clickHere: "Click here", privacyPolicy: "Privacy Policy", termsOfService: "Terms of Service", consent: "consent", object: "object", optIn: "opt in", optOut: "opt out" },
1378
+ en: { clickHere: "Click here", privacyPolicy: "Privacy Policy", termsOfService: "Terms of Service", contactUs: "Contact Us", consent: "consent", object: "object", optIn: "opt in", optOut: "opt out" },
1371
1379
  es: { clickHere: "Haz clic aqu\xED", privacyPolicy: "Pol\xEDtica de privacidad", termsOfService: "Condiciones del servicio", consent: "consentimiento", object: "oponerte", optIn: "inscribirte", optOut: "no quieres recibirlo" },
1372
1380
  de: { clickHere: "Klicken Sie hier", privacyPolicy: "Datenschutzrichtlinie", termsOfService: "Servicebedingungen", consent: "Zustimmung", object: "protestieren", optIn: "zuzustimmen", optOut: "widersprechen" },
1373
1381
  fr: { clickHere: "Cliquez ici", privacyPolicy: "Politique de confidentialit\xE9", termsOfService: "Conditions d'utilisation", consent: "consentement", object: "d\xE9sapprouver", optIn: "accepter", optOut: "refuser" }
@@ -1473,6 +1481,7 @@ var el = (tag, { className, text, attrs = {} } = {}, children = []) => {
1473
1481
  for (const c of children) node.append(c);
1474
1482
  return node;
1475
1483
  };
1484
+ var PREVIEW_BADGE = "Preview \xB7 nothing is recorded";
1476
1485
  var _shadow;
1477
1486
  var _root;
1478
1487
  var _onConsentChange;
@@ -1513,7 +1522,7 @@ _shadow = /* @__PURE__ */ new WeakMap();
1513
1522
  _root = /* @__PURE__ */ new WeakMap();
1514
1523
  _onConsentChange = /* @__PURE__ */ new WeakMap();
1515
1524
  _DatashipsWidget_instances = /* @__PURE__ */ new WeakSet();
1516
- renderInto_fn = function(response, { page, locale = "en", heading = "Email marketing preferences", channel = "EMAIL" }) {
1525
+ renderInto_fn = function(response, { page, locale = "en", heading = "Email marketing preferences", channel = "EMAIL", preview = false }) {
1517
1526
  __privateGet4(this, _root)?.remove();
1518
1527
  __privateSet4(this, _root, null);
1519
1528
  const item = (response?.consents ?? []).find((c) => c.channel === channel);
@@ -1556,6 +1565,7 @@ renderInto_fn = function(response, { page, locale = "en", heading = "Email marke
1556
1565
  return b;
1557
1566
  },
1558
1567
  privacyPolicy: (m) => link(m, policyURL),
1568
+ contactUs: (m) => link(m, cfg.contactUsURL),
1559
1569
  // SMS copy also names the mobile terms; email copy keeps linking the privacy policy only.
1560
1570
  ...channel === "SMS" ? { termsOfService: (m) => link(m, cfg.mobileTermsOfServiceURL) } : {}
1561
1571
  });
@@ -1585,6 +1595,7 @@ renderInto_fn = function(response, { page, locale = "en", heading = "Email marke
1585
1595
  root.append(el("p", { className: "description" }, formatCopy(description, locale, rules(cfg.policyURL))));
1586
1596
  }
1587
1597
  if (modal) root.append(modal);
1598
+ if (preview) root.append(el("p", { className: "preview-badge", text: PREVIEW_BADGE }));
1588
1599
  __privateGet4(this, _shadow).append(root);
1589
1600
  __privateSet4(this, _root, root);
1590
1601
  this.setAttribute("data-visible", "");
@@ -1641,7 +1652,7 @@ var createSdkClient = (opts) => {
1641
1652
  ...preview ? {} : opts.unsafeServerKey ? { auth: { unsafeServerKey: opts.unsafeServerKey } } : { auth: { publicKey: opts.publicKey, token: opts.token } },
1642
1653
  env: opts.env ?? "production",
1643
1654
  app: ELEMENTS_APP_NAME,
1644
- version: "2.5.0",
1655
+ version: "2.7.0",
1645
1656
  adapter,
1646
1657
  ...opts.baseUrl ? { baseUrl: opts.baseUrl } : {},
1647
1658
  ...opts.fetch ? { fetch: opts.fetch } : {}
@@ -2126,6 +2137,7 @@ var mount = (config) => {
2126
2137
  defineWidget();
2127
2138
  const { page, appearance = {}, locale = "en", position = "after" } = config;
2128
2139
  const target = config.mount;
2140
+ const preview = config.preview === true;
2129
2141
  const log = config.log ?? defaultLog;
2130
2142
  const root = config.root ?? document;
2131
2143
  const registry = registryFor(root);
@@ -2159,7 +2171,7 @@ var mount = (config) => {
2159
2171
  emit,
2160
2172
  heartbeat: strategy.heartbeat,
2161
2173
  identifierType,
2162
- onResponse: (response) => widget.render(response, { page, locale, channel })
2174
+ onResponse: (response) => widget.render(response, { page, locale, channel, preview })
2163
2175
  });
2164
2176
  widget.onConsentChange = (consent) => session.saveConsent(consent);
2165
2177
  keepPlaced(dom, widget, target, position);
@@ -2169,7 +2181,7 @@ var mount = (config) => {
2169
2181
  update: ({ appearance: a, page: p }) => {
2170
2182
  widget.setAppearance(a);
2171
2183
  if (p !== page) log("page change on a repeat mount() is not supported; unmount first");
2172
- widget.render(session.response, { page, locale, channel });
2184
+ widget.render(session.response, { page, locale, channel, preview });
2173
2185
  },
2174
2186
  handle: {
2175
2187
  ready,
@@ -2188,7 +2200,7 @@ var mount = (config) => {
2188
2200
  return entry.handle;
2189
2201
  };
2190
2202
 
2191
- // node_modules/@dataships/sdk/dist/adapters/alia-form/index.js
2203
+ // node_modules/@dataships/sdk/dist/index.js
2192
2204
  var __typeError5 = (msg) => {
2193
2205
  throw TypeError(msg);
2194
2206
  };
@@ -2196,6 +2208,638 @@ var __accessCheck5 = (obj, member, msg) => member.has(obj) || __typeError5("Cann
2196
2208
  var __privateGet5 = (obj, member, getter) => (__accessCheck5(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
2197
2209
  var __privateAdd5 = (obj, member, value) => member.has(obj) ? __typeError5("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2198
2210
  var __privateSet5 = (obj, member, value, setter) => (__accessCheck5(obj, member, "write to private field"), member.set(obj, value), value);
2211
+ var __privateMethod5 = (obj, member, method) => (__accessCheck5(obj, member, "access private method"), method);
2212
+ var SERVER_KEY_PREFIX2 = "ds_sk_";
2213
+ var isServerKey2 = (key) => key.startsWith(SERVER_KEY_PREFIX2);
2214
+ var isServerKeyAuth2 = (auth) => "serverKey" in auth;
2215
+ var isUnsafeServerKeyAuth2 = (auth) => "unsafeServerKey" in auth;
2216
+ var isTokenProviderAuth2 = (auth) => typeof auth.getToken === "function";
2217
+ var resolveTokenProviderAuth2 = async (auth) => {
2218
+ const token = await auth.getToken();
2219
+ if (!token) {
2220
+ throw new Error("DatashipsClient: auth.getToken() returned an empty token");
2221
+ }
2222
+ return { publicKey: auth.publicKey, token };
2223
+ };
2224
+ var UNSAFE_SERVER_KEY_APP_MARKER2 = "unsafe-server-key";
2225
+ var UNSAFE_SERVER_KEY_WARNING2 = "Dataships SDK: the merchant SERVER KEY is being used in the browser (auth.unsafeServerKey). Anyone who views this page's source can act as this merchant until the key is revoked. Mint a short-lived token on your server and pass auth: { publicKey, token } instead.";
2226
+ var assertBrowserAuth2 = (auth) => {
2227
+ if (isUnsafeServerKeyAuth2(auth)) {
2228
+ if (!auth.unsafeServerKey || !isServerKey2(auth.unsafeServerKey)) {
2229
+ throw new Error(
2230
+ "DatashipsClient: auth.unsafeServerKey must be a server key (ds_sk_\u2026); a public key belongs in auth: { publicKey, token }"
2231
+ );
2232
+ }
2233
+ warnUnsafeServerKey2();
2234
+ return;
2235
+ }
2236
+ if (isServerKey2(auth.publicKey)) {
2237
+ throw new Error(
2238
+ "DatashipsClient: a server key (ds_sk_\u2026) must never be used in the browser; use the public key with a merchant-signed token, or DatashipsServerClient from '@dataships/sdk/server' on your server"
2239
+ );
2240
+ }
2241
+ const hasProvider = "getToken" in auth && auth.getToken !== void 0;
2242
+ const hook = auth.onUnauthorized;
2243
+ if (hook !== void 0 && typeof hook !== "function") {
2244
+ throw new Error("DatashipsClient: auth.onUnauthorized must be a function");
2245
+ }
2246
+ if (hook !== void 0 && !hasProvider) {
2247
+ throw new Error(
2248
+ "DatashipsClient: auth.onUnauthorized requires getToken; a fixed token cannot be refreshed for the retry"
2249
+ );
2250
+ }
2251
+ if (hasProvider && "token" in auth && auth.token !== void 0) {
2252
+ throw new Error(
2253
+ "DatashipsClient: pass either auth.token or auth.getToken, not both"
2254
+ );
2255
+ }
2256
+ if (hasProvider) {
2257
+ if (!isTokenProviderAuth2(auth)) {
2258
+ throw new Error("DatashipsClient: auth.getToken must be a function");
2259
+ }
2260
+ return;
2261
+ }
2262
+ if (!auth.token) {
2263
+ throw new Error(
2264
+ "DatashipsClient: auth.token is required with a public key (the merchant's server mints it), or auth.getToken to fetch one per request"
2265
+ );
2266
+ }
2267
+ };
2268
+ var warnUnsafeServerKey2 = () => {
2269
+ const c = globalThis.console;
2270
+ c?.warn?.(UNSAFE_SERVER_KEY_WARNING2);
2271
+ };
2272
+ var authHeaders2 = (auth) => {
2273
+ if (isUnsafeServerKeyAuth2(auth)) return { "X-Api-Key": auth.unsafeServerKey };
2274
+ return isServerKeyAuth2(auth) ? { "X-Api-Key": auth.serverKey } : { "X-Api-Key": auth.publicKey, Authorization: `Bearer ${auth.token}` };
2275
+ };
2276
+ var PRODUCTION_BASE_URL2 = "https://api.dataships.io";
2277
+ var resolveBaseUrl2 = (env = "production", baseUrl) => {
2278
+ if (baseUrl) return baseUrl;
2279
+ if (env === "production") return PRODUCTION_BASE_URL2;
2280
+ throw new Error(
2281
+ `Dataships SDK: env "${env}" has no default base URL; pass \`baseUrl\``
2282
+ );
2283
+ };
2284
+ var TERMINAL_STATUSES2 = /* @__PURE__ */ new Set([
2285
+ 400,
2286
+ 401,
2287
+ 403,
2288
+ 404,
2289
+ 417,
2290
+ 422,
2291
+ 426
2292
+ ]);
2293
+ var isTerminalStatus2 = (status) => status !== void 0 && TERMINAL_STATUSES2.has(status);
2294
+ var CONSENT_SESSION_ALREADY_PROCESSED2 = "CONSENT_SESSION_ALREADY_PROCESSED";
2295
+ var TERMINAL_ERROR_CODES2 = /* @__PURE__ */ new Set([
2296
+ CONSENT_SESSION_ALREADY_PROCESSED2
2297
+ ]);
2298
+ var isTerminalErrorCode2 = (errorCode) => errorCode !== void 0 && TERMINAL_ERROR_CODES2.has(errorCode);
2299
+ var MAX_FAILURES2 = 4;
2300
+ var backoffMs2 = (failureCount) => failureCount >= MAX_FAILURES2 ? 0 : failureCount * 2e3;
2301
+ var defaultRetryPolicy2 = {
2302
+ shouldRetry: (failureCount, status, errorCode) => !isTerminalStatus2(status) && !isTerminalErrorCode2(errorCode) && failureCount < MAX_FAILURES2,
2303
+ delayMs: backoffMs2
2304
+ };
2305
+ var upsertSessionRetryPolicy2 = defaultRetryPolicy2;
2306
+ var noRetryPolicy2 = {
2307
+ shouldRetry: () => false,
2308
+ delayMs: () => 0
2309
+ };
2310
+ var DatashipsError2 = class extends Error {
2311
+ constructor(args) {
2312
+ super(`Dataships request failed (${args.status || "network"})`);
2313
+ this.name = "DatashipsError";
2314
+ this.status = args.status;
2315
+ this.body = args.body;
2316
+ this.challenge = args.challenge ?? null;
2317
+ this.code = errorCodeFromBody2(args.body);
2318
+ this.reason = reasonFromBody2(args.body);
2319
+ }
2320
+ /** 401 (missing / refused credential) or 403 (unknown, revoked or disabled key). */
2321
+ get isAuthenticationFailure() {
2322
+ return this.status === 401 || this.status === 403;
2323
+ }
2324
+ /** 409 `CONSENT_SESSION_ALREADY_PROCESSED`: the session is closed; no later call on it can succeed. */
2325
+ get isSessionProcessed() {
2326
+ return this.code === CONSENT_SESSION_ALREADY_PROCESSED2;
2327
+ }
2328
+ };
2329
+ var errorCodeFromBody2 = (body) => {
2330
+ if (typeof body !== "object" || body === null) return null;
2331
+ const errors = body.errors;
2332
+ if (!Array.isArray(errors)) return null;
2333
+ const code = errors[0]?.code;
2334
+ return typeof code === "string" ? code : null;
2335
+ };
2336
+ var reasonFromBody2 = (body) => {
2337
+ if (typeof body !== "object" || body === null) return null;
2338
+ const message = body.message;
2339
+ return typeof message === "string" && message.length > 0 ? message : null;
2340
+ };
2341
+ var CONSENT_SESSION_START_PATH2 = "/v1/consent-session";
2342
+ var CONSENT_SESSION_CONSENT_PATH2 = "/v1/consent-session/consent";
2343
+ var CONSENT_SESSION_HEARTBEAT_PATH2 = "/v1/consent-session/heartbeat";
2344
+ var CONSENT_SESSION_TRIGGER_VERIFICATION_CODE_PATH2 = "/v1/consent-session/trigger-verification-code";
2345
+ var CONSENT_SESSION_SUBMIT_VERIFICATION_CODE_PATH2 = "/v1/consent-session/submit-verification-code";
2346
+ var CONSENT_SESSION_SUBMIT_PATH2 = "/v1/consent-session/submit";
2347
+ var COUNTRY_NOT_FOUND_CODE2 = "COUNTRY_NOT_FOUND";
2348
+ var verificationErrorCodeFromBody2 = errorCodeFromBody2;
2349
+ var buildUpsertRequest2 = (args) => ({
2350
+ identifier: args.identifier,
2351
+ identifierType: args.identifierType,
2352
+ locale: args.locale,
2353
+ ...args.userIp ? { userIp: args.userIp } : {},
2354
+ ...args.format ? { format: args.format } : {},
2355
+ integration: {
2356
+ ...args.context,
2357
+ type: args.integrationType
2358
+ }
2359
+ });
2360
+ var isCountryNotFound2 = (error) => error.status === 422 && error.code === COUNTRY_NOT_FOUND_CODE2;
2361
+ var emptyUpsertResponse2 = () => ({
2362
+ consentSessionId: null,
2363
+ consents: [],
2364
+ userVerificationRequired: null,
2365
+ lastHeartbeat: null,
2366
+ identifier: null
2367
+ });
2368
+ var buildSaveConsentRequest2 = (args) => ({
2369
+ consentSessionId: args.consentSessionId,
2370
+ channel: args.channel,
2371
+ consent: args.consent
2372
+ });
2373
+ var buildHeartbeatRequest2 = (args) => ({
2374
+ consentSessionId: args.consentSessionId
2375
+ });
2376
+ var buildTriggerVerificationCodeRequest2 = (args) => ({
2377
+ consentSessionId: args.consentSessionId
2378
+ });
2379
+ var buildSubmitVerificationCodeRequest2 = (args) => ({
2380
+ consentSessionId: args.consentSessionId,
2381
+ verificationCode: args.verificationCode,
2382
+ referenceId: args.referenceId
2383
+ });
2384
+ var buildSubmitRequest2 = (args) => {
2385
+ const details = { ...args.details };
2386
+ if (details.submittedAt instanceof Date) details.submittedAt = details.submittedAt.toISOString();
2387
+ if (typeof details.billingCountryCode === "string") {
2388
+ details.billingCountryCode = details.billingCountryCode.trim().toUpperCase();
2389
+ }
2390
+ const omitUser = args.user === void 0 && args.requiresUser === false;
2391
+ return {
2392
+ datashipsSessionId: args.datashipsSessionId,
2393
+ ...omitUser ? {} : { user: normaliseSubmitUser2(args.user) },
2394
+ integration: { ...details, type: args.integrationType }
2395
+ };
2396
+ };
2397
+ var normaliseSubmitUser2 = (user) => {
2398
+ const firstName = user?.firstName?.trim() ?? "";
2399
+ const lastName = user?.lastName?.trim() ?? "";
2400
+ if (!firstName || !lastName) {
2401
+ throw new Error(
2402
+ "submitSession: user.firstName and user.lastName are required (core-api refuses a blank name)"
2403
+ );
2404
+ }
2405
+ return { firstName, lastName };
2406
+ };
2407
+ var upsertSession2 = async (args) => {
2408
+ const { adapter, input } = args;
2409
+ const identifier = input.identifier ?? (await adapter.getIdentifier(input.identifierType)).identifier;
2410
+ const context = await adapter.getSessionContext();
2411
+ const body = buildUpsertRequest2({
2412
+ integrationType: adapter.integrationType,
2413
+ locale: adapter.getLocale(),
2414
+ identifier,
2415
+ identifierType: input.identifierType,
2416
+ userIp: input.userIp,
2417
+ format: input.format,
2418
+ context
2419
+ });
2420
+ try {
2421
+ const response = await args.post({
2422
+ path: CONSENT_SESSION_START_PATH2,
2423
+ body,
2424
+ retry: args.retry
2425
+ });
2426
+ return response ?? emptyUpsertResponse2();
2427
+ } catch (error) {
2428
+ if (error instanceof DatashipsError2 && isCountryNotFound2(error)) {
2429
+ return emptyUpsertResponse2();
2430
+ }
2431
+ throw error;
2432
+ }
2433
+ };
2434
+ var saveConsent2 = (args) => args.post({
2435
+ path: CONSENT_SESSION_CONSENT_PATH2,
2436
+ body: buildSaveConsentRequest2({
2437
+ consentSessionId: args.consentSessionId,
2438
+ channel: args.channel,
2439
+ consent: args.consent
2440
+ }),
2441
+ retry: args.retry
2442
+ });
2443
+ var heartbeat2 = (args) => args.post({
2444
+ path: CONSENT_SESSION_HEARTBEAT_PATH2,
2445
+ body: buildHeartbeatRequest2({ consentSessionId: args.consentSessionId }),
2446
+ retry: args.retry
2447
+ });
2448
+ var triggerVerificationCode2 = (args) => args.post({
2449
+ path: CONSENT_SESSION_TRIGGER_VERIFICATION_CODE_PATH2,
2450
+ body: buildTriggerVerificationCodeRequest2({
2451
+ consentSessionId: args.consentSessionId
2452
+ }),
2453
+ retry: noRetryPolicy2
2454
+ });
2455
+ var submitVerificationCode2 = async (args) => {
2456
+ try {
2457
+ await args.post({
2458
+ path: CONSENT_SESSION_SUBMIT_VERIFICATION_CODE_PATH2,
2459
+ body: buildSubmitVerificationCodeRequest2({
2460
+ consentSessionId: args.consentSessionId,
2461
+ verificationCode: args.verificationCode,
2462
+ referenceId: args.referenceId
2463
+ }),
2464
+ retry: noRetryPolicy2
2465
+ });
2466
+ return { verified: true, errorCode: null };
2467
+ } catch (error) {
2468
+ if (error instanceof DatashipsError2 && error.status === 400) {
2469
+ return {
2470
+ verified: false,
2471
+ errorCode: verificationErrorCodeFromBody2(error.body)
2472
+ };
2473
+ }
2474
+ throw error;
2475
+ }
2476
+ };
2477
+ var submitSession2 = async (args) => {
2478
+ const { adapter, input } = args;
2479
+ const datashipsSessionId = input.datashipsSessionId ?? adapter.getDatashipsSessionId?.();
2480
+ if (!datashipsSessionId) {
2481
+ throw new Error(
2482
+ "submitSession: datashipsSessionId is required; this adapter holds no beacon of its own"
2483
+ );
2484
+ }
2485
+ await args.post({
2486
+ path: CONSENT_SESSION_SUBMIT_PATH2,
2487
+ body: buildSubmitRequest2({
2488
+ datashipsSessionId,
2489
+ integrationType: adapter.integrationType,
2490
+ user: input.user,
2491
+ details: input.details,
2492
+ requiresUser: adapter.submitRequiresUser
2493
+ }),
2494
+ retry: args.retry
2495
+ });
2496
+ if (input.datashipsSessionId === void 0 && input.resetBeacon !== false) {
2497
+ adapter.resetDatashipsSessionId?.();
2498
+ }
2499
+ };
2500
+ var postJson2 = async ({
2501
+ url,
2502
+ headers,
2503
+ body,
2504
+ fetch,
2505
+ retry
2506
+ }) => {
2507
+ let attempt = 0;
2508
+ while (true) {
2509
+ let response;
2510
+ let networkError;
2511
+ const attemptHeaders = typeof headers === "function" ? await headers() : headers;
2512
+ try {
2513
+ response = await fetch(url, {
2514
+ method: "POST",
2515
+ headers: { "Content-Type": "application/json", ...attemptHeaders },
2516
+ body: JSON.stringify(body)
2517
+ });
2518
+ } catch (err) {
2519
+ networkError = err;
2520
+ }
2521
+ const status = response?.status;
2522
+ const ok = response?.ok ?? false;
2523
+ if (ok && response) {
2524
+ const text = await response.text();
2525
+ return text ? JSON.parse(text) : void 0;
2526
+ }
2527
+ const errorBody = response ? await readBody2(response) : null;
2528
+ const errorCode = errorCodeFromBody2(errorBody) ?? void 0;
2529
+ if (!retry.shouldRetry(attempt, status, errorCode)) {
2530
+ if (networkError) throw networkError;
2531
+ throw new DatashipsError2({
2532
+ status: status ?? 0,
2533
+ body: errorBody,
2534
+ challenge: response?.headers.get("WWW-Authenticate") ?? null
2535
+ });
2536
+ }
2537
+ attempt += 1;
2538
+ const delay = retry.delayMs(attempt);
2539
+ if (delay > 0) await new Promise((r) => setTimeout(r, delay));
2540
+ }
2541
+ };
2542
+ var readBody2 = async (response) => {
2543
+ const text = await response.text();
2544
+ if (!text) return null;
2545
+ try {
2546
+ return JSON.parse(text);
2547
+ } catch {
2548
+ return text;
2549
+ }
2550
+ };
2551
+ var DEFAULT_HEARTBEAT_INTERVAL_MS2 = 210 * 1e3;
2552
+ var DEFAULT_HEARTBEAT_DURATION_MS2 = 10 * 60 * 1e3;
2553
+ var _auth2;
2554
+ var _fetch2;
2555
+ var _upsertSessionRetry2;
2556
+ var _defaultRetry2;
2557
+ var _DatashipsClient_instances2;
2558
+ var previewUpsertResponse_fn2;
2559
+ var credentialHeaders_fn2;
2560
+ var requireAuth_fn2;
2561
+ var requireConsentSessionId_fn2;
2562
+ var sendHeartbeat_fn2;
2563
+ var post_fn2;
2564
+ var send_fn;
2565
+ var DatashipsClient2 = class {
2566
+ constructor(opts) {
2567
+ __privateAdd5(this, _DatashipsClient_instances2);
2568
+ __privateAdd5(this, _auth2);
2569
+ __privateAdd5(this, _fetch2);
2570
+ __privateAdd5(this, _upsertSessionRetry2);
2571
+ __privateAdd5(this, _defaultRetry2);
2572
+ this.adapter = opts.adapter;
2573
+ if (opts.auth) assertBrowserAuth2(opts.auth);
2574
+ if (!opts.auth && !opts.adapter.previewMode) {
2575
+ throw new Error(
2576
+ "DatashipsClient: `auth: { publicKey, token }` (or `{ publicKey, getToken }`) is required unless the adapter runs in preview mode"
2577
+ );
2578
+ }
2579
+ this.publicKey = opts.auth && !isUnsafeServerKeyAuth2(opts.auth) ? opts.auth.publicKey : null;
2580
+ __privateSet5(this, _auth2, opts.auth ?? null);
2581
+ this.app = opts.app;
2582
+ this.version = opts.version;
2583
+ this.baseUrl = resolveBaseUrl2(opts.env, opts.baseUrl);
2584
+ __privateSet5(this, _fetch2, opts.fetch ?? globalThis.fetch.bind(globalThis));
2585
+ __privateSet5(this, _upsertSessionRetry2, opts.retry?.upsertSession ?? upsertSessionRetryPolicy2);
2586
+ __privateSet5(this, _defaultRetry2, opts.retry?.default ?? defaultRetryPolicy2);
2587
+ }
2588
+ /** The credentials in use, or null for a preview-mode client constructed without them. */
2589
+ get auth() {
2590
+ return __privateGet5(this, _auth2);
2591
+ }
2592
+ /** Whether this client runs on the unsafe server-key escape hatch. */
2593
+ get isUnsafeServerKey() {
2594
+ return __privateGet5(this, _auth2) !== null && isUnsafeServerKeyAuth2(__privateGet5(this, _auth2));
2595
+ }
2596
+ /**
2597
+ * Replace the Bearer token before it expires. The next call and any running
2598
+ * heartbeat use it; a missed rotation surfaces as a 401 on the next call.
2599
+ * Not applicable under `auth.getToken`, which already fetches one per request.
2600
+ */
2601
+ setToken(token) {
2602
+ if (!__privateGet5(this, _auth2)) {
2603
+ throw new Error(
2604
+ "DatashipsClient: setToken() requires a client constructed with `auth`"
2605
+ );
2606
+ }
2607
+ if (isUnsafeServerKeyAuth2(__privateGet5(this, _auth2))) {
2608
+ throw new Error(
2609
+ "DatashipsClient: setToken() does not apply under auth.unsafeServerKey; there is no token to rotate"
2610
+ );
2611
+ }
2612
+ if (isTokenProviderAuth2(__privateGet5(this, _auth2))) {
2613
+ throw new Error(
2614
+ "DatashipsClient: setToken() does not apply under auth.getToken; the provider is called before every request"
2615
+ );
2616
+ }
2617
+ if (!token) {
2618
+ throw new Error("DatashipsClient: token must be a non-empty string");
2619
+ }
2620
+ __privateSet5(this, _auth2, { ...__privateGet5(this, _auth2), token });
2621
+ }
2622
+ /**
2623
+ * Open or update the consent session for one identifier type
2624
+ * (`POST /v1/consent-session`, contract v2). The client only states which
2625
+ * identifier type it holds; the server decides the channels and returns one
2626
+ * entry per channel to render. An empty `consents` means render nothing:
2627
+ * that also covers a 204 No Content (a surface that never collects, no
2628
+ * eligible channel, or a checkout that already asked on an earlier step) and
2629
+ * a user IP the API could not geolocate (422 COUNTRY_NOT_FOUND), both of
2630
+ * which resolve instead of throwing.
2631
+ */
2632
+ async upsertSession(input) {
2633
+ const preview = __privateMethod5(this, _DatashipsClient_instances2, previewUpsertResponse_fn2).call(this, input.identifierType, input.format);
2634
+ if (preview) return preview;
2635
+ return upsertSession2({
2636
+ adapter: this.adapter,
2637
+ input,
2638
+ post: __privateMethod5(this, _DatashipsClient_instances2, post_fn2).bind(this),
2639
+ retry: __privateGet5(this, _upsertSessionRetry2)
2640
+ });
2641
+ }
2642
+ async saveConsent(input) {
2643
+ if (this.adapter.previewMode) return;
2644
+ await saveConsent2({
2645
+ consentSessionId: __privateMethod5(this, _DatashipsClient_instances2, requireConsentSessionId_fn2).call(this, input.session),
2646
+ channel: input.channel,
2647
+ consent: input.consent,
2648
+ post: __privateMethod5(this, _DatashipsClient_instances2, post_fn2).bind(this),
2649
+ retry: __privateGet5(this, _defaultRetry2)
2650
+ });
2651
+ }
2652
+ /**
2653
+ * Ask the backend to send an OTP verification code to the phone-channel
2654
+ * session's number. `referenceId` must be echoed back on
2655
+ * {@link submitVerificationCode}. Never retried — a retry could send the
2656
+ * buyer duplicate codes.
2657
+ *
2658
+ * In preview mode no code is sent and `{ userVerificationTriggered: false }` is
2659
+ * returned, mirroring a store without verification enabled.
2660
+ */
2661
+ async triggerVerificationCode(input) {
2662
+ if (this.adapter.previewMode) {
2663
+ return {
2664
+ userVerificationTriggered: false,
2665
+ referenceId: null,
2666
+ codeLength: null,
2667
+ resendAfterSeconds: null
2668
+ };
2669
+ }
2670
+ return triggerVerificationCode2({
2671
+ consentSessionId: input.consentSessionId,
2672
+ post: __privateMethod5(this, _DatashipsClient_instances2, post_fn2).bind(this)
2673
+ });
2674
+ }
2675
+ /**
2676
+ * Submit the OTP code the buyer received. Resolves
2677
+ * `{ verified: true, errorCode: null }` on 2xx. A 400 rejection resolves
2678
+ * `{ verified: false, errorCode }` with the body's `errors[0].code` (see
2679
+ * `SUBMIT_VERIFICATION_CODE_ERROR_CODES`), or `null` when the body carries
2680
+ * none. Any other failure throws. Never retried — a rejection is definitive.
2681
+ *
2682
+ * In preview mode resolves verified without a network call.
2683
+ */
2684
+ async submitVerificationCode(input) {
2685
+ if (this.adapter.previewMode) return { verified: true, errorCode: null };
2686
+ return submitVerificationCode2({
2687
+ ...input,
2688
+ post: __privateMethod5(this, _DatashipsClient_instances2, post_fn2).bind(this)
2689
+ });
2690
+ }
2691
+ /**
2692
+ * Complete the sessions opened under a beacon: the placed order (or the
2693
+ * flow's equivalent) lands on every sibling session and processing is
2694
+ * queued (`POST /v1/consent-session/submit`).
2695
+ *
2696
+ * `user.firstName` / `lastName` are required (the backend refuses a blank
2697
+ * name; the SDK refuses it before sending), unless the adapter's
2698
+ * `submitRequiresUser` is false, as on the Alia form adapters: then `user` may be
2699
+ * omitted and the submit goes without it. The beacon defaults to the
2700
+ * adapter's own `datashipsSessionId`, which is then discarded once the
2701
+ * submit is accepted. Idempotent on the backend; a
2702
+ * beacon that matches no session is accepted silently. Retried on 409 and
2703
+ * server errors like any other call.
2704
+ *
2705
+ * In preview mode nothing is sent; the beacon is still discarded so a
2706
+ * styled sandbox behaves like a real checkout.
2707
+ */
2708
+ async submitSession(input) {
2709
+ const adapter = this.adapter;
2710
+ if (adapter.previewMode) {
2711
+ if (input.datashipsSessionId === void 0 && input.resetBeacon !== false) {
2712
+ adapter.resetDatashipsSessionId?.();
2713
+ }
2714
+ return;
2715
+ }
2716
+ await submitSession2({
2717
+ adapter,
2718
+ input,
2719
+ post: __privateMethod5(this, _DatashipsClient_instances2, post_fn2).bind(this),
2720
+ retry: __privateGet5(this, _defaultRetry2)
2721
+ });
2722
+ }
2723
+ /**
2724
+ * Begin a periodic heartbeat. Returns an idempotent stop function. The
2725
+ * scheduler stops itself at the duration limit, when the credential is
2726
+ * refused (401 / 403) and when the session has already been processed; every
2727
+ * failure is reported through `onError`.
2728
+ */
2729
+ startHeartbeat(session, opts = {}) {
2730
+ if (this.adapter.previewMode) return () => {
2731
+ };
2732
+ const intervalMs = opts.intervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS2;
2733
+ const durationMs = opts.durationMs ?? DEFAULT_HEARTBEAT_DURATION_MS2;
2734
+ const startedAt = Date.now();
2735
+ let stopped = false;
2736
+ const stop = () => {
2737
+ if (stopped) return;
2738
+ stopped = true;
2739
+ clearInterval(handle);
2740
+ };
2741
+ const handle = setInterval(() => {
2742
+ if (Date.now() - startedAt >= durationMs) {
2743
+ stop();
2744
+ return;
2745
+ }
2746
+ __privateMethod5(this, _DatashipsClient_instances2, sendHeartbeat_fn2).call(this, session).catch((error) => {
2747
+ opts.onError?.(error);
2748
+ if (error instanceof DatashipsError2 && (error.isAuthenticationFailure || error.isSessionProcessed)) {
2749
+ stop();
2750
+ }
2751
+ });
2752
+ }, intervalMs);
2753
+ return stop;
2754
+ }
2755
+ };
2756
+ _auth2 = /* @__PURE__ */ new WeakMap();
2757
+ _fetch2 = /* @__PURE__ */ new WeakMap();
2758
+ _upsertSessionRetry2 = /* @__PURE__ */ new WeakMap();
2759
+ _defaultRetry2 = /* @__PURE__ */ new WeakMap();
2760
+ _DatashipsClient_instances2 = /* @__PURE__ */ new WeakSet();
2761
+ previewUpsertResponse_fn2 = function(identifierType, format) {
2762
+ if (this.adapter.previewMode && this.adapter.getPreviewUpsertResponse) {
2763
+ return this.adapter.getPreviewUpsertResponse(identifierType, format);
2764
+ }
2765
+ return null;
2766
+ };
2767
+ credentialHeaders_fn2 = async function() {
2768
+ const auth = __privateMethod5(this, _DatashipsClient_instances2, requireAuth_fn2).call(this);
2769
+ return authHeaders2(
2770
+ isTokenProviderAuth2(auth) ? await resolveTokenProviderAuth2(auth) : auth
2771
+ );
2772
+ };
2773
+ requireAuth_fn2 = function() {
2774
+ if (!__privateGet5(this, _auth2)) {
2775
+ throw new Error(
2776
+ "DatashipsClient: no credentials configured; pass `auth: { publicKey, token }`"
2777
+ );
2778
+ }
2779
+ return __privateGet5(this, _auth2);
2780
+ };
2781
+ requireConsentSessionId_fn2 = function(session) {
2782
+ if (!session.consentSessionId) {
2783
+ throw new Error(
2784
+ "DatashipsClient: consentSessionId is required"
2785
+ );
2786
+ }
2787
+ return session.consentSessionId;
2788
+ };
2789
+ sendHeartbeat_fn2 = async function(session) {
2790
+ await heartbeat2({
2791
+ consentSessionId: __privateMethod5(this, _DatashipsClient_instances2, requireConsentSessionId_fn2).call(this, session),
2792
+ post: __privateMethod5(this, _DatashipsClient_instances2, post_fn2).bind(this),
2793
+ retry: __privateGet5(this, _defaultRetry2)
2794
+ });
2795
+ };
2796
+ post_fn2 = async function(args) {
2797
+ try {
2798
+ return await __privateMethod5(this, _DatashipsClient_instances2, send_fn).call(this, args);
2799
+ } catch (error) {
2800
+ const auth = __privateGet5(this, _auth2);
2801
+ if (!(error instanceof DatashipsError2) || error.status !== 401 || !auth || !isTokenProviderAuth2(auth) || !auth.onUnauthorized) {
2802
+ throw error;
2803
+ }
2804
+ let credentials;
2805
+ try {
2806
+ await auth.onUnauthorized();
2807
+ credentials = await __privateMethod5(this, _DatashipsClient_instances2, credentialHeaders_fn2).call(this);
2808
+ } catch {
2809
+ throw error;
2810
+ }
2811
+ return __privateMethod5(this, _DatashipsClient_instances2, send_fn).call(this, { ...args, retry: noRetryPolicy2 }, credentials);
2812
+ }
2813
+ };
2814
+ send_fn = async function(args, credentials) {
2815
+ let pending = credentials;
2816
+ const staticHeaders = {
2817
+ // The marker lets the backend tell an exposed key in a page from a genuine server call.
2818
+ "X-Dataships-App": `${this.app} (SDK: ${this.adapter.name}${this.isUnsafeServerKey ? `; ${UNSAFE_SERVER_KEY_APP_MARKER2}` : ""})`,
2819
+ "X-Dataships-Version": `${this.version} (SDK: ${"2.5.0"})`
2820
+ };
2821
+ return postJson2({
2822
+ url: `${this.baseUrl}${args.path}`,
2823
+ // Resolved per attempt so a token provider hands every retry a fresh token.
2824
+ headers: async () => {
2825
+ const resolved = pending ?? await __privateMethod5(this, _DatashipsClient_instances2, credentialHeaders_fn2).call(this);
2826
+ pending = void 0;
2827
+ return { ...resolved, ...staticHeaders };
2828
+ },
2829
+ body: args.body,
2830
+ fetch: __privateGet5(this, _fetch2),
2831
+ retry: args.retry
2832
+ });
2833
+ };
2834
+
2835
+ // node_modules/@dataships/sdk/dist/adapters/alia-form/index.js
2836
+ var __typeError6 = (msg) => {
2837
+ throw TypeError(msg);
2838
+ };
2839
+ var __accessCheck6 = (obj, member, msg) => member.has(obj) || __typeError6("Cannot " + msg);
2840
+ var __privateGet6 = (obj, member, getter) => (__accessCheck6(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
2841
+ var __privateAdd6 = (obj, member, value) => member.has(obj) ? __typeError6("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2842
+ var __privateSet6 = (obj, member, value, setter) => (__accessCheck6(obj, member, "write to private field"), member.set(obj, value), value);
2199
2843
  var DEFAULT_EMAIL_OPT_IN_TEXT3 = "We would like to email you news and promotions. Tick to opt in.";
2200
2844
  var DEFAULT_EMAIL_OPT_IN_CONSENT_DESCRIPTION3 = "Click here for an overview of how your personal data is processed for marketing purposes or see our Privacy Policy for further information.";
2201
2845
  var DEFAULT_SMS_OPT_IN_TEXT3 = "We would like to text you news and promotions. Tick to opt in.";
@@ -2328,19 +2972,19 @@ var AliaFormAdapterBase = class {
2328
2972
  constructor(adapterName, opts) {
2329
2973
  this.sessionApi = "consent-session";
2330
2974
  this.submitRequiresUser = false;
2331
- __privateAdd5(this, _datashipsSessionId);
2332
- __privateAdd5(this, _campaignId);
2333
- __privateAdd5(this, _locale3);
2334
- __privateSet5(this, _datashipsSessionId, required(adapterName, opts.datashipsSessionId, "datashipsSessionId"));
2335
- __privateSet5(this, _campaignId, required(adapterName, opts.campaignId, "campaignId"));
2336
- __privateSet5(this, _locale3, coerceLocale3(opts.locale));
2975
+ __privateAdd6(this, _datashipsSessionId);
2976
+ __privateAdd6(this, _campaignId);
2977
+ __privateAdd6(this, _locale3);
2978
+ __privateSet6(this, _datashipsSessionId, required(adapterName, opts.datashipsSessionId, "datashipsSessionId"));
2979
+ __privateSet6(this, _campaignId, required(adapterName, opts.campaignId, "campaignId"));
2980
+ __privateSet6(this, _locale3, coerceLocale3(opts.locale));
2337
2981
  }
2338
2982
  getLocale() {
2339
- return __privateGet5(this, _locale3);
2983
+ return __privateGet6(this, _locale3);
2340
2984
  }
2341
2985
  /** Change the envelope locale, e.g. when the visitor switches language. */
2342
2986
  setLocale(locale) {
2343
- __privateSet5(this, _locale3, coerceLocale3(locale));
2987
+ __privateSet6(this, _locale3, coerceLocale3(locale));
2344
2988
  }
2345
2989
  /** The adapter holds no contact: the popup's field is passed to `upsertSession({ identifier })`. */
2346
2990
  getIdentifier(identifierType) {
@@ -2348,10 +2992,10 @@ var AliaFormAdapterBase = class {
2348
2992
  }
2349
2993
  /** The id the adapter was given; a submit leaves it in place. */
2350
2994
  getDatashipsSessionId() {
2351
- return __privateGet5(this, _datashipsSessionId);
2995
+ return __privateGet6(this, _datashipsSessionId);
2352
2996
  }
2353
2997
  baseSessionContext() {
2354
- return { datashipsSessionId: __privateGet5(this, _datashipsSessionId), campaignId: __privateGet5(this, _campaignId) };
2998
+ return { datashipsSessionId: __privateGet6(this, _datashipsSessionId), campaignId: __privateGet6(this, _campaignId) };
2355
2999
  }
2356
3000
  };
2357
3001
  _datashipsSessionId = /* @__PURE__ */ new WeakMap();
@@ -2380,19 +3024,19 @@ var AliaFormListenAdapter = class extends AliaFormAdapterBase {
2380
3024
  super("AliaFormListenAdapter", opts);
2381
3025
  this.name = "AliaFormListenAdapter";
2382
3026
  this.integrationType = ALIA_FORM_LISTEN_INTEGRATION_TYPE;
2383
- __privateAdd5(this, _disclosureText);
2384
- __privateAdd5(this, _privacyPolicyUrl);
2385
- __privateAdd5(this, _termsUrl);
2386
- __privateSet5(this, _disclosureText, optional(opts.disclosureText));
2387
- __privateSet5(this, _privacyPolicyUrl, optional(opts.privacyPolicyUrl));
2388
- __privateSet5(this, _termsUrl, optional(opts.termsUrl));
3027
+ __privateAdd6(this, _disclosureText);
3028
+ __privateAdd6(this, _privacyPolicyUrl);
3029
+ __privateAdd6(this, _termsUrl);
3030
+ __privateSet6(this, _disclosureText, optional(opts.disclosureText));
3031
+ __privateSet6(this, _privacyPolicyUrl, optional(opts.privacyPolicyUrl));
3032
+ __privateSet6(this, _termsUrl, optional(opts.termsUrl));
2389
3033
  }
2390
3034
  async getSessionContext() {
2391
3035
  return {
2392
3036
  ...this.baseSessionContext(),
2393
- ...__privateGet5(this, _disclosureText) === void 0 ? {} : { disclosureText: __privateGet5(this, _disclosureText) },
2394
- ...__privateGet5(this, _privacyPolicyUrl) === void 0 ? {} : { privacyPolicyUrl: __privateGet5(this, _privacyPolicyUrl) },
2395
- ...__privateGet5(this, _termsUrl) === void 0 ? {} : { termsUrl: __privateGet5(this, _termsUrl) }
3037
+ ...__privateGet6(this, _disclosureText) === void 0 ? {} : { disclosureText: __privateGet6(this, _disclosureText) },
3038
+ ...__privateGet6(this, _privacyPolicyUrl) === void 0 ? {} : { privacyPolicyUrl: __privateGet6(this, _privacyPolicyUrl) },
3039
+ ...__privateGet6(this, _termsUrl) === void 0 ? {} : { termsUrl: __privateGet6(this, _termsUrl) }
2396
3040
  };
2397
3041
  }
2398
3042
  };
@@ -2619,7 +3263,7 @@ var watchPopups = (context, deps) => {
2619
3263
  datashipsSessionId: context.datashipsSessionId,
2620
3264
  publicKey: context.publicKey,
2621
3265
  baseUrl: context.baseUrl,
2622
- token: context.token,
3266
+ auth: context.auth,
2623
3267
  preview: context.preview
2624
3268
  });
2625
3269
  const hideOwnText = (handle, ownText, shadow) => {
@@ -2659,6 +3303,8 @@ var watchPopups = (context, deps) => {
2659
3303
  position: "after",
2660
3304
  ...step,
2661
3305
  className: source ? classOf(source) : COMPLIANCE_CLASS,
3306
+ // Elements labels the widget as a preview only when told.
3307
+ preview: context.preview,
2662
3308
  ...shadow ? { root: shadow } : {},
2663
3309
  // The submit names the campaign, because one session id can hold several campaigns'
2664
3310
  // sessions, and the step's identifier type, so it completes this step's session only
@@ -2740,7 +3386,7 @@ var watchPopups = (context, deps) => {
2740
3386
  popup.sms = { kind: "render", handle, retag: true };
2741
3387
  };
2742
3388
  const listenSms = (root) => {
2743
- const token = context.token;
3389
+ const auth = context.auth;
2744
3390
  const datashipsSessionId = context.datashipsSessionId;
2745
3391
  const disclosure = readSmsDisclosure(root);
2746
3392
  const shown = disclosure.kind === "unreadable" ? [] : elementsOf(root, [
@@ -2748,7 +3394,7 @@ var watchPopups = (context, deps) => {
2748
3394
  ...disclosure.ownText
2749
3395
  ]);
2750
3396
  const disclosureText = textOf(shown);
2751
- if (disclosure.kind === "unreadable" || !token || !datashipsSessionId) {
3397
+ if (disclosure.kind === "unreadable" || !auth || !datashipsSessionId) {
2752
3398
  popup.sms = { kind: "none" };
2753
3399
  return;
2754
3400
  }
@@ -2759,7 +3405,7 @@ var watchPopups = (context, deps) => {
2759
3405
  datashipsSessionId,
2760
3406
  publicKey: context.publicKey,
2761
3407
  baseUrl: context.baseUrl,
2762
- token,
3408
+ auth,
2763
3409
  ...disclosureText ? { disclosureText } : {},
2764
3410
  ...privacyPolicyUrl ? { privacyPolicyUrl } : {},
2765
3411
  ...termsUrl ? { termsUrl } : {}
@@ -2828,7 +3474,7 @@ var watchPopups = (context, deps) => {
2828
3474
  const campaignId = idOf(detail.campaignID);
2829
3475
  if (!popupId || !campaignId || popups.has(popupId)) return;
2830
3476
  if (!context.preview) {
2831
- if (!context.token || !context.elements.some((element) => element.id === campaignId))
3477
+ if (!context.auth || !context.elements.some((element) => element.id === campaignId))
2832
3478
  return;
2833
3479
  }
2834
3480
  track(popupId, campaignId);
@@ -2873,15 +3519,21 @@ var createRenderClient = (options) => {
2873
3519
  campaignId: options.campaignId,
2874
3520
  previewMode: options.preview
2875
3521
  });
2876
- return new DatashipsClient({
3522
+ return new DatashipsClient2({
2877
3523
  adapter,
2878
3524
  app: "launcher",
2879
- version: "0.2.0",
3525
+ version: "0.3.1",
2880
3526
  baseUrl: options.baseUrl,
2881
- ...options.token ? { auth: { publicKey: options.publicKey, token: options.token } } : {}
3527
+ ...options.auth ? {
3528
+ auth: {
3529
+ publicKey: options.publicKey,
3530
+ getToken: options.auth.getToken,
3531
+ onUnauthorized: options.auth.onUnauthorized
3532
+ }
3533
+ } : {}
2882
3534
  });
2883
3535
  };
2884
- var createListenClient = (options) => new DatashipsClient({
3536
+ var createListenClient = (options) => new DatashipsClient2({
2885
3537
  adapter: new AliaFormListenAdapter({
2886
3538
  datashipsSessionId: options.datashipsSessionId,
2887
3539
  campaignId: options.campaignId,
@@ -2890,9 +3542,13 @@ var createListenClient = (options) => new DatashipsClient({
2890
3542
  ...options.termsUrl ? { termsUrl: options.termsUrl } : {}
2891
3543
  }),
2892
3544
  app: "launcher",
2893
- version: "0.2.0",
3545
+ version: "0.3.1",
2894
3546
  baseUrl: options.baseUrl,
2895
- auth: { publicKey: options.publicKey, token: options.token }
3547
+ auth: {
3548
+ publicKey: options.publicKey,
3549
+ getToken: options.auth.getToken,
3550
+ onUnauthorized: options.auth.onUnauthorized
3551
+ }
2896
3552
  });
2897
3553
  var start = (context) => {
2898
3554
  watchPopups(context, { mount, createRenderClient, createListenClient });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dataships/launcher",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "Dataships Launcher — the one storefront script. Reads the public key from its script tag, asks the Dataships API what to render and loads the matching module.",
5
5
  "private": false,
6
6
  "license": "Apache-2.0",
@@ -33,8 +33,8 @@
33
33
  "smoke:cdn": "node scripts/smoke-cdn.mjs"
34
34
  },
35
35
  "devDependencies": {
36
- "@dataships/elements": "2.5.0",
37
- "@dataships/sdk": "2.4.0",
36
+ "@dataships/elements": "2.7.0",
37
+ "@dataships/sdk": "2.5.0",
38
38
  "@types/node": "^20.12.11",
39
39
  "@typescript-eslint/eslint-plugin": "^7.0.0",
40
40
  "@typescript-eslint/parser": "^7.0.0",