@trycurious/js 0.1.0 → 0.2.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
@@ -226,6 +226,46 @@ var AssignmentCache = class {
226
226
  }
227
227
  };
228
228
 
229
+ // src/history.ts
230
+ var subscribers = /* @__PURE__ */ new WeakMap();
231
+ function notify(listeners) {
232
+ for (const listener of Array.from(listeners)) {
233
+ try {
234
+ listener();
235
+ } catch {
236
+ }
237
+ }
238
+ }
239
+ function install(target) {
240
+ const existing = subscribers.get(target);
241
+ if (existing !== void 0) return existing;
242
+ const listeners = /* @__PURE__ */ new Set();
243
+ subscribers.set(target, listeners);
244
+ for (const method of ["pushState", "replaceState"]) {
245
+ const original = target[method];
246
+ if (typeof original !== "function") continue;
247
+ try {
248
+ target[method] = function(...args) {
249
+ const result = original.apply(this, args);
250
+ notify(listeners);
251
+ return result;
252
+ };
253
+ } catch {
254
+ }
255
+ }
256
+ addEventListener("popstate", () => notify(listeners));
257
+ return listeners;
258
+ }
259
+ function onHistoryChange(listener) {
260
+ if (typeof history === "undefined" || typeof addEventListener === "undefined") return () => {
261
+ };
262
+ const listeners = install(history);
263
+ listeners.add(listener);
264
+ return () => {
265
+ listeners.delete(listener);
266
+ };
267
+ }
268
+
229
269
  // src/events.ts
