@dataships/launcher 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
1
  {
2
- "launcher.js": "sha384-NtsTZ3C4YYlHLFrA9Vhx+BCmNFi87xmxKTYVCpAu5c/Py1iksefAd23uE2cp4+6C",
3
- "modules/alia-0.1.1.js": "sha384-G7MwLc6JmBZs6MoTSvHuVj98jJqGIw8lyrn6l2QB6wxmo5/IuSeoFJhgJWhA31Pt"
2
+ "launcher.js": "sha384-vwZeTLLmB6BK/WHxTbkMlHNo/f4TwOZGpTFhCMZdC7bA/LKSl7/Q9jlV6KB6hXLx",
3
+ "modules/alia-0.3.0.js": "sha384-xT/0dMdBCmn66PCdLNkknVwj2piQlxI2mc/AjrjFgbBLhXg776dyJRWNftzCB1+N"
4
4
  }
package/dist/launcher.js CHANGED
@@ -12,6 +12,19 @@
12
12
  // src/elementsApi.ts
13
13
  var ELEMENTS_PATH = "/v1/elements";
14
14
  var isNonEmptyString = (value) => typeof value === "string" && value.length > 0;
15
+ var parseChannels = (value) => {
16
+ if (value === void 0) return [];
17
+ if (!Array.isArray(value)) return null;
18
+ const channels = [];
19
+ for (const entry of value) {
20
+ if (typeof entry !== "object" || entry === null) return null;
21
+ const { channel, subscriptionType } = entry;
22
+ if (!isNonEmptyString(channel) || !isNonEmptyString(subscriptionType))
23
+ return null;
24
+ channels.push({ channel, subscriptionType });
25
+ }
26
+ return channels;
27
+ };
15
28
  var parseElements = (body) => {
16
29
  if (typeof body !== "object" || body === null) return null;
17
30
  const { datashipsSessionId, token, elements } = body;
@@ -20,13 +33,32 @@
20
33
  const refs = [];
21
34
  for (const element of elements) {
22
35
  if (typeof element !== "object" || element === null) return null;
23
- const { type, id } = element;
36
+ const { type, id, channels } = element;
24
37
  if (!isNonEmptyString(type) || !isNonEmptyString(id)) return null;
25
- refs.push({ type, id });
38
+ const parsedChannels = parseChannels(channels);
39
+ if (!parsedChannels) return null;
40
+ refs.push({ type, id, channels: parsedChannels });
26
41
  }
27
42
  return { datashipsSessionId, token, elements: refs };
28
43
  };
29
- var idsOfType = (data, type) => data.elements.filter((element) => element.type === type).map((element) => element.id);
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
+ };
30
62
  var fetchElements = async (fetchFn, baseUrl, publicKey) => {
31
63
  try {
32
64
  const response = await fetchFn(`${baseUrl}${ELEMENTS_PATH}`, {
@@ -34,13 +66,12 @@
34
66
  headers: { "x-api-key": publicKey },
35
67
  credentials: "omit"
36
68
  });
37
- if (response.status === 403) return { status: "refused" };
38
- if (response.status !== 200) return { status: "failed" };
39
- const data = parseElements(await response.json());
40
- if (!data) return { status: "failed" };
41
- return data.elements.length === 0 ? { status: "refused" } : { status: "ok", data };
69
+ return {
70
+ outcome: await outcomeOf(response),
71
+ maxAgeMs: maxAgeMsOf(response)
72
+ };
42
73
  } catch {
43
- return { status: "failed" };
74
+ return { outcome: { status: "failed" }, maxAgeMs: 0 };
44
75
  }
45
76
  };
46
77
 
@@ -62,18 +93,21 @@
62
93
  const entry = JSON.parse(raw);
63
94
  if (typeof entry.at !== "number" || now < entry.at || now - entry.at >= CACHE_TTL_MS)
64
95
  return null;
65
- 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 };
66
100
  const data = entry.status === "ok" ? parseElements(entry.data) : null;
67
- return data && data.elements.length > 0 ? { status: "ok", data } : null;
101
+ return data && data.elements.length > 0 ? { answer: { status: "ok", data }, at, receivedAt } : null;
68
102
  } catch {
69
103
  return null;
70
104
  }
71
105
  }
