@wireai/activation 0.9.2 → 0.10.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.
package/dist/index.js CHANGED
@@ -1507,22 +1507,38 @@ var readProgress = (response) => {
1507
1507
 
1508
1508
  // src/analytics/reportClientEvent.ts
1509
1509
  var makeSessionId = () => `wire_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
1510
- var reportClientEvents = (target, events) => {
1511
- if (!(target == null ? void 0 : target.serverUrl) || events.length === 0) return;
1510
+ var buildEventsRequest = (target, events) => {
1511
+ if (!(target == null ? void 0 : target.serverUrl) || events.length === 0) return null;
1512
1512
  try {
1513
1513
  const url = `${target.serverUrl.replace(/\/$/, "")}/v1/events`;
1514
1514
  const headers = { "Content-Type": "application/json" };
1515
1515
  if (target.apiKey) headers.Authorization = `Bearer ${target.apiKey}`;
1516
- void fetch(url, {
1517
- method: "POST",
1518
- headers,
1519
- body: JSON.stringify({ events })
1520
- }).catch(() => {
1516
+ return { url, init: { method: "POST", headers, body: JSON.stringify({ events }) } };
1517
+ } catch {
1518
+ return null;
1519
+ }
1520
+ };
1521
+ var reportClientEvents = (target, events) => {
1522
+ try {
1523
+ const req = buildEventsRequest(target, events);
1524
+ if (!req) return;
1525
+ void fetch(req.url, req.init).catch(() => {
1521
1526
  });
1522
1527
  } catch {
1523
1528
  }
1524
1529
  };
1525
1530
  var reportClientEvent = (target, event) => reportClientEvents(target, [event]);
1531
+ var reportClientEventsAwait = async (target, events) => {
1532
+ try {
1533
+ const req = buildEventsRequest(target, events);
1534
+ if (!req) return false;
1535
+ const res = await fetch(req.url, req.init);
1536
+ return Boolean(res && res.ok);
1537
+ } catch {
1538
+ return false;
1539
+ }
1540
+ };
1541
+ var reportClientEventAwait = (target, event) => reportClientEventsAwait(target, [event]);
1526
1542
 
1527
1543
  // src/analytics/sendPreview.ts
1528
1544
  var sendPreview = (target, { sessionId, userMessage }) => {
@@ -3285,13 +3301,18 @@ var collectDeviceContext = () => {
3285
3301
  };
3286
3302
 
3287
3303
  // src/analytics/currentSession.ts
3288
- var _currentSessionId;
3304
+ var CURRENT_SESSION_ID_SLOT = /* @__PURE__ */ Symbol.for(
3305
+ "@wireai/activation:currentSessionId"
3306
+ );
3307
+ var globalSlot = globalThis;
3289
3308
  var setCurrentSessionId = (id) => {
3290
- if (typeof id === "string" && id.length > 0) _currentSessionId = id;
3309
+ if (typeof id === "string" && id.length > 0) {
3310
+ globalSlot[CURRENT_SESSION_ID_SLOT] = id;
3311
+ }
3291
3312
  };
3292
- var getCurrentSessionId = () => _currentSessionId;
3313
+ var getCurrentSessionId = () => globalSlot[CURRENT_SESSION_ID_SLOT];
3293
3314
  var resetCurrentSessionId = () => {
3294
- _currentSessionId = void 0;
3315
+ globalSlot[CURRENT_SESSION_ID_SLOT] = void 0;
3295
3316
  };
3296
3317
 
3297
3318
  // src/session/persistedSession.ts
@@ -4115,6 +4136,115 @@ var mintDeviceId = () => {
4115
4136
  return `${AUTO_DEVICE_ID_PREFIX}${time}_${randomChunk()}${randomChunk()}`;
4116
4137
  };
4117
4138
 
4139
+ // src/activation/revalidation.ts
4140
+ var REVALIDATION_SLOT = /* @__PURE__ */ Symbol.for(
4141
+ "@wireai/activation:activationRevalidation"
4142
+ );
4143
+ var globalSlot2 = globalThis;
4144
+ var store = () => {
4145
+ const existing = globalSlot2[REVALIDATION_SLOT];
4146
+ if (existing) return existing;
4147
+ const created = { version: 0, listeners: /* @__PURE__ */ new Set() };
4148
+ globalSlot2[REVALIDATION_SLOT] = created;
4149
+ return created;
4150
+ };
4151
+ var bumpActivationRevalidation = () => {
4152
+ const s = store();
4153
+ s.version += 1;
4154
+ for (const listener of Array.from(s.listeners)) {
4155
+ try {
4156
+ listener();
4157
+ } catch {
4158
+ }
4159
+ }
4160
+ };
4161
+ var subscribeActivationRevalidation = (listener) => {
4162
+ const s = store();
4163
+ s.listeners.add(listener);
4164
+ return () => {
4165
+ s.listeners.delete(listener);
4166
+ };
4167
+ };
4168
+ var getActivationRevalidationVersion = () => store().version;
4169
+ var resetActivationRevalidation = () => {
4170
+ const s = store();
4171
+ s.version = 0;
4172
+ s.listeners.clear();
4173
+ };
4174
+
4175
+ // src/activation/wireActivation.ts
4176
+ var clean = (value) => {
4177
+ if (typeof value !== "string") return void 0;
4178
+ const trimmed = value.trim();
4179
+ return trimmed.length > 0 ? trimmed : void 0;
4180
+ };
4181
+ var createWireActivation = (config) => {
4182
+ var _a2, _b;
4183
+ const target = { serverUrl: config.serverUrl, apiKey: config.apiKey };
4184
+ const explicitDeviceKey = (_b = clean(config.deviceKey)) != null ? _b : clean((_a2 = config.userContext) == null ? void 0 : _a2.deviceKey);
4185
+ let autoDeviceKey = explicitDeviceKey != null ? explicitDeviceKey : mintDeviceId();
4186
+ if (config.storage && !explicitDeviceKey) {
4187
+ const storage = config.storage;
4188
+ const key = deviceIdStorageKey(config.appId);
4189
+ void storage.getItem(key).then((saved) => {
4190
+ const persisted = clean(saved != null ? saved : void 0);
4191
+ if (persisted) autoDeviceKey = persisted;
4192
+ else void storage.setItem(key, autoDeviceKey).catch(() => {
4193
+ });
4194
+ }).catch(() => {
4195
+ });
4196
+ }
4197
+ const applyContext = (event) => {
4198
+ var _a3, _b2;
4199
+ const resolved = resolveUserContext(
4200
+ { ...(_a3 = config.userContext) != null ? _a3 : {}, deviceKey: explicitDeviceKey != null ? explicitDeviceKey : autoDeviceKey },
4201
+ { autoAppVersion: config.appVersion }
4202
+ );
4203
+ if (resolved.userContext) {
4204
+ event.user_context = { ...resolved.userContext, ...(_b2 = event.user_context) != null ? _b2 : {} };
4205
+ }
4206
+ if (resolved.userId && !event.user_id) event.user_id = resolved.userId;
4207
+ };
4208
+ const track = async (name2, meta) => {
4209
+ const sessionId = getCurrentSessionId();
4210
+ if (!clean(name2) || !sessionId) return false;
4211
+ const event = {
4212
+ event_type: "app_event",
4213
+ session_id: sessionId,
4214
+ question_key: name2
4215
+ };
4216
+ if (meta && Object.keys(meta).length > 0) event.meta = JSON.stringify(meta);
4217
+ applyContext(event);
4218
+ const ok = await reportClientEventAwait(target, event);
4219
+ if (ok) bumpActivationRevalidation();
4220
+ return ok;
4221
+ };
4222
+ return {
4223
+ track,
4224
+ get sessionId() {
4225
+ return getCurrentSessionId();
4226
+ },
4227
+ subscribeRevalidation: subscribeActivationRevalidation,
4228
+ getRevalidationVersion: getActivationRevalidationVersion
4229
+ };
4230
+ };
4231
+ var useActivationRevalidation = () => React18.useSyncExternalStore(
4232
+ subscribeActivationRevalidation,
4233
+ getActivationRevalidationVersion,
4234
+ getActivationRevalidationVersion
4235
+ );
4236
+ var useWireActivation = (config) => {
4237
+ const ref = React18.useRef(void 0);
4238
+ const prevKeys = React18.useRef("");
4239
+ const currentKeys = `${config.serverUrl}|${config.apiKey}|${config.appId}|${config.deviceKey}`;
4240
+ if (!ref.current || prevKeys.current !== currentKeys) {
4241
+ prevKeys.current = currentKeys;
4242
+ ref.current = createWireActivation(config);
4243
+ }
4244
+ const revalidation = useActivationRevalidation();
4245
+ return { track: ref.current.track, sessionId: ref.current.sessionId, revalidation };
4246
+ };
4247
+
4118
4248
  // src/session-analytics/reportSessionStart.ts
4119
4249
  var SESSION_STARTED_EVENT = "app.session_started";
4120
4250
  var _emitted = /* @__PURE__ */ new Set();
@@ -4435,9 +4565,8 @@ var createEventQueue = (options) => {
4435
4565
  } catch {
4436
4566
  }
4437
4567
  })();
4438
- const DROP_STATUSES = /* @__PURE__ */ new Set([400, 404, 413, 422]);
4439
4568
  const postBatch = async (events) => {
4440
- if (!(target == null ? void 0 : target.serverUrl) || events.length === 0) return "retry";
4569
+ if (!(target == null ? void 0 : target.serverUrl) || events.length === 0) return false;
4441
4570
  const controller = typeof AbortController !== "undefined" ? new AbortController() : void 0;
4442
4571
  const timer = setTimeout(() => controller == null ? void 0 : controller.abort(), 15e3);
4443
4572
  try {
@@ -4450,12 +4579,9 @@ var createEventQueue = (options) => {
4450
4579
  body: JSON.stringify({ events }),
4451
4580
  signal: controller == null ? void 0 : controller.signal
4452
4581
  });
4453
- if (res && res.ok) return "ok";
4454
- const status = res == null ? void 0 : res.status;
4455
- if (typeof status === "number" && DROP_STATUSES.has(status)) return "drop";
4456
- return "retry";
4582
+ return !!(res && res.ok);
4457
4583
  } catch {
4458
- return "retry";
4584
+ return false;
4459
4585
  } finally {
4460
4586
  clearTimeout(timer);
4461
4587
  }
@@ -4487,8 +4613,8 @@ var createEventQueue = (options) => {
4487
4613
  try {
4488
4614
  while (pending.length > 0) {
4489
4615
  const batch = pending.slice(0, batchSize);
4490
- const result = await postBatch(batch.map((item) => item.event));
4491
- if (result === "retry") {
4616
+ const ok = await postBatch(batch.map((item) => item.event));
4617
+ if (!ok) {
4492
4618
  scheduleRetry();
4493
4619
  return;
4494
4620
  }
@@ -4657,8 +4783,10 @@ exports.WireFeaturesProvider = WireFeaturesProvider;
4657
4783
  exports.WireIcon = WireIcon;
4658
4784
  exports.WireOnboarding = WireOnboarding;
4659
4785
  exports.attributionMetadata = attributionMetadata;
4786
+ exports.bumpActivationRevalidation = bumpActivationRevalidation;
4660
4787
  exports.clearPersistedSession = clearPersistedSession;
4661
4788
  exports.collectDeviceContext = collectDeviceContext;
4789
+ exports.createWireActivation = createWireActivation;
4662
4790
  exports.defaultIllustrations = defaultIllustrations;
4663
4791
  exports.defaultOnboardingTheme = defaultOnboardingTheme;
4664
4792
  exports.defaultWireFeatures = defaultWireFeatures;
@@ -4670,6 +4798,7 @@ exports.featuresCacheKey = featuresCacheKey;
4670
4798
  exports.featuresEqual = featuresEqual;
4671
4799
  exports.fetchWireFeatures = fetchWireFeatures;
4672
4800
  exports.firstOpenStorageKey = firstOpenStorageKey;
4801
+ exports.getActivationRevalidationVersion = getActivationRevalidationVersion;
4673
4802
  exports.getCurrentSessionId = getCurrentSessionId;
4674
4803
  exports.hashEmailFnv1a = hashEmailFnv1a;
4675
4804
  exports.identifyOnboarding = identifyOnboarding;
@@ -4689,9 +4818,12 @@ exports.peekPersistedSession = peekPersistedSession;
4689
4818
  exports.readCachedFeatures = readCachedFeatures;
4690
4819
  exports.readProgress = readProgress;
4691
4820
  exports.reportClientEvent = reportClientEvent;
4821
+ exports.reportClientEventAwait = reportClientEventAwait;
4692
4822
  exports.reportClientEvents = reportClientEvents;
4823
+ exports.reportClientEventsAwait = reportClientEventsAwait;
4693
4824
  exports.reportFirstOpen = reportFirstOpen;
4694
4825
  exports.reportSessionStart = reportSessionStart;
4826
+ exports.resetActivationRevalidation = resetActivationRevalidation;
4695
4827
  exports.resetCurrentSessionId = resetCurrentSessionId;
4696
4828
  exports.resetFirstOpenLatch = resetFirstOpenLatch;
4697
4829
  exports.resetSessionStartGuard = resetSessionStartGuard;
@@ -4700,8 +4832,10 @@ exports.sanitizeUserId = sanitizeUserId;
4700
4832
  exports.savePersistedSession = savePersistedSession;
4701
4833
  exports.sessionStorageKey = sessionStorageKey;
4702
4834
  exports.setCurrentSessionId = setCurrentSessionId;
4835
+ exports.subscribeActivationRevalidation = subscribeActivationRevalidation;
4703
4836
  exports.themeFromBrand = themeFromBrand;
4704
4837
  exports.toAnalyticsEvent = toAnalyticsEvent;
4838
+ exports.useActivationRevalidation = useActivationRevalidation;
4705
4839
  exports.useHostIcon = useHostIcon;
4706
4840
  exports.useIllustration = useIllustration;
4707
4841
  exports.useLifecycleEvents = useLifecycleEvents;
@@ -4709,6 +4843,7 @@ exports.useOnboardingTheme = useOnboardingTheme;
4709
4843
  exports.useReducedMotion = useReducedMotion;
4710
4844
  exports.useResolvedFeatures = useResolvedFeatures;
4711
4845
  exports.useSessionStart = useSessionStart;
4846
+ exports.useWireActivation = useWireActivation;
4712
4847
  exports.useWireFeatures = useWireFeatures;
4713
4848
  exports.useWireFeaturesContext = useWireFeaturesContext;
4714
4849
  exports.wireConfigFromEnv = wireConfigFromEnv;