230
270
  var DEFAULTS = {
231
271
  flushIntervalMs: 5e3,
@@ -681,7 +721,7 @@ var TagRuntime = class {
681
721
  };
682
722
 
683
723
  // src/version.ts
684
- var SDK_VERSION = "0.1.0";
724
+ var SDK_VERSION = "0.2.0";
685
725
 
686
726
  // src/transport.ts
687
727
  var MAX_RESPONSE_BYTES = 1048576;
@@ -801,8 +841,14 @@ function createCurious(options) {
801
841
  let started = false;
802
842
  let active = false;
803
843
  const inFlight = /* @__PURE__ */ new Map();
844
+ const directInFlight = /* @__PURE__ */ new Map();
804
845
  let events = null;
805
846
  const listeners = [];
847
+ const pageviewSetting = options.autocapture === false ? false : options.autocapture?.pageviews ?? true;
848
+ const pageviews = pageviewSetting !== false;
849
+ const historyChanges = pageviews && (pageviewSetting === true || pageviewSetting.historyChanges !== false);
850
+ let visitPath = null;
851
+ let visitRecorded = false;
806
852
  const tags = new TagRuntime({
807
853
  ...options.rootMargin === void 0 ? {} : { rootMargin: options.rootMargin },
808
854
  onPending: (elements) => void decideTagged(elements),
@@ -815,6 +861,15 @@ function createCurious(options) {
815
861
  if (typeof navigator !== "undefined" && navigator.language) base.locale = navigator.language;
816
862
  return { ...base, ...options.context ?? {} };
817
863
  }
864
+ function recordPageview() {
865
+ visitPath = location.pathname;
866
+ const recorded = queue().system({ name: "$pageview", properties: { path: visitPath } });
867
+ visitRecorded = recorded.queued;
868
+ return recorded;
869
+ }
870
+ function pageviewRecorded() {
871
+ return visitRecorded && location.pathname === visitPath;
872
+ }
818
873
  function queue() {
819
874
  if (events === null) {
820
875
  const tuning = options.events ?? {};
@@ -837,6 +892,10 @@ function createCurious(options) {
837
892
  for (const element of elements) {
838
893
  const hit = cache.get(userId, element);
839
894
  if (hit !== null) {
895
+ if (typeof hit.content !== "string") {
896
+ fallbackTag(element, summary("content_shape_mismatch", "Served content is not text", { retryable: false, status: 200 }));
897
+ continue;
898
+ }
840
899
  if (tags.apply(element, hit.content) === "applied") {
841
900
  onDecision(element, { content: hit.content, served: "cache", armId: hit.armId, armType: hit.armType, experimentId: hit.experimentId, experimentStatus: hit.experimentStatus, requestId: null });
842
901
  }
@@ -903,6 +962,31 @@ function createCurious(options) {
903
962
  }
904
963
  });
905
964
  }
965
+ async function requestDecision(userId, input) {
966
+ const body = { element: input.element, user_id: userId, context: { ...pageContext(), ...input.context ?? {} } };
967
+ if (input.identifiers !== void 0) body.identifiers = input.identifiers;
968
+ if (input.attributes !== void 0) body.attributes = input.attributes;
969
+ let response;
970
+ try {
971
+ response = await transport.post("/decide", body, { timeoutMs });
972
+ } catch (error) {
973
+ return { ok: false, error: error.summary, requestId: null };
974
+ }
975
+ if (response.status !== 200) return { ok: false, error: summarizeHttpError(response.status, response.body, response.requestId), requestId: response.requestId };
976
+ const decision = response.body;
977
+ if (decision === null || typeof decision !== "object" || typeof decision.arm_id !== "string" || !("content" in decision)) {
978
+ return { ok: false, error: summary("protocol_error", "Decision response was missing required fields", { retryable: false, status: 200 }), requestId: response.requestId };
979
+ }
980
+ return {
981
+ ok: true,
982
+ content: decision.content,
983
+ armId: decision.arm_id,
984
+ armType: decision.arm_type ?? null,
985
+ experimentId: typeof decision.experiment_id === "string" ? decision.experiment_id : null,
986
+ experimentStatus: typeof decision.experiment_status === "string" ? decision.experiment_status : null,
987
+ requestId: response.requestId
988
+ };
989
+ }
906
990
  function fallbackTag(element, error) {
907
991
  tags.fallback(element);
908
992
  onFallback(element, error);
@@ -920,9 +1004,14 @@ function createCurious(options) {
920
1004
  listeners.push(() => document.removeEventListener("visibilitychange", onVisibility));
921
1005
  listeners.push(() => removeEventListener("pagehide", onPageHide));
922
1006
  if (options.autocapture === false) return;
923
- const capture = { pageviews: true, taggedClicks: true, taggedFormSubmits: true, ...options.autocapture };
924
- if (capture.pageviews) {
925
- queue().system({ name: "$pageview", properties: { path: location.pathname } });
1007
+ const capture = { taggedClicks: true, taggedFormSubmits: true, ...options.autocapture };
1008
+ if (pageviews && !pageviewRecorded()) recordPageview();
1009
+ if (historyChanges) {
1010
+ listeners.push(
1011
+ onHistoryChange(() => {
1012
+ if (active && !pageviewRecorded()) recordPageview();
1013
+ })
1014
+ );
926
1015
  }
927
1016
  if (capture.taggedClicks) {
928
1017
  const onClick = (event) => {
@@ -975,24 +1064,37 @@ function createCurious(options) {
975
1064
  return { content: input.fallback, served: "fallback", armId: null, armType: null, experimentId: null, experimentStatus: null, error, requestId };
976
1065
  };
977
1066
  if (!active) return fallback(summary("capability_unavailable", "The SDK is not active (consent or start)", { retryable: false }), null);
978
- const body = { element: input.element, user_id: identity.activeUserId, context: { ...pageContext(), ...input.context ?? {} } };
979
- if (input.identifiers !== void 0) body.identifiers = input.identifiers;
980
- if (input.attributes !== void 0) body.attributes = input.attributes;
981
- let response;
982
- try {
983
- response = await transport.post("/decide", body, { timeoutMs });
984
- } catch (error) {
985
- return fallback(error.summary, null);
1067
+ const userId = identity.activeUserId;
1068
+ const plain = input.identifiers === void 0 && input.attributes === void 0 && input.context === void 0;
1069
+ const hit = plain ? cache.get(userId, input.element) : null;
1070
+ if (hit !== null && sameShape(hit.content, input.fallback)) {
1071
+ const cached = { content: hit.content, served: "cache", armId: hit.armId, armType: hit.armType, experimentId: hit.experimentId, experimentStatus: hit.experimentStatus, requestId: null };
1072
+ onDecision(input.element, cached);
1073
+ return cached;
986
1074
  }
987
- if (response.status !== 200) return fallback(summarizeHttpError(response.status, response.body, response.requestId), response.requestId);
988
- const decision = response.body;
989
- if (decision === null || typeof decision !== "object" || typeof decision.arm_id !== "string" || !("content" in decision)) {
990
- return fallback(summary("protocol_error", "Decision response was missing required fields", { retryable: false, status: 200 }), response.requestId);
1075
+ const key = `${userId}:${input.element}`;
1076
+ const out = plain ? directInFlight.get(key) : void 0;
1077
+ const pending = out ?? requestDecision(userId, input);
1078
+ if (plain && out === void 0) {
1079
+ directInFlight.set(key, pending);
1080
+ void pending.then(() => {
1081
+ if (directInFlight.get(key) === pending) directInFlight.delete(key);
1082
+ });
991
1083
  }
992
- if (typeof decision.content !== typeof input.fallback) {
993
- return fallback(summary("content_shape_mismatch", "Served content does not match the fallback's shape", { retryable: false, status: 200 }), response.requestId);
1084
+ const outcome = await pending;
1085
+ if (!active || identity.activeUserId !== userId) {
1086
+ return fallback(summary("capability_unavailable", "The SDK was stopped, or the visitor changed, while the decision was in flight", { retryable: false }), outcome.requestId);
1087
+ }
1088
+ if (!outcome.ok) return fallback(outcome.error, outcome.requestId);
1089
+ if (!sameShape(outcome.content, input.fallback)) {
1090
+ return fallback(summary("content_shape_mismatch", "Served content does not match the fallback's shape", { retryable: false, status: 200 }), outcome.requestId);
1091
+ }
1092
+ const result = { content: outcome.content, served: out === void 0 ? "curious" : "cache", armId: outcome.armId, armType: outcome.armType, experimentId: outcome.experimentId, experimentStatus: outcome.experimentStatus, requestId: outcome.requestId };
1093
+ if (plain && outcome.experimentId !== null && outcome.experimentStatus !== null) {
1094
+ cache.set(userId, input.element, { content: outcome.content, armId: outcome.armId, armType: outcome.armType, experimentId: outcome.experimentId, experimentStatus: outcome.experimentStatus });
1095
+ } else if (input.identifiers !== void 0 || input.attributes !== void 0) {
1096
+ cache.remove(userId, input.element);
994
1097
  }
995
- const result = { content: decision.content, served: "curious", armId: decision.arm_id, armType: decision.arm_type ?? null, experimentId: decision.experiment_id ?? null, experimentStatus: decision.experiment_status ?? null, requestId: response.requestId };
996
1098
  onDecision(input.element, result);
997
1099
  return result;
998
1100
  },
@@ -1008,13 +1110,14 @@ function createCurious(options) {
1008
1110
  return events.flush(flushOptions);
1009
1111
  },
1010
1112
  page() {
1011
- if (options.autocapture === false || options.autocapture?.pageviews === false) return { id: "", queued: false };
1113
+ if (!pageviews) return { id: "", queued: false };
1012
1114
  if (!active) {
1013
1115
  onEventDrop(summary("capability_unavailable", "Events are not collected before consent", { retryable: false }));
1014
1116
  return { id: "", queued: false };
1015
1117
  }
1016
1118
  if (typeof location === "undefined") return { id: "", queued: false };
1017
- return queue().system({ name: "$pageview", properties: { path: location.pathname } });
1119
+ if (historyChanges && pageviewRecorded()) return { id: "", queued: false };
1120
+ return recordPageview();
1018
1121
  },
1019
1122
  // After the customer's backend has linked the anonymous id with a secret
1020
1123
  // key: flush anonymous events, switch the active user, forget cached
@@ -1044,6 +1147,7 @@ function createCurious(options) {
1044
1147
  if (active) identity.reset();
1045
1148
  cache.clear();
1046
1149
  tags.resetDecisions();
1150
+ visitRecorded = false;
1047
1151
  onIdentityChange(null);
1048
1152
  },
1049
1153
  grantConsent() {
@@ -1058,6 +1162,7 @@ function createCurious(options) {
1058
1162
  events?.clear();
1059
1163
  cache.clear();
1060
1164
  identity.clear();
1165
+ visitRecorded = false;
1061
1166
  onIdentityChange(null);
1062
1167
  },
1063
1168
  get anonymousId() {
@@ -1069,6 +1174,21 @@ function createCurious(options) {
1069
1174
  };
1070
1175
  return client;
1071
1176
  }
1177
+ function sameShape(content, fallback) {
1178
+ if (fallback === null || fallback === void 0) return true;
1179
+ if (content === null || content === void 0) return false;
1180
+ if (Array.isArray(fallback) || Array.isArray(content)) {
1181
+ if (!Array.isArray(fallback) || !Array.isArray(content)) return false;
1182
+ return fallback.length === 0 || content.every((item) => sameShape(item, fallback[0]));
1183
+ }
1184
+ if (typeof fallback !== "object") return typeof content === typeof fallback;
1185
+ if (typeof content !== "object") return false;
1186
+ for (const [key, want] of Object.entries(fallback)) {
1187
+ if (!Object.prototype.hasOwnProperty.call(content, key)) return false;
1188
+ if (!sameShape(content[key], want)) return false;
1189
+ }
1190
+ return true;
1191
+ }
1072
1192
  function guarded(hook) {
1073
1193
  return (...args) => {
1074
1194
  if (hook === void 0) return;