@gravity-ai/api 1.1.8 → 1.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
@@ -35,7 +35,7 @@ var require_package = __commonJS({
35
35
  "package.json"(exports2, module2) {
36
36
  module2.exports = {
37
37
  name: "@gravity-ai/api",
38
- version: "1.1.8",
38
+ version: "1.2.0",
39
39
  description: "Gravity JS SDK for retrieving targeted advertisements",
40
40
  main: "dist/index.js",
41
41
  module: "dist/index.mjs",
@@ -122,17 +122,22 @@ var index_exports = {};
122
122
  __export(index_exports, {
123
123
  Client: () => Client,
124
124
  Gravity: () => Gravity,
125
+ GravityPixel: () => GravityPixel,
126
+ detectCmpConsent: () => detectCmpConsent,
125
127
  extractClientIp: () => extractClientIp,
126
128
  gravityAds: () => gravityAds,
127
129
  gravityContext: () => gravityContext,
130
+ gravityContextAsync: () => gravityContextAsync,
131
+ gravityPixel: () => gravityPixel,
128
132
  hashPii: () => hashPii,
133
+ readCmpConsent: () => readCmpConsent,
129
134
  toGravityMessages: () => toGravityMessages
130
135
  });
131
136
  module.exports = __toCommonJS(index_exports);
132
137
 
133
138
  // ads.ts
134
139
  var DEFAULT_GRAVITY_API = "https://server.trygravity.ai/api/v1/ad";
135
- var DEFAULT_TIMEOUT_MS = 3e3;
140
+ var DEFAULT_TIMEOUT_MS = 4e3;
136
141
  function toGravityMessages(messages, maxTurns = 2) {
137
142
  if (!messages || messages.length === 0) return [];
138
143
  return messages.slice(-maxTurns).map((m) => ({
@@ -177,8 +182,17 @@ async function gravityAds(req, messages, placements, opts = {}) {
177
182
  ...clientIp ? { ip: clientIp } : {}
178
183
  }
179
184
  };
185
+ if (ctx?.consent && typeof ctx.consent === "object") {
186
+ body.consent = ctx.consent;
187
+ }
180
188
  body.relevancy = opts.relevancy ?? 0.2;
181
189
  body.testAd = opts.production === true ? false : true;
190
+ if (body.testAd && opts.alwaysReturn === true) body.alwaysReturn = true;
191
+ const supportsSpec = opts.supportsSpec ?? true;
192
+ body.supportsSpec = supportsSpec;
193
+ if (supportsSpec) body.specCapabilities = opts.specCapabilities ?? "web1";
194
+ if (opts.enableFrames ?? supportsSpec) body.supportsFrames = true;
195
+ if (body.testAd && opts.adLayout) body.adLayout = opts.adLayout;
182
196
  if (opts.excludedTopics) body.excludedTopics = opts.excludedTopics;
183
197
  const start = performance.now();
184
198
  try {
@@ -192,8 +206,8 @@ async function gravityAds(req, messages, placements, opts = {}) {
192
206
  signal: AbortSignal.timeout(timeoutMs)
193
207
  });
194
208
  const elapsed = (performance.now() - start).toFixed(0);
195
- if (res.status === 204) {
196
- return { ads: [], status: 204, elapsed, requestBody: body };
209
+ if (res.status === 204 || res.status === 202) {
210
+ return { ads: [], status: res.status, elapsed, requestBody: body };
197
211
  }
198
212
  if (!res.ok) {
199
213
  const errText = await res.text().catch(() => "");
@@ -224,8 +238,9 @@ var Gravity = class {
224
238
  * |--------|------|---------|-------------|
225
239
  * | `apiKey` | `string` | `process.env.GRAVITY_API_KEY` | Gravity API key |
226
240
  * | `production` | `boolean` | `false` | `true` = real ads. `false` = test ads (no billing). |
241
+ * | `alwaysReturn` | `boolean` | `false` | Test-only: return a default test ad instead of a 204 no-fill. Ignored in production. |
227
242
  * | `relevancy` | `number` | `0.2` | Minimum relevancy threshold (0-1) |
228
- * | `timeoutMs` | `number` | `3000` | Request timeout in ms |
243
+ * | `timeoutMs` | `number` | `4000` | Request timeout in ms |
229
244
  * | `excludedTopics` | `string[]` | — | Topics to exclude from ad matching |
230
245
  * | `gravityApi` | `string` | production URL | Custom API endpoint |
231
246
  */
@@ -253,6 +268,99 @@ var Gravity = class {
253
268
  }
254
269
  };
255
270
 
271
+ // ../ui/src/consent.ts
272
+ function findCmpApi(name) {
273
+ if (typeof window === "undefined") return void 0;
274
+ let frame = window;
275
+ for (let hops = 0; frame && hops < 10; hops++) {
276
+ try {
277
+ const api = frame[name];
278
+ if (typeof api === "function") return api;
279
+ } catch {
280
+ break;
281
+ }
282
+ if (frame === frame.parent) break;
283
+ frame = frame.parent;
284
+ }
285
+ return void 0;
286
+ }
287
+ var cachedTcf;
288
+ var cachedUsp;
289
+ var tcfListening = false;
290
+ var cmpWaitExhausted = false;
291
+ function ensureListening() {
292
+ if (typeof window === "undefined") return;
293
+ const tcfapi = tcfListening ? void 0 : findCmpApi("__tcfapi");
294
+ if (tcfapi) {
295
+ tcfListening = true;
296
+ try {
297
+ tcfapi("addEventListener", 2, (data, success) => {
298
+ if (!success || typeof data !== "object" || data === null) return;
299
+ const tc = data;
300
+ if (tc.eventStatus === "tcloaded" || tc.eventStatus === "useractioncomplete") {
301
+ cachedTcf = {
302
+ gdprApplies: typeof tc.gdprApplies === "boolean" ? tc.gdprApplies : void 0,
303
+ tcfString: typeof tc.tcString === "string" && tc.tcString ? tc.tcString : void 0
304
+ };
305
+ } else if (typeof tc.gdprApplies === "boolean" && !tc.gdprApplies) {
306
+ cachedTcf = { gdprApplies: false };
307
+ }
308
+ });
309
+ } catch {
310
+ }
311
+ }
312
+ const uspapi = findCmpApi("__uspapi");
313
+ if (uspapi) {
314
+ try {
315
+ uspapi("getUSPData", 1, (data, success) => {
316
+ if (!success || typeof data !== "object" || data === null) return;
317
+ const usp = data.uspString;
318
+ if (typeof usp === "string" && usp) cachedUsp = usp;
319
+ });
320
+ } catch {
321
+ }
322
+ }
323
+ }
324
+ function detectCmpConsent() {
325
+ ensureListening();
326
+ if (!cachedTcf && !cachedUsp) return void 0;
327
+ const consent = {};
328
+ if (cachedTcf?.gdprApplies !== void 0) consent.gdprApplies = cachedTcf.gdprApplies;
329
+ if (cachedTcf?.tcfString) consent.tcfString = cachedTcf.tcfString;
330
+ if (cachedUsp) consent.usPrivacy = cachedUsp;
331
+ if (Object.keys(consent).length === 0) return void 0;
332
+ return consent;
333
+ }
334
+ var NO_CMP_GRACE_MS = 150;
335
+ var graceStartedAt = typeof window === "undefined" ? 0 : Date.now();
336
+ if (typeof window !== "undefined") ensureListening();
337
+ function readCmpConsent(timeoutMs = 500) {
338
+ ensureListening();
339
+ const immediate = detectCmpConsent();
340
+ if (immediate || cmpWaitExhausted || typeof window === "undefined") {
341
+ return Promise.resolve(immediate);
342
+ }
343
+ return new Promise((resolve) => {
344
+ const started = Date.now();
345
+ const poll = () => {
346
+ const consent = detectCmpConsent();
347
+ if (consent) return resolve(consent);
348
+ const elapsed = Date.now() - started;
349
+ const cmpPresent = Boolean(findCmpApi("__tcfapi") || findCmpApi("__uspapi"));
350
+ if (cmpPresent) {
351
+ if (elapsed >= timeoutMs) {
352
+ cmpWaitExhausted = true;
353
+ return resolve(void 0);
354
+ }
355
+ } else if (elapsed >= timeoutMs || Date.now() - graceStartedAt >= NO_CMP_GRACE_MS) {
356
+ return resolve(void 0);
357
+ }
358
+ setTimeout(poll, 50);
359
+ };
360
+ poll();
361
+ });
362
+ }
363
+
256
364
  // context.ts
257
365
  function readPixel(method) {
258
366
  if (typeof window === "undefined") return void 0;
@@ -290,12 +398,19 @@ function gravityContext(overrides) {
290
398
  if (gruid) pixelUserFields.gruid = gruid;
291
399
  if (grclid) pixelUserFields.grclid = grclid;
292
400
  if (graid) pixelUserFields.graid = graid;
401
+ const consent = overrides.consent ?? (isBrowser ? detectCmpConsent() : void 0);
293
402
  return {
294
403
  sessionId,
295
404
  user: { ...pixelUserFields, ...restUser, id: userId },
296
- device
405
+ device,
406
+ ...consent ? { consent } : {}
297
407
  };
298
408
  }
409
+ async function gravityContextAsync(overrides) {
410
+ const isBrowser = typeof window !== "undefined" && typeof navigator !== "undefined";
411
+ const consent = overrides.consent ?? (isBrowser ? await readCmpConsent() : void 0);
412
+ return gravityContext(consent ? { ...overrides, consent } : overrides);
413
+ }
299
414
  function browserDevice() {
300
415
  const nav = typeof navigator !== "undefined" ? navigator : void 0;
301
416
  const win = typeof window !== "undefined" ? window : void 0;
@@ -467,8 +582,13 @@ var Client = class {
467
582
  */
468
583
  async getAd(params) {
469
584
  try {
585
+ const supportsSpec = params.supportsSpec ?? true;
586
+ const { enableFrames, ...requestParams } = params;
470
587
  const body = {
471
- ...params,
588
+ ...requestParams,
589
+ ...enableFrames ?? supportsSpec ? { supportsFrames: true } : {},
590
+ supportsSpec,
591
+ ...supportsSpec ? { specCapabilities: params.specCapabilities ?? "web1" } : { specCapabilities: void 0 },
472
592
  excludedTopics: params.excludedTopics ?? this.excludedTopics,
473
593
  relevancy: params.relevancy ?? this.relevancy
474
594
  };
@@ -554,13 +674,471 @@ async function hashPii(values) {
554
674
  if (hashedPhone) out.hashed_phone = hashedPhone;
555
675
  return out;
556
676
  }
677
+
678
+ // gravity-pixel.ts
679
+ function uuid(prefix) {
680
+ const hex = () => Math.random().toString(36).slice(2, 10);
681
+ return prefix + hex() + hex();
682
+ }
683
+ function nowMs() {
684
+ return Date.now();
685
+ }
686
+ var _fs;
687
+ var _path;
688
+ var _os;
689
+ var _modulesLoaded = false;
690
+ async function loadModules() {
691
+ if (_modulesLoaded) return;
692
+ _modulesLoaded = true;
693
+ try {
694
+ _fs = await import("fs");
695
+ _path = await import("path");
696
+ _os = await import("os");
697
+ } catch {
698
+ }
699
+ }
700
+ function resolveStorageDir(custom) {
701
+ if (custom) return custom;
702
+ const home = _os?.homedir?.() || "/tmp";
703
+ return _path?.join(home, ".gravity") || `${home}/.gravity`;
704
+ }
705
+ function ensureDir(dir) {
706
+ if (!_fs) return;
707
+ try {
708
+ _fs.mkdirSync(dir, { recursive: true });
709
+ } catch {
710
+ }
711
+ }
712
+ function readJSON(filePath, fallback) {
713
+ if (!_fs) return fallback;
714
+ try {
715
+ const raw = _fs.readFileSync(filePath, "utf-8");
716
+ return JSON.parse(raw);
717
+ } catch {
718
+ return fallback;
719
+ }
720
+ }
721
+ function writeJSON(filePath, data) {
722
+ if (!_fs) return;
723
+ try {
724
+ _fs.writeFileSync(filePath, JSON.stringify(data), "utf-8");
725
+ } catch {
726
+ }
727
+ }
728
+ function collectTerminalContext() {
729
+ const os = _os;
730
+ const runtimeTag = (() => {
731
+ if (typeof globalThis !== "undefined") {
732
+ const g = globalThis;
733
+ if (g.Bun && typeof g.Bun === "object" && "version" in g.Bun) {
734
+ return `Bun/${g.Bun.version}`;
735
+ }
736
+ if (g.Deno && typeof g.Deno === "object") {
737
+ const deno = g.Deno;
738
+ const ver = deno.version;
739
+ return `Deno/${ver?.deno || "unknown"}`;
740
+ }
741
+ }
742
+ if (typeof process !== "undefined" && process.versions?.node) {
743
+ return `Node/${process.versions.node}`;
744
+ }
745
+ return "unknown";
746
+ })();
747
+ const cols = typeof process !== "undefined" ? process.stdout?.columns || 80 : 80;
748
+ const rows = typeof process !== "undefined" ? process.stdout?.rows || 24 : 24;
749
+ const env = typeof process !== "undefined" ? process.env : {};
750
+ return {
751
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
752
+ platform: typeof process !== "undefined" ? process.platform : void 0,
753
+ arch: os?.arch(),
754
+ os: os ? `${os.type()} ${os.release()}` : void 0,
755
+ runtime: runtimeTag,
756
+ device_type: env.CI ? "server" : "desktop",
757
+ screen: {
758
+ width: cols,
759
+ height: rows
760
+ },
761
+ viewport: {
762
+ width: cols,
763
+ height: rows
764
+ },
765
+ language: env.LANG?.split(".")[0]?.replace("_", "-") || "en",
766
+ locale: Intl.DateTimeFormat().resolvedOptions().locale,
767
+ hardware_concurrency: os?.cpus()?.length || null,
768
+ device_memory: os ? Math.round(os.totalmem() / (1024 * 1024 * 1024)) : null,
769
+ hostname_hash: null,
770
+ // populated async in start()
771
+ term_program: env.TERM_PROGRAM || void 0,
772
+ term: env.TERM || void 0,
773
+ colorterm: env.COLORTERM || void 0,
774
+ is_ci: !!env.CI
775
+ };
776
+ }
777
+ async function postJSON(url, payload) {
778
+ if (!url) return;
779
+ try {
780
+ await fetch(url, {
781
+ method: "POST",
782
+ headers: { "Content-Type": "application/json" },
783
+ body: JSON.stringify(payload)
784
+ });
785
+ } catch {
786
+ }
787
+ }
788
+ var ATTR_PARAMS = [
789
+ "grclid",
790
+ "grcpid",
791
+ "grpuid",
792
+ "gradid",
793
+ "grsig",
794
+ "graid",
795
+ // OpenAI click identifier — used by the OpenAI conversions passthrough.
796
+ "oppref"
797
+ ];
798
+ var UTM_PARAMS = [
799
+ "utm_source",
800
+ "utm_medium",
801
+ "utm_campaign",
802
+ "utm_term",
803
+ "utm_content",
804
+ "utm_id",
805
+ "utm_source_platform",
806
+ "utm_creative_format",
807
+ "utm_marketing_tactic",
808
+ "gclid",
809
+ "dclid",
810
+ "gbraid",
811
+ "wbraid",
812
+ "msclkid",
813
+ "fbclid",
814
+ "ttclid",
815
+ "twclid",
816
+ "li_fat_id",
817
+ "rdt_cid",
818
+ "ScCid",
819
+ "epik",
820
+ "ko_click_id"
821
+ ];
822
+ var GravityPixel = class {
823
+ constructor(opts) {
824
+ this.attribution = null;
825
+ this.session = null;
826
+ this.isNewSession = false;
827
+ this.contextSent = false;
828
+ this.started = false;
829
+ this.config = {
830
+ pixelId: opts.pixelId,
831
+ eventEndpoint: opts.eventEndpoint || "https://api.trygravity.ai/track/gr-events",
832
+ sessionEndpoint: opts.sessionEndpoint || "https://api.trygravity.ai/track/gr-session",
833
+ sessionTimeoutMinutes: opts.sessionTimeoutMinutes ?? 30,
834
+ attrMaxAgeDays: opts.attrMaxAgeDays ?? 180,
835
+ sessionMaxPages: opts.sessionMaxPages ?? 50,
836
+ hashIdentityFields: opts.hashIdentityFields ?? true,
837
+ storageDir: opts.storageDir || "",
838
+ appName: opts.appName || "terminal"
839
+ };
840
+ }
841
+ // -----------------------------------------------------------------------
842
+ // Lifecycle
843
+ // -----------------------------------------------------------------------
844
+ /**
845
+ * Initialize the pixel: load persisted attribution + session, register
846
+ * process exit hooks, and fire the initial session update.
847
+ */
848
+ async start() {
849
+ if (this.started) return;
850
+ this.started = true;
851
+ await loadModules();
852
+ if (!this.config.storageDir) {
853
+ this.config.storageDir = resolveStorageDir();
854
+ }
855
+ ensureDir(this.config.storageDir);
856
+ this.loadAttribution();
857
+ this.loadSession();
858
+ const context = collectTerminalContext();
859
+ if (_os) {
860
+ const hostname = _os.hostname();
861
+ const hashed = await hashPii({ email: hostname });
862
+ context.hostname_hash = hashed.hashed_email || null;
863
+ }
864
+ const onExit = () => {
865
+ this.persistAll();
866
+ };
867
+ process.on("exit", onExit);
868
+ process.on("SIGINT", () => {
869
+ this.shutdownSync();
870
+ process.exit(0);
871
+ });
872
+ process.on("SIGTERM", () => {
873
+ this.shutdownSync();
874
+ process.exit(0);
875
+ });
876
+ await this.sendSessionUpdate(false, null);
877
+ }
878
+ shutdownSync() {
879
+ this.persistAll();
880
+ this.sendSessionUpdate(true, "exit").catch(() => {
881
+ });
882
+ }
883
+ // -----------------------------------------------------------------------
884
+ // Attribution (replaces captureAttribution + cookie read/write)
885
+ // -----------------------------------------------------------------------
886
+ attrFilePath() {
887
+ return _path?.join(this.config.storageDir, "attribution.json") || `${this.config.storageDir}/attribution.json`;
888
+ }
889
+ loadAttribution() {
890
+ const now = nowMs();
891
+ const stored = readJSON(this.attrFilePath(), {});
892
+ const maxAgeMs = this.config.attrMaxAgeDays * 24 * 60 * 60 * 1e3;
893
+ if (stored.first_seen && now - stored.first_seen > maxAgeMs) {
894
+ this.attribution = {
895
+ gruid: uuid("gruid_"),
896
+ first_seen: now,
897
+ last_seen: now
898
+ };
899
+ this.persistAttribution();
900
+ return;
901
+ }
902
+ this.attribution = {
903
+ gruid: stored.gruid || uuid("gruid_"),
904
+ first_seen: stored.first_seen || now,
905
+ last_seen: now,
906
+ ...stored
907
+ };
908
+ this.attribution.last_seen = now;
909
+ this.persistAttribution();
910
+ }
911
+ persistAttribution() {
912
+ if (!this.attribution) return;
913
+ writeJSON(this.attrFilePath(), this.attribution);
914
+ }
915
+ /**
916
+ * Capture attribution parameters (grclid, graid, UTMs, etc.).
917
+ * Call with params extracted from CLI args, environment variables,
918
+ * deep links, or any other source.
919
+ *
920
+ * Mirrors the same param set that gr-pix.js reads from URL query strings.
921
+ */
922
+ handleAttribution(params) {
923
+ if (!this.attribution) return;
924
+ const now = nowMs();
925
+ let touched = false;
926
+ for (const key of ATTR_PARAMS) {
927
+ const value = params[key];
928
+ if (value) {
929
+ this.attribution[key] = value;
930
+ touched = true;
931
+ }
932
+ }
933
+ for (const key of UTM_PARAMS) {
934
+ const value = params[key];
935
+ if (value) {
936
+ this.attribution[key] = value;
937
+ touched = true;
938
+ }
939
+ }
940
+ if (touched) {
941
+ this.attribution.last_touch = now;
942
+ }
943
+ this.attribution.last_seen = now;
944
+ this.persistAttribution();
945
+ }
946
+ // -----------------------------------------------------------------------
947
+ // Session (replaces loadSession + persistSession + cookie/localStorage)
948
+ // -----------------------------------------------------------------------
949
+ sessionFilePath() {
950
+ return _path?.join(this.config.storageDir, "session.json") || `${this.config.storageDir}/session.json`;
951
+ }
952
+ loadSession() {
953
+ const now = nowMs();
954
+ const timeoutMs = this.config.sessionTimeoutMinutes * 60 * 1e3;
955
+ const stored = readJSON(this.sessionFilePath(), null);
956
+ const appUri = `terminal://${this.config.appName}`;
957
+ if (!stored || !stored.id || typeof stored.started_at !== "number" || now - (stored.last_seen || 0) > timeoutMs) {
958
+ this.isNewSession = true;
959
+ this.session = {
960
+ id: uuid("gr_sess_"),
961
+ started_at: now,
962
+ last_seen: now,
963
+ page_views: 0,
964
+ landing_url: appUri,
965
+ entry_referrer: null,
966
+ last_page_url: appUri,
967
+ last_page_title: this.config.appName,
968
+ visitor_id: this.attribution?.gruid || "",
969
+ page_history: []
970
+ };
971
+ } else {
972
+ this.isNewSession = false;
973
+ this.session = { ...stored, last_seen: now };
974
+ }
975
+ this.session.page_views += 1;
976
+ this.session.last_page_url = appUri;
977
+ this.session.last_page_title = this.config.appName;
978
+ this.session.visitor_id = this.attribution?.gruid || "";
979
+ this.session.page_history.push({
980
+ url: appUri,
981
+ title: this.config.appName,
982
+ timestamp: new Date(now).toISOString()
983
+ });
984
+ const maxPages = this.config.sessionMaxPages;
985
+ if (this.session.page_history.length > maxPages) {
986
+ this.session.page_history.splice(
987
+ 0,
988
+ this.session.page_history.length - maxPages
989
+ );
990
+ }
991
+ this.persistSession();
992
+ }
993
+ persistSession() {
994
+ if (!this.session) return;
995
+ writeJSON(this.sessionFilePath(), this.session);
996
+ }
997
+ persistAll() {
998
+ this.persistAttribution();
999
+ this.persistSession();
1000
+ }
1001
+ // -----------------------------------------------------------------------
1002
+ // Event tracking (replaces trackEvent + baseEventPayload)
1003
+ // -----------------------------------------------------------------------
1004
+ /**
1005
+ * Fire a tracking event. Mirrors `window.gravityPixel.track()`.
1006
+ *
1007
+ * @param eventType - e.g. 'query', 'response', 'purchase', 'page_view'
1008
+ * @param metadata - arbitrary key-value pairs attached to the event
1009
+ */
1010
+ async track(eventType, metadata = {}) {
1011
+ if (!this.session || !this.attribution) return;
1012
+ const now = nowMs();
1013
+ this.session.last_seen = now;
1014
+ this.persistSession();
1015
+ const payload = {
1016
+ event_id: uuid("gr_evt_"),
1017
+ event_timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1018
+ session_id: this.session.id,
1019
+ visitor_id: this.attribution.gruid,
1020
+ click_id: this.attribution.grclid || null,
1021
+ pixel_id: this.config.pixelId || null,
1022
+ page_url: this.session.last_page_url,
1023
+ page_title: this.session.last_page_title || null,
1024
+ referrer: null,
1025
+ user_agent: this.buildUserAgent(),
1026
+ language: (typeof process !== "undefined" ? process.env.LANG?.split(".")[0]?.replace("_", "-") : void 0) || "en",
1027
+ screen: {
1028
+ width: typeof process !== "undefined" ? process.stdout?.columns || 80 : 80,
1029
+ height: typeof process !== "undefined" ? process.stdout?.rows || 24 : 24
1030
+ },
1031
+ event_type: eventType,
1032
+ session_start: this.isNewSession,
1033
+ metadata: {
1034
+ ...metadata,
1035
+ visitor: {
1036
+ id: this.attribution.gruid,
1037
+ click_id: this.attribution.grclid || null
1038
+ },
1039
+ pixel_source: "terminal"
1040
+ },
1041
+ context: collectTerminalContext(),
1042
+ attribution: { ...this.attribution }
1043
+ };
1044
+ this.isNewSession = false;
1045
+ await postJSON(this.config.eventEndpoint, payload);
1046
+ }
1047
+ /**
1048
+ * Track an event with identity fields (email, phone).
1049
+ * Fields are hashed with SHA-256 before sending (same normalization
1050
+ * as gr-pix.js: email lowercased+trimmed, phone digits-only).
1051
+ */
1052
+ async trackWithIdentity(eventType, identity, metadata = {}) {
1053
+ if (this.config.hashIdentityFields) {
1054
+ const hashed = await hashPii(identity);
1055
+ metadata.identity = hashed;
1056
+ } else {
1057
+ metadata.identity = identity;
1058
+ }
1059
+ return this.track(eventType, metadata);
1060
+ }
1061
+ // -----------------------------------------------------------------------
1062
+ // Session reporting (replaces sendSessionUpdate + sessionPayload)
1063
+ // -----------------------------------------------------------------------
1064
+ async sendSessionUpdate(ended, reason) {
1065
+ if (!this.session || !this.attribution) return;
1066
+ this.persistSession();
1067
+ const durationMs = Date.now() - this.session.started_at;
1068
+ const payload = {
1069
+ session_id: this.session.id,
1070
+ visitor_id: this.attribution.gruid,
1071
+ pixel_id: this.config.pixelId || null,
1072
+ new_session: this.isNewSession,
1073
+ started_at: new Date(this.session.started_at).toISOString(),
1074
+ last_seen_at: new Date(this.session.last_seen).toISOString(),
1075
+ duration_ms: durationMs,
1076
+ page_views: this.session.page_views,
1077
+ landing_url: this.session.landing_url,
1078
+ last_page_url: this.session.last_page_url,
1079
+ entry_referrer: this.session.entry_referrer,
1080
+ last_referrer: null,
1081
+ ended,
1082
+ reason,
1083
+ attribution: { ...this.attribution },
1084
+ page_history: this.session.page_history
1085
+ };
1086
+ if (!this.contextSent) {
1087
+ payload.context = collectTerminalContext();
1088
+ this.contextSent = true;
1089
+ }
1090
+ await postJSON(this.config.sessionEndpoint, payload);
1091
+ }
1092
+ // -----------------------------------------------------------------------
1093
+ // Public getters (same API surface as window.gravityPixel.*)
1094
+ // -----------------------------------------------------------------------
1095
+ /** Stable first-party visitor ID (gruid_...). */
1096
+ getVisitorId() {
1097
+ return this.attribution?.gruid;
1098
+ }
1099
+ /** Current session ID (gr_sess_...). */
1100
+ getSessionId() {
1101
+ return this.session?.id;
1102
+ }
1103
+ /** Inbound Gravity click ID if present. */
1104
+ getClickId() {
1105
+ return this.attribution?.grclid;
1106
+ }
1107
+ /** Inbound Gravity ad identifier if present. */
1108
+ getGraid() {
1109
+ return this.attribution?.graid;
1110
+ }
1111
+ /** Full attribution object. */
1112
+ getAttribution() {
1113
+ return { ...this.attribution || {} };
1114
+ }
1115
+ // -----------------------------------------------------------------------
1116
+ // Internal helpers
1117
+ // -----------------------------------------------------------------------
1118
+ buildUserAgent() {
1119
+ let runtimeTag = "unknown";
1120
+ if (typeof process !== "undefined" && process.versions?.node) {
1121
+ runtimeTag = `Node/${process.versions.node}`;
1122
+ }
1123
+ const osInfo = _os ? `${_os.type()} ${_os.arch()}` : "unknown";
1124
+ return `gravity-pixel/1.0.0 (${osInfo}; ${runtimeTag})`;
1125
+ }
1126
+ };
1127
+ function gravityPixel(opts) {
1128
+ return new GravityPixel(opts);
1129
+ }
557
1130
  // Annotate the CommonJS export names for ESM import in node:
558
1131
  0 && (module.exports = {
559
1132
  Client,
560
1133
  Gravity,
1134
+ GravityPixel,
1135
+ detectCmpConsent,
561
1136
  extractClientIp,
562
1137
  gravityAds,
563
1138
  gravityContext,
1139
+ gravityContextAsync,
1140
+ gravityPixel,
564
1141
  hashPii,
1142
+ readCmpConsent,
565
1143
  toGravityMessages
566
1144
  });