@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.mjs CHANGED
@@ -8,7 +8,7 @@ var require_package = __commonJS({
8
8
  "package.json"(exports, module) {
9
9
  module.exports = {
10
10
  name: "@gravity-ai/api",
11
- version: "1.1.8",
11
+ version: "1.2.0",
12
12
  description: "Gravity JS SDK for retrieving targeted advertisements",
13
13
  main: "dist/index.js",
14
14
  module: "dist/index.mjs",
@@ -92,7 +92,7 @@ var require_package = __commonJS({
92
92
 
93
93
  // ads.ts
94
94
  var DEFAULT_GRAVITY_API = "https://server.trygravity.ai/api/v1/ad";
95
- var DEFAULT_TIMEOUT_MS = 3e3;
95
+ var DEFAULT_TIMEOUT_MS = 4e3;
96
96
  function toGravityMessages(messages, maxTurns = 2) {
97
97
  if (!messages || messages.length === 0) return [];
98
98
  return messages.slice(-maxTurns).map((m) => ({
@@ -137,8 +137,17 @@ async function gravityAds(req, messages, placements, opts = {}) {
137
137
  ...clientIp ? { ip: clientIp } : {}
138
138
  }
139
139
  };
140
+ if (ctx?.consent && typeof ctx.consent === "object") {
141
+ body.consent = ctx.consent;
142
+ }
140
143
  body.relevancy = opts.relevancy ?? 0.2;
141
144
  body.testAd = opts.production === true ? false : true;
145
+ if (body.testAd && opts.alwaysReturn === true) body.alwaysReturn = true;
146
+ const supportsSpec = opts.supportsSpec ?? true;
147
+ body.supportsSpec = supportsSpec;
148
+ if (supportsSpec) body.specCapabilities = opts.specCapabilities ?? "web1";
149
+ if (opts.enableFrames ?? supportsSpec) body.supportsFrames = true;
150
+ if (body.testAd && opts.adLayout) body.adLayout = opts.adLayout;
142
151
  if (opts.excludedTopics) body.excludedTopics = opts.excludedTopics;
143
152
  const start = performance.now();
144
153
  try {
@@ -152,8 +161,8 @@ async function gravityAds(req, messages, placements, opts = {}) {
152
161
  signal: AbortSignal.timeout(timeoutMs)
153
162
  });
154
163
  const elapsed = (performance.now() - start).toFixed(0);
155
- if (res.status === 204) {
156
- return { ads: [], status: 204, elapsed, requestBody: body };
164
+ if (res.status === 204 || res.status === 202) {
165
+ return { ads: [], status: res.status, elapsed, requestBody: body };
157
166
  }
158
167
  if (!res.ok) {
159
168
  const errText = await res.text().catch(() => "");
@@ -184,8 +193,9 @@ var Gravity = class {
184
193
  * |--------|------|---------|-------------|
185
194
  * | `apiKey` | `string` | `process.env.GRAVITY_API_KEY` | Gravity API key |
186
195
  * | `production` | `boolean` | `false` | `true` = real ads. `false` = test ads (no billing). |
196
+ * | `alwaysReturn` | `boolean` | `false` | Test-only: return a default test ad instead of a 204 no-fill. Ignored in production. |
187
197
  * | `relevancy` | `number` | `0.2` | Minimum relevancy threshold (0-1) |
188
- * | `timeoutMs` | `number` | `3000` | Request timeout in ms |
198
+ * | `timeoutMs` | `number` | `4000` | Request timeout in ms |
189
199
  * | `excludedTopics` | `string[]` | — | Topics to exclude from ad matching |
190
200
  * | `gravityApi` | `string` | production URL | Custom API endpoint |
191
201
  */
@@ -213,6 +223,99 @@ var Gravity = class {
213
223
  }
214
224
  };
215
225
 
226
+ // ../ui/src/consent.ts
227
+ function findCmpApi(name) {
228
+ if (typeof window === "undefined") return void 0;
229
+ let frame = window;
230
+ for (let hops = 0; frame && hops < 10; hops++) {
231
+ try {
232
+ const api = frame[name];
233
+ if (typeof api === "function") return api;
234
+ } catch {
235
+ break;
236
+ }
237
+ if (frame === frame.parent) break;
238
+ frame = frame.parent;
239
+ }
240
+ return void 0;
241
+ }
242
+ var cachedTcf;
243
+ var cachedUsp;
244
+ var tcfListening = false;
245
+ var cmpWaitExhausted = false;
246
+ function ensureListening() {
247
+ if (typeof window === "undefined") return;
248
+ const tcfapi = tcfListening ? void 0 : findCmpApi("__tcfapi");
249
+ if (tcfapi) {
250
+ tcfListening = true;
251
+ try {
252
+ tcfapi("addEventListener", 2, (data, success) => {
253
+ if (!success || typeof data !== "object" || data === null) return;
254
+ const tc = data;
255
+ if (tc.eventStatus === "tcloaded" || tc.eventStatus === "useractioncomplete") {
256
+ cachedTcf = {
257
+ gdprApplies: typeof tc.gdprApplies === "boolean" ? tc.gdprApplies : void 0,
258
+ tcfString: typeof tc.tcString === "string" && tc.tcString ? tc.tcString : void 0
259
+ };
260
+ } else if (typeof tc.gdprApplies === "boolean" && !tc.gdprApplies) {
261
+ cachedTcf = { gdprApplies: false };
262
+ }
263
+ });
264
+ } catch {
265
+ }
266
+ }
267
+ const uspapi = findCmpApi("__uspapi");
268
+ if (uspapi) {
269
+ try {
270
+ uspapi("getUSPData", 1, (data, success) => {
271
+ if (!success || typeof data !== "object" || data === null) return;
272
+ const usp = data.uspString;
273
+ if (typeof usp === "string" && usp) cachedUsp = usp;
274
+ });
275
+ } catch {
276
+ }
277
+ }
278
+ }
279
+ function detectCmpConsent() {
280
+ ensureListening();
281
+ if (!cachedTcf && !cachedUsp) return void 0;
282
+ const consent = {};
283
+ if (cachedTcf?.gdprApplies !== void 0) consent.gdprApplies = cachedTcf.gdprApplies;
284
+ if (cachedTcf?.tcfString) consent.tcfString = cachedTcf.tcfString;
285
+ if (cachedUsp) consent.usPrivacy = cachedUsp;
286
+ if (Object.keys(consent).length === 0) return void 0;
287
+ return consent;
288
+ }
289
+ var NO_CMP_GRACE_MS = 150;
290
+ var graceStartedAt = typeof window === "undefined" ? 0 : Date.now();
291
+ if (typeof window !== "undefined") ensureListening();
292
+ function readCmpConsent(timeoutMs = 500) {
293
+ ensureListening();
294
+ const immediate = detectCmpConsent();
295
+ if (immediate || cmpWaitExhausted || typeof window === "undefined") {
296
+ return Promise.resolve(immediate);
297
+ }
298
+ return new Promise((resolve) => {
299
+ const started = Date.now();
300
+ const poll = () => {
301
+ const consent = detectCmpConsent();
302
+ if (consent) return resolve(consent);
303
+ const elapsed = Date.now() - started;
304
+ const cmpPresent = Boolean(findCmpApi("__tcfapi") || findCmpApi("__uspapi"));
305
+ if (cmpPresent) {
306
+ if (elapsed >= timeoutMs) {
307
+ cmpWaitExhausted = true;
308
+ return resolve(void 0);
309
+ }
310
+ } else if (elapsed >= timeoutMs || Date.now() - graceStartedAt >= NO_CMP_GRACE_MS) {
311
+ return resolve(void 0);
312
+ }
313
+ setTimeout(poll, 50);
314
+ };
315
+ poll();
316
+ });
317
+ }
318
+
216
319
  // context.ts
217
320
  function readPixel(method) {
218
321
  if (typeof window === "undefined") return void 0;
@@ -250,12 +353,19 @@ function gravityContext(overrides) {
250
353
  if (gruid) pixelUserFields.gruid = gruid;
251
354
  if (grclid) pixelUserFields.grclid = grclid;
252
355
  if (graid) pixelUserFields.graid = graid;
356
+ const consent = overrides.consent ?? (isBrowser ? detectCmpConsent() : void 0);
253
357
  return {
254
358
  sessionId,
255
359
  user: { ...pixelUserFields, ...restUser, id: userId },
256
- device
360
+ device,
361
+ ...consent ? { consent } : {}
257
362
  };
258
363
  }
364
+ async function gravityContextAsync(overrides) {
365
+ const isBrowser = typeof window !== "undefined" && typeof navigator !== "undefined";
366
+ const consent = overrides.consent ?? (isBrowser ? await readCmpConsent() : void 0);
367
+ return gravityContext(consent ? { ...overrides, consent } : overrides);
368
+ }
259
369
  function browserDevice() {
260
370
  const nav = typeof navigator !== "undefined" ? navigator : void 0;
261
371
  const win = typeof window !== "undefined" ? window : void 0;
@@ -427,8 +537,13 @@ var Client = class {
427
537
  */
428
538
  async getAd(params) {
429
539
  try {
540
+ const supportsSpec = params.supportsSpec ?? true;
541
+ const { enableFrames, ...requestParams } = params;
430
542
  const body = {
431
- ...params,
543
+ ...requestParams,
544
+ ...enableFrames ?? supportsSpec ? { supportsFrames: true } : {},
545
+ supportsSpec,
546
+ ...supportsSpec ? { specCapabilities: params.specCapabilities ?? "web1" } : { specCapabilities: void 0 },
432
547
  excludedTopics: params.excludedTopics ?? this.excludedTopics,
433
548
  relevancy: params.relevancy ?? this.relevancy
434
549
  };
@@ -514,12 +629,470 @@ async function hashPii(values) {
514
629
  if (hashedPhone) out.hashed_phone = hashedPhone;
515
630
  return out;
516
631
  }
632
+
633
+ // gravity-pixel.ts
634
+ function uuid(prefix) {
635
+ const hex = () => Math.random().toString(36).slice(2, 10);
636
+ return prefix + hex() + hex();
637
+ }
638
+ function nowMs() {
639
+ return Date.now();
640
+ }
641
+ var _fs;
642
+ var _path;
643
+ var _os;
644
+ var _modulesLoaded = false;
645
+ async function loadModules() {
646
+ if (_modulesLoaded) return;
647
+ _modulesLoaded = true;
648
+ try {
649
+ _fs = await import("fs");
650
+ _path = await import("path");
651
+ _os = await import("os");
652
+ } catch {
653
+ }
654
+ }
655
+ function resolveStorageDir(custom) {
656
+ if (custom) return custom;
657
+ const home = _os?.homedir?.() || "/tmp";
658
+ return _path?.join(home, ".gravity") || `${home}/.gravity`;
659
+ }
660
+ function ensureDir(dir) {
661
+ if (!_fs) return;
662
+ try {
663
+ _fs.mkdirSync(dir, { recursive: true });
664
+ } catch {
665
+ }
666
+ }
667
+ function readJSON(filePath, fallback) {
668
+ if (!_fs) return fallback;
669
+ try {
670
+ const raw = _fs.readFileSync(filePath, "utf-8");
671
+ return JSON.parse(raw);
672
+ } catch {
673
+ return fallback;
674
+ }
675
+ }
676
+ function writeJSON(filePath, data) {
677
+ if (!_fs) return;
678
+ try {
679
+ _fs.writeFileSync(filePath, JSON.stringify(data), "utf-8");
680
+ } catch {
681
+ }
682
+ }
683
+ function collectTerminalContext() {
684
+ const os = _os;
685
+ const runtimeTag = (() => {
686
+ if (typeof globalThis !== "undefined") {
687
+ const g = globalThis;
688
+ if (g.Bun && typeof g.Bun === "object" && "version" in g.Bun) {
689
+ return `Bun/${g.Bun.version}`;
690
+ }
691
+ if (g.Deno && typeof g.Deno === "object") {
692
+ const deno = g.Deno;
693
+ const ver = deno.version;
694
+ return `Deno/${ver?.deno || "unknown"}`;
695
+ }
696
+ }
697
+ if (typeof process !== "undefined" && process.versions?.node) {
698
+ return `Node/${process.versions.node}`;
699
+ }
700
+ return "unknown";
701
+ })();
702
+ const cols = typeof process !== "undefined" ? process.stdout?.columns || 80 : 80;
703
+ const rows = typeof process !== "undefined" ? process.stdout?.rows || 24 : 24;
704
+ const env = typeof process !== "undefined" ? process.env : {};
705
+ return {
706
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
707
+ platform: typeof process !== "undefined" ? process.platform : void 0,
708
+ arch: os?.arch(),
709
+ os: os ? `${os.type()} ${os.release()}` : void 0,
710
+ runtime: runtimeTag,
711
+ device_type: env.CI ? "server" : "desktop",
712
+ screen: {
713
+ width: cols,
714
+ height: rows
715
+ },
716
+ viewport: {
717
+ width: cols,
718
+ height: rows
719
+ },
720
+ language: env.LANG?.split(".")[0]?.replace("_", "-") || "en",
721
+ locale: Intl.DateTimeFormat().resolvedOptions().locale,
722
+ hardware_concurrency: os?.cpus()?.length || null,
723
+ device_memory: os ? Math.round(os.totalmem() / (1024 * 1024 * 1024)) : null,
724
+ hostname_hash: null,
725
+ // populated async in start()
726
+ term_program: env.TERM_PROGRAM || void 0,
727
+ term: env.TERM || void 0,
728
+ colorterm: env.COLORTERM || void 0,
729
+ is_ci: !!env.CI
730
+ };
731
+ }
732
+ async function postJSON(url, payload) {
733
+ if (!url) return;
734
+ try {
735
+ await fetch(url, {
736
+ method: "POST",
737
+ headers: { "Content-Type": "application/json" },
738
+ body: JSON.stringify(payload)
739
+ });
740
+ } catch {
741
+ }
742
+ }
743
+ var ATTR_PARAMS = [
744
+ "grclid",
745
+ "grcpid",
746
+ "grpuid",
747
+ "gradid",
748
+ "grsig",
749
+ "graid",
750
+ // OpenAI click identifier — used by the OpenAI conversions passthrough.
751
+ "oppref"
752
+ ];
753
+ var UTM_PARAMS = [
754
+ "utm_source",
755
+ "utm_medium",
756
+ "utm_campaign",
757
+ "utm_term",
758
+ "utm_content",
759
+ "utm_id",
760
+ "utm_source_platform",
761
+ "utm_creative_format",
762
+ "utm_marketing_tactic",
763
+ "gclid",
764
+ "dclid",
765
+ "gbraid",
766
+ "wbraid",
767
+ "msclkid",
768
+ "fbclid",
769
+ "ttclid",
770
+ "twclid",
771
+ "li_fat_id",
772
+ "rdt_cid",
773
+ "ScCid",
774
+ "epik",
775
+ "ko_click_id"
776
+ ];
777
+ var GravityPixel = class {
778
+ constructor(opts) {
779
+ this.attribution = null;
780
+ this.session = null;
781
+ this.isNewSession = false;
782
+ this.contextSent = false;
783
+ this.started = false;
784
+ this.config = {
785
+ pixelId: opts.pixelId,
786
+ eventEndpoint: opts.eventEndpoint || "https://api.trygravity.ai/track/gr-events",
787
+ sessionEndpoint: opts.sessionEndpoint || "https://api.trygravity.ai/track/gr-session",
788
+ sessionTimeoutMinutes: opts.sessionTimeoutMinutes ?? 30,
789
+ attrMaxAgeDays: opts.attrMaxAgeDays ?? 180,
790
+ sessionMaxPages: opts.sessionMaxPages ?? 50,
791
+ hashIdentityFields: opts.hashIdentityFields ?? true,
792
+ storageDir: opts.storageDir || "",
793
+ appName: opts.appName || "terminal"
794
+ };
795
+ }
796
+ // -----------------------------------------------------------------------
797
+ // Lifecycle
798
+ // -----------------------------------------------------------------------
799
+ /**
800
+ * Initialize the pixel: load persisted attribution + session, register
801
+ * process exit hooks, and fire the initial session update.
802
+ */
803
+ async start() {
804
+ if (this.started) return;
805
+ this.started = true;
806
+ await loadModules();
807
+ if (!this.config.storageDir) {
808
+ this.config.storageDir = resolveStorageDir();
809
+ }
810
+ ensureDir(this.config.storageDir);
811
+ this.loadAttribution();
812
+ this.loadSession();
813
+ const context = collectTerminalContext();
814
+ if (_os) {
815
+ const hostname = _os.hostname();
816
+ const hashed = await hashPii({ email: hostname });
817
+ context.hostname_hash = hashed.hashed_email || null;
818
+ }
819
+ const onExit = () => {
820
+ this.persistAll();
821
+ };
822
+ process.on("exit", onExit);
823
+ process.on("SIGINT", () => {
824
+ this.shutdownSync();
825
+ process.exit(0);
826
+ });
827
+ process.on("SIGTERM", () => {
828
+ this.shutdownSync();
829
+ process.exit(0);
830
+ });
831
+ await this.sendSessionUpdate(false, null);
832
+ }
833
+ shutdownSync() {
834
+ this.persistAll();
835
+ this.sendSessionUpdate(true, "exit").catch(() => {
836
+ });
837
+ }
838
+ // -----------------------------------------------------------------------
839
+ // Attribution (replaces captureAttribution + cookie read/write)
840
+ // -----------------------------------------------------------------------
841
+ attrFilePath() {
842
+ return _path?.join(this.config.storageDir, "attribution.json") || `${this.config.storageDir}/attribution.json`;
843
+ }
844
+ loadAttribution() {
845
+ const now = nowMs();
846
+ const stored = readJSON(this.attrFilePath(), {});
847
+ const maxAgeMs = this.config.attrMaxAgeDays * 24 * 60 * 60 * 1e3;
848
+ if (stored.first_seen && now - stored.first_seen > maxAgeMs) {
849
+ this.attribution = {
850
+ gruid: uuid("gruid_"),
851
+ first_seen: now,
852
+ last_seen: now
853
+ };
854
+ this.persistAttribution();
855
+ return;
856
+ }
857
+ this.attribution = {
858
+ gruid: stored.gruid || uuid("gruid_"),
859
+ first_seen: stored.first_seen || now,
860
+ last_seen: now,
861
+ ...stored
862
+ };
863
+ this.attribution.last_seen = now;
864
+ this.persistAttribution();
865
+ }
866
+ persistAttribution() {
867
+ if (!this.attribution) return;
868
+ writeJSON(this.attrFilePath(), this.attribution);
869
+ }
870
+ /**
871
+ * Capture attribution parameters (grclid, graid, UTMs, etc.).
872
+ * Call with params extracted from CLI args, environment variables,
873
+ * deep links, or any other source.
874
+ *
875
+ * Mirrors the same param set that gr-pix.js reads from URL query strings.
876
+ */
877
+ handleAttribution(params) {
878
+ if (!this.attribution) return;
879
+ const now = nowMs();
880
+ let touched = false;
881
+ for (const key of ATTR_PARAMS) {
882
+ const value = params[key];
883
+ if (value) {
884
+ this.attribution[key] = value;
885
+ touched = true;
886
+ }
887
+ }
888
+ for (const key of UTM_PARAMS) {
889
+ const value = params[key];
890
+ if (value) {
891
+ this.attribution[key] = value;
892
+ touched = true;
893
+ }
894
+ }
895
+ if (touched) {
896
+ this.attribution.last_touch = now;
897
+ }
898
+ this.attribution.last_seen = now;
899
+ this.persistAttribution();
900
+ }
901
+ // -----------------------------------------------------------------------
902
+ // Session (replaces loadSession + persistSession + cookie/localStorage)
903
+ // -----------------------------------------------------------------------
904
+ sessionFilePath() {
905
+ return _path?.join(this.config.storageDir, "session.json") || `${this.config.storageDir}/session.json`;
906
+ }
907
+ loadSession() {
908
+ const now = nowMs();
909
+ const timeoutMs = this.config.sessionTimeoutMinutes * 60 * 1e3;
910
+ const stored = readJSON(this.sessionFilePath(), null);
911
+ const appUri = `terminal://${this.config.appName}`;
912
+ if (!stored || !stored.id || typeof stored.started_at !== "number" || now - (stored.last_seen || 0) > timeoutMs) {
913
+ this.isNewSession = true;
914
+ this.session = {
915
+ id: uuid("gr_sess_"),
916
+ started_at: now,
917
+ last_seen: now,
918
+ page_views: 0,
919
+ landing_url: appUri,
920
+ entry_referrer: null,
921
+ last_page_url: appUri,
922
+ last_page_title: this.config.appName,
923
+ visitor_id: this.attribution?.gruid || "",
924
+ page_history: []
925
+ };
926
+ } else {
927
+ this.isNewSession = false;
928
+ this.session = { ...stored, last_seen: now };
929
+ }
930
+ this.session.page_views += 1;
931
+ this.session.last_page_url = appUri;
932
+ this.session.last_page_title = this.config.appName;
933
+ this.session.visitor_id = this.attribution?.gruid || "";
934
+ this.session.page_history.push({
935
+ url: appUri,
936
+ title: this.config.appName,
937
+ timestamp: new Date(now).toISOString()
938
+ });
939
+ const maxPages = this.config.sessionMaxPages;
940
+ if (this.session.page_history.length > maxPages) {
941
+ this.session.page_history.splice(
942
+ 0,
943
+ this.session.page_history.length - maxPages
944
+ );
945
+ }
946
+ this.persistSession();
947
+ }
948
+ persistSession() {
949
+ if (!this.session) return;
950
+ writeJSON(this.sessionFilePath(), this.session);
951
+ }
952
+ persistAll() {
953
+ this.persistAttribution();
954
+ this.persistSession();
955
+ }
956
+ // -----------------------------------------------------------------------
957
+ // Event tracking (replaces trackEvent + baseEventPayload)
958
+ // -----------------------------------------------------------------------
959
+ /**
960
+ * Fire a tracking event. Mirrors `window.gravityPixel.track()`.
961
+ *
962
+ * @param eventType - e.g. 'query', 'response', 'purchase', 'page_view'
963
+ * @param metadata - arbitrary key-value pairs attached to the event
964
+ */
965
+ async track(eventType, metadata = {}) {
966
+ if (!this.session || !this.attribution) return;
967
+ const now = nowMs();
968
+ this.session.last_seen = now;
969
+ this.persistSession();
970
+ const payload = {
971
+ event_id: uuid("gr_evt_"),
972
+ event_timestamp: (/* @__PURE__ */ new Date()).toISOString(),
973
+ session_id: this.session.id,
974
+ visitor_id: this.attribution.gruid,
975
+ click_id: this.attribution.grclid || null,
976
+ pixel_id: this.config.pixelId || null,
977
+ page_url: this.session.last_page_url,
978
+ page_title: this.session.last_page_title || null,
979
+ referrer: null,
980
+ user_agent: this.buildUserAgent(),
981
+ language: (typeof process !== "undefined" ? process.env.LANG?.split(".")[0]?.replace("_", "-") : void 0) || "en",
982
+ screen: {
983
+ width: typeof process !== "undefined" ? process.stdout?.columns || 80 : 80,
984
+ height: typeof process !== "undefined" ? process.stdout?.rows || 24 : 24
985
+ },
986
+ event_type: eventType,
987
+ session_start: this.isNewSession,
988
+ metadata: {
989
+ ...metadata,
990
+ visitor: {
991
+ id: this.attribution.gruid,
992
+ click_id: this.attribution.grclid || null
993
+ },
994
+ pixel_source: "terminal"
995
+ },
996
+ context: collectTerminalContext(),
997
+ attribution: { ...this.attribution }
998
+ };
999
+ this.isNewSession = false;
1000
+ await postJSON(this.config.eventEndpoint, payload);
1001
+ }
1002
+ /**
1003
+ * Track an event with identity fields (email, phone).
1004
+ * Fields are hashed with SHA-256 before sending (same normalization
1005
+ * as gr-pix.js: email lowercased+trimmed, phone digits-only).
1006
+ */
1007
+ async trackWithIdentity(eventType, identity, metadata = {}) {
1008
+ if (this.config.hashIdentityFields) {
1009
+ const hashed = await hashPii(identity);
1010
+ metadata.identity = hashed;
1011
+ } else {
1012
+ metadata.identity = identity;
1013
+ }
1014
+ return this.track(eventType, metadata);
1015
+ }
1016
+ // -----------------------------------------------------------------------
1017
+ // Session reporting (replaces sendSessionUpdate + sessionPayload)
1018
+ // -----------------------------------------------------------------------
1019
+ async sendSessionUpdate(ended, reason) {
1020
+ if (!this.session || !this.attribution) return;
1021
+ this.persistSession();
1022
+ const durationMs = Date.now() - this.session.started_at;
1023
+ const payload = {
1024
+ session_id: this.session.id,
1025
+ visitor_id: this.attribution.gruid,
1026
+ pixel_id: this.config.pixelId || null,
1027
+ new_session: this.isNewSession,
1028
+ started_at: new Date(this.session.started_at).toISOString(),
1029
+ last_seen_at: new Date(this.session.last_seen).toISOString(),
1030
+ duration_ms: durationMs,
1031
+ page_views: this.session.page_views,
1032
+ landing_url: this.session.landing_url,
1033
+ last_page_url: this.session.last_page_url,
1034
+ entry_referrer: this.session.entry_referrer,
1035
+ last_referrer: null,
1036
+ ended,
1037
+ reason,
1038
+ attribution: { ...this.attribution },
1039
+ page_history: this.session.page_history
1040
+ };
1041
+ if (!this.contextSent) {
1042
+ payload.context = collectTerminalContext();
1043
+ this.contextSent = true;
1044
+ }
1045
+ await postJSON(this.config.sessionEndpoint, payload);
1046
+ }
1047
+ // -----------------------------------------------------------------------
1048
+ // Public getters (same API surface as window.gravityPixel.*)
1049
+ // -----------------------------------------------------------------------
1050
+ /** Stable first-party visitor ID (gruid_...). */
1051
+ getVisitorId() {
1052
+ return this.attribution?.gruid;
1053
+ }
1054
+ /** Current session ID (gr_sess_...). */
1055
+ getSessionId() {
1056
+ return this.session?.id;
1057
+ }
1058
+ /** Inbound Gravity click ID if present. */
1059
+ getClickId() {
1060
+ return this.attribution?.grclid;
1061
+ }
1062
+ /** Inbound Gravity ad identifier if present. */
1063
+ getGraid() {
1064
+ return this.attribution?.graid;
1065
+ }
1066
+ /** Full attribution object. */
1067
+ getAttribution() {
1068
+ return { ...this.attribution || {} };
1069
+ }
1070
+ // -----------------------------------------------------------------------
1071
+ // Internal helpers
1072
+ // -----------------------------------------------------------------------
1073
+ buildUserAgent() {
1074
+ let runtimeTag = "unknown";
1075
+ if (typeof process !== "undefined" && process.versions?.node) {
1076
+ runtimeTag = `Node/${process.versions.node}`;
1077
+ }
1078
+ const osInfo = _os ? `${_os.type()} ${_os.arch()}` : "unknown";
1079
+ return `gravity-pixel/1.0.0 (${osInfo}; ${runtimeTag})`;
1080
+ }
1081
+ };
1082
+ function gravityPixel(opts) {
1083
+ return new GravityPixel(opts);
1084
+ }
517
1085
  export {
518
1086
  Client,
519
1087
  Gravity,
1088
+ GravityPixel,
1089
+ detectCmpConsent,
520
1090
  extractClientIp,
521
1091
  gravityAds,
522
1092
  gravityContext,
1093
+ gravityContextAsync,
1094
+ gravityPixel,
523
1095
  hashPii,
1096
+ readCmpConsent,
524
1097
  toGravityMessages
525
1098
  };
@@ -1,4 +1,4 @@
1
- import { d as Ad } from './types-BHk98aM_.mjs';
1
+ import { d as Ad } from './types-CnuFH98L.mjs';
2
2
 
3
3
  /**
4
4
  * @gravity-ai/api/opentui — Gravity ad rendering + tracking for OpenTUI terminals
package/dist/opentui.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { d as Ad } from './types-BHk98aM_.js';
1
+ import { d as Ad } from './types-CnuFH98L.js';
2
2
 
3
3
  /**
4
4
  * @gravity-ai/api/opentui — Gravity ad rendering + tracking for OpenTUI terminals