@splithub/node 0.4.3 → 0.5.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.
package/README.md CHANGED
@@ -48,6 +48,13 @@ Reads return raw numbers from your own database:
48
48
  The first variant is the control. `rawResults(config, store, id)` and `rawStatusTable(config, store)`
49
49
  give the same numbers in code. Verdicts, data-quality stars and recommendations come with SplitHub Cloud.
50
50
 
51
+ ## Apps
52
+
53
+ The same handler takes events from apps built with `@splithub/react-native` (React Native, Expo).
54
+ An app batch carries the app's info instead of a user agent: every stored event gets `platform`
55
+ (`ios`, `android` ...; `web` for websites) and `app_version`, and the device, OS and host come from
56
+ the app. Events sent while the app was offline arrive later with their original time.
57
+
51
58
  ## Bring your own database
52
59
 
53
60
  Implement the `Store` interface (three methods) against Postgres, Supabase,
package/dist/index.cjs CHANGED
@@ -24,8 +24,10 @@ __export(index_exports, {
24
24
  ANALYTICS_TYPES: () => ANALYTICS_TYPES,
25
25
  ATTRIBUTION_SKEW_MS: () => ATTRIBUTION_SKEW_MS,
26
26
  GOAL_DAILY_CAP: () => GOAL_DAILY_CAP,
27
+ MAX_BODY_BYTES: () => MAX_BODY_BYTES,
27
28
  PROPERTY_REPORTS_UNAVAILABLE: () => PROPERTY_REPORTS_UNAVAILABLE,
28
29
  SAME_ACTION_MS: () => SAME_ACTION_MS,
30
+ appDimensions: () => appDimensions,
29
31
  attributeVariants: () => attributeVariants,
30
32
  attributionConformance: () => attributionConformance,
31
33
  countProperty: () => countProperty,
@@ -42,11 +44,13 @@ __export(index_exports, {
42
44
  rawStatusTable: () => rawStatusTable,
43
45
  resultsExperiment: () => resultsExperiment,
44
46
  revenueOf: () => revenueOf,
47
+ sanitizeApp: () => sanitizeApp,
45
48
  sortCounts: () => sortCounts,
46
49
  storedEventFromRow: () => storedEventFromRow,
47
50
  toNodeListener: () => toNodeListener,
48
51
  validateBatch: () => validateBatch,
49
- variantCountsSql: () => variantCountsSql
52
+ variantCountsSql: () => variantCountsSql,
53
+ withAppDimensions: () => withAppDimensions
50
54
  });
51
55
  module.exports = __toCommonJS(index_exports);
52
56
 
@@ -192,7 +196,10 @@ function storedEventFromRow(r) {
192
196
  host: s(r.host),
193
197
  country: s(r.country),
194
198
  device: s(r.device),
195
- browser: s(r.browser)
199
+ browser: s(r.browser),
200
+ // Columns added for apps; rows of stores without them keep the old shape.
201
+ ..."platform" in r ? { platform: s(r.platform) } : {},
202
+ ..."app_version" in r ? { app_version: s(r.app_version) } : {}
196
203
  };
197
204
  }
198
205
  var PROPERTY_REPORTS_UNAVAILABLE = {
@@ -459,7 +466,33 @@ function validateBatch(body, expectedProject, now = Date.now()) {
459
466
  if (errors.length < 5 && !errors.includes(e)) errors.push(e);
460
467
  } else out.push(e);
461
468
  }
462
- return { ok: true, events: out, dropped, errors };
469
+ const app = sanitizeApp(batch.app);
470
+ return { ok: true, events: out, dropped, errors, ...app ? { app } : {} };
471
+ }
472
+ var APP_PLATFORMS = /* @__PURE__ */ new Set(["ios", "android", "macos", "windows", "linux"]);
473
+ var APP_DEVICES = /* @__PURE__ */ new Set(["mobile", "tablet", "desktop"]);
474
+ function text(value, max) {
475
+ if (typeof value !== "string") return void 0;
476
+ const t = value.trim();
477
+ return t ? t.slice(0, max) : void 0;
478
+ }
479
+ function sanitizeApp(raw) {
480
+ if (!raw || typeof raw !== "object") return void 0;
481
+ const a = raw;
482
+ if (typeof a.platform !== "string" || !APP_PLATFORMS.has(a.platform)) return void 0;
483
+ const out = { platform: a.platform };
484
+ const id = text(a.id, 128);
485
+ const version = text(a.version, 32);
486
+ const build = text(a.build, 32);
487
+ const os = text(a.os, 32);
488
+ const model = text(a.model, 64);
489
+ if (id) out.id = id.toLowerCase();
490
+ if (version) out.version = version;
491
+ if (build) out.build = build;
492
+ if (os) out.os = os;
493
+ if (model) out.model = model;
494
+ if (typeof a.device === "string" && APP_DEVICES.has(a.device)) out.device = a.device;
495
+ return out;
463
496
  }
