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