72
- write(answer, now) {
106
+ write(answer, now, receivedAt = now) {
73
107
  try {
74
108
  __privateGet(this, _win).sessionStorage.setItem(
75
109
  __privateGet(this, _key),
76
- JSON.stringify({ at: now, ...answer })
110
+ JSON.stringify({ at: now, receivedAt, ...answer })
77
111
  );
78
112
  } catch {
79
113
  }
@@ -132,11 +166,98 @@
132
166
  var MODULES = [
133
167
  {
134
168
  type: "ALIA_FORM",
135
- file: `modules/alia-${"0.1.1"}.js`,
169
+ file: `modules/alia-${"0.3.0"}.js`,
136
170
  watch: watchAlia
137
171
  }
138
172
  ];
139
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
+
140
261
  // src/boot.ts
141
262
  var defaultImport = (url) => import(
142
263
  /* @vite-ignore */
@@ -154,7 +275,7 @@
154
275
  if (!config) return;
155
276
  const guard = win;
156
277
  if (guard.__datashipsLauncher) return;
157
- guard.__datashipsLauncher = { version: "0.1.1" };
278
+ guard.__datashipsLauncher = { version: "0.3.0" };
158
279
  const modules = env.modules ?? MODULES;
159
280
  const importModule = env.importModule ?? defaultImport;
160
281
  const load = (definition, context, beforeStart) => startModule(importModule, config, definition, context, beforeStart);
@@ -163,9 +284,9 @@
163
284
  publicKey: config.publicKey,
164
285
  baseUrl: config.baseUrl,
165
286
  preview: true,
166
- token: null,
287
+ auth: null,
167
288
  datashipsSessionId: null,
168
- campaignIds: [],
289
+ elements: [],
169
290
  events: []
170
291
  };
171
292
  await Promise.all(modules.map((definition) => load(definition, context)));
@@ -175,10 +296,28 @@
175
296
  definition,
176
297
  watch: definition.watch(win)
177
298
  }));
178
- 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;
179
316
  for (const { definition, watch } of watched) {
180
- const campaignIds = outcome.status === "ok" ? idsOfType(outcome.data, definition.type) : [];
181
- if (outcome.status !== "ok" || campaignIds.length === 0) {
317
+ const elements = outcome.status === "ok" ? elementsOfType(outcome.data, definition.type).map(
318
+ ({ id, channels }) => ({ id, channels })
319
+ ) : [];
320
+ if (outcome.status !== "ok" || elements.length === 0) {
182
321
  watch.stop();
183
322
  continue;
184
323
  }
@@ -186,27 +325,27 @@
186
325
  publicKey: config.publicKey,
187
326
  baseUrl: config.baseUrl,
188
327
  preview: false,
189
- token: outcome.data.token,
328
+ auth,
190
329
  datashipsSessionId: outcome.data.datashipsSessionId,
191
- campaignIds,
330
+ elements,
192
331
  events: watch.events
193
332
  };
194
333
  void watch.present.then(() => load(definition, context, watch.stop));
195
334
  }
196
335
  };
197
- var resolveElements = async (env, config) => {
198
- const now = env.now ?? Date.now;
199
- const cache = new ElementsCache(env.window, config.publicKey);
336
+ var resolveElements = async (win, fetchFn, now, config) => {
337
+ const cache = new ElementsCache(win, config.publicKey);
200
338
  const cached = cache.read(now());
201
- if (cached) return cached;
202
- const fetchFn = env.fetch ?? ((url, init) => env.window.fetch(url, init));
203
- const outcome = await fetchElements(
339
+ if (cached) return { outcome: cached.answer, receivedAt: cached.receivedAt };
340
+ const sentAt = now();
341
+ const { outcome, maxAgeMs } = await fetchElements(
204
342
  fetchFn,
205
343
  config.baseUrl,
206
344
  config.publicKey
207
345
  );
208
- if (outcome.status !== "failed") cache.write(outcome, now());
209
- return outcome;
346
+ const receivedAt = sentAt - maxAgeMs;
347
+ if (outcome.status !== "failed") cache.write(outcome, sentAt, receivedAt);
348
+ return { outcome, receivedAt };
210
349
  };
211
350
  var startModule = async (importModule, config, definition, context, beforeStart) => {
212
351
  try {