464
497
  function normalize(e, now) {
465
498
  if (!e || typeof e !== "object") return "event must be an object";
@@ -581,9 +614,45 @@ function goalsFromAnalytics(events, goals) {
581
614
  return out;
582
615
  }
583
616
 
617
+ // src/app.ts
618
+ var APP_OS = { ios: "iOS", android: "Android", macos: "macOS", windows: "Windows", linux: "Linux" };
619
+ function appDimensions(app) {
620
+ if (!app) return { platform: "web", app_version: null };
621
+ return { platform: app.platform, app_version: app.version ?? null, device: app.device ?? "mobile", os: APP_OS[app.platform], browser: "App", host: app.id ?? null };
622
+ }
623
+ function withAppDimensions(events, app) {
624
+ const d = appDimensions(app);
625
+ return events.map((e) => ({ ...e, ...d, ...e.host ? { host: e.host } : {} }));
626
+ }
627
+
584
628
  // src/handler.ts
585
629
  var isBotUserAgent = (ua) => (0, import_core4.isCrawler)(ua);
586
630
  var visitorUserAgent = (request) => request.headers.get("x-splithub-ua") ?? request.headers.get("user-agent");
631
+ var MAX_BODY_BYTES = 1024 * 1024;
632
+ async function readCapped(request, max) {
633
+ if (Number(request.headers.get("content-length") ?? 0) > max) return null;
634
+ if (!request.body) return "";
635
+ const reader = request.body.getReader();
636
+ const chunks = [];
637
+ let size = 0;
638
+ for (; ; ) {
639
+ const { done, value } = await reader.read();
640
+ if (done) break;
641
+ size += value.byteLength;
642
+ if (size > max) {
643
+ await reader.cancel().catch(() => void 0);
644
+ return null;
645
+ }
646
+ chunks.push(value);
647
+ }
648
+ const all = new Uint8Array(size);
649
+ let at = 0;
650
+ for (const c of chunks) {
651
+ all.set(c, at);
652
+ at += c.byteLength;
653
+ }
654
+ return new TextDecoder().decode(all);
655
+ }
587
656
  function createSplitHubHandler(options) {
588
657
  const { config, store } = options;
589
658
  const derivable = experimentGoals(config);
@@ -611,9 +680,11 @@ function createSplitHubHandler(options) {
611
680
  const tail = path.split("/").slice(-2);
612
681
  if (request.method === "OPTIONS") return new Response(null, { status: 204, headers: corsHeaders(request) });
613
682
  if (request.method === "POST") {
683
+ const text2 = await readCapped(request, MAX_BODY_BYTES);
684
+ if (text2 === null) return json(request, { error: `body larger than ${MAX_BODY_BYTES} bytes` }, 413);
614
685
  let body;
615
686
  try {
616
- body = await request.json();
687
+ body = JSON.parse(text2);
617
688
  } catch {
618
689
  return json(request, { error: "invalid JSON" }, 400);
619
690
  }
@@ -623,8 +694,9 @@ function createSplitHubHandler(options) {
623
694
  const received = result.events.length + result.dropped;
624
695
  if (isBotUserAgent(visitorUserAgent(request))) return json(request, { ok: true, received, inserted: 0, ...dropped }, 202);
625
696
  const running = new Set((config.properties ?? []).filter((p) => p.status === "running").map((p) => p.key));
626
- const derived = goalsFromAnalytics(result.events, derivable).map(({ derived: _, ...goal2 }) => goal2);
627
- const events = [...result.events.filter((e) => !ANALYTICS_TYPES.has(e.type) || e.experiment !== null && running.has(e.experiment)), ...derived];
697
+ const stamped = withAppDimensions(result.events, result.app);
698
+ const derived = goalsFromAnalytics(stamped, derivable).map(({ derived: _, ...goal2 }) => goal2);
699
+ const events = [...stamped.filter((e) => !ANALYTICS_TYPES.has(e.type) || e.experiment !== null && running.has(e.experiment)), ...derived];
628
700
  const inserted = events.length ? await store.insertEvents(events) : 0;
629
701
  return json(request, { ok: true, received, inserted, ...dropped }, 202);
630
702
  }
@@ -664,6 +736,8 @@ function createSplitHubHandler(options) {
664
736
  }
665
737
 
666
738
  // src/nodeAdapter.ts
739
+ var BodyTooLarge = class extends Error {
740
+ };
667
741
  function toNodeListener(handler) {
668
742
  return (req, res) => {
669
743
  void (async () => {
@@ -675,9 +749,12 @@ function toNodeListener(handler) {
675
749
  const body = response.body ? Buffer.from(await response.arrayBuffer()) : null;
676
750
  res.end(body);
677
751
  } catch (error) {
678
- res.statusCode = 500;
752
+ const tooLarge = error instanceof BodyTooLarge;
753
+ res.statusCode = tooLarge ? 413 : 500;
679
754
  res.setHeader("content-type", "application/json");
680
- res.end(JSON.stringify({ error: error instanceof Error ? error.message : "internal error" }));
755
+ if (tooLarge) res.setHeader("connection", "close");
756
+ res.end(JSON.stringify({ error: tooLarge ? `body larger than ${MAX_BODY_BYTES} bytes` : error instanceof Error ? error.message : "internal error" }));
757
+ if (tooLarge) req.destroy();
681
758
  }
682
759
  })();
683
760
  };
@@ -695,11 +772,21 @@ async function toRequest(req) {
695
772
  const method = req.method ?? "GET";
696
773
  let body;
697
774
  if (method !== "GET" && method !== "HEAD") {
775
+ if (Number(req.headers["content-length"] ?? 0) > MAX_BODY_BYTES) throw new BodyTooLarge();
698
776
  const chunks = [];
699
- for await (const chunk of req) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
700
- const all = Buffer.concat(chunks);
701
- const copy = new Uint8Array(all.byteLength);
702
- copy.set(all);
777
+ let size = 0;
778
+ for await (const chunk of req) {
779
+ const b = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
780
+ size += b.byteLength;
781
+ if (size > MAX_BODY_BYTES) throw new BodyTooLarge();
782
+ chunks.push(b);
783
+ }
784
+ const copy = new Uint8Array(size);
785
+ let at = 0;
786
+ for (const c of chunks) {
787
+ copy.set(c, at);
788
+ at += c.byteLength;
789
+ }
703
790
  body = copy.buffer;
704
791
  }
705
792
  return new Request(url, { method, headers, body });
@@ -815,8 +902,10 @@ function sortCounts(rows) {
815
902
  ANALYTICS_TYPES,
816
903
  ATTRIBUTION_SKEW_MS,
817
904
  GOAL_DAILY_CAP,
905
+ MAX_BODY_BYTES,
818
906
  PROPERTY_REPORTS_UNAVAILABLE,
819
907
  SAME_ACTION_MS,
908
+ appDimensions,
820
909
  attributeVariants,
821
910
  attributionConformance,
822
911
  countProperty,
@@ -833,10 +922,12 @@ function sortCounts(rows) {
833
922
  rawStatusTable,
834
923
  resultsExperiment,
835
924
  revenueOf,
925
+ sanitizeApp,
836
926
  sortCounts,
837
927
  storedEventFromRow,
838
928
  toNodeListener,
839
929
  validateBatch,
840
- variantCountsSql
930
+ variantCountsSql,
931
+ withAppDimensions
841
932
  });
842
933
  //# sourceMappingURL=index.cjs.map