@gravity-ai/api 1.5.0 → 1.6.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.5.0",
11
+ version: "1.6.0",
12
12
  description: "Gravity JS SDK for retrieving targeted advertisements",
13
13
  main: "dist/index.js",
14
14
  module: "dist/index.mjs",
@@ -537,10 +537,256 @@ async function gravityAds(req, messages, placements, opts = {}) {
537
537
  }
538
538
  }
539
539
 
540
+ // hash.ts
541
+ async function sha256Hex(value) {
542
+ const subtle = typeof globalThis !== "undefined" && globalThis.crypto?.subtle || void 0;
543
+ if (!subtle) return void 0;
544
+ try {
545
+ const bytes = new TextEncoder().encode(value);
546
+ const digest = await subtle.digest("SHA-256", bytes);
547
+ const hex2 = Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
548
+ return hex2;
549
+ } catch {
550
+ return void 0;
551
+ }
552
+ }
553
+ function normalizeEmail(raw) {
554
+ if (typeof raw !== "string") return void 0;
555
+ const trimmed = raw.trim().toLowerCase();
556
+ return trimmed || void 0;
557
+ }
558
+ function normalizePhone(raw) {
559
+ if (typeof raw !== "string") return void 0;
560
+ const digits = raw.replace(/\D+/g, "");
561
+ return digits || void 0;
562
+ }
563
+ async function hashPii(values) {
564
+ const out = {};
565
+ const emailNorm = normalizeEmail(values.email ?? void 0);
566
+ const phoneNorm = normalizePhone(values.phone ?? void 0);
567
+ const [hashedEmail, hashedPhone] = await Promise.all([
568
+ emailNorm ? sha256Hex(emailNorm) : Promise.resolve(void 0),
569
+ phoneNorm ? sha256Hex(phoneNorm) : Promise.resolve(void 0)
570
+ ]);
571
+ if (hashedEmail) out.hashed_email = hashedEmail;
572
+ if (hashedPhone) out.hashed_phone = hashedPhone;
573
+ return out;
574
+ }
575
+
576
+ // gravity-index.ts
577
+ var DEFAULT_INDEX_URL = "https://index.trygravity.com";
578
+ var DEFAULT_INDEX_TIMEOUT_MS = 3e4;
579
+ var MAX_USER_AGENT_LENGTH = 1024;
580
+ function readEnv(name) {
581
+ return typeof process !== "undefined" ? process.env?.[name] : void 0;
582
+ }
583
+ function stripTrailingSlashes(url) {
584
+ return url.replace(/\/+$/, "");
585
+ }
586
+ function parseRetryAfter(headers) {
587
+ const raw = headers?.get("retry-after");
588
+ if (!raw) return void 0;
589
+ const parsed = Number.parseInt(raw.trim(), 10);
590
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : void 0;
591
+ }
592
+ function extractErrorMessage(rawText, status) {
593
+ const trimmed = rawText.trim();
594
+ if (!trimmed) return `HTTP ${status}`;
595
+ try {
596
+ const parsed = JSON.parse(trimmed);
597
+ if (parsed && typeof parsed === "object") {
598
+ const record = parsed;
599
+ if (typeof record.detail === "string" && record.detail.trim()) {
600
+ return record.detail;
601
+ }
602
+ if (Array.isArray(record.detail) && record.detail.length > 0) {
603
+ const parts = record.detail.map((item) => {
604
+ if (item && typeof item === "object" && "msg" in item) {
605
+ return String(item.msg);
606
+ }
607
+ return typeof item === "string" ? item : JSON.stringify(item);
608
+ }).filter(Boolean);
609
+ if (parts.length > 0) return parts.join("; ");
610
+ }
611
+ if (typeof record.error === "string" && record.error.trim()) {
612
+ return record.error;
613
+ }
614
+ }
615
+ } catch {
616
+ }
617
+ return trimmed;
618
+ }
619
+ function buildSignal(timeoutMs, externalSignal) {
620
+ if (!externalSignal) {
621
+ return { signal: AbortSignal.timeout(timeoutMs), cleanup: () => {
622
+ } };
623
+ }
624
+ if (typeof AbortSignal.any === "function") {
625
+ return {
626
+ signal: AbortSignal.any([AbortSignal.timeout(timeoutMs), externalSignal]),
627
+ cleanup: () => {
628
+ }
629
+ };
630
+ }
631
+ const controller = new AbortController();
632
+ if (externalSignal.aborted) {
633
+ controller.abort(externalSignal.reason);
634
+ return { signal: controller.signal, cleanup: () => {
635
+ } };
636
+ }
637
+ const onExternalAbort = () => controller.abort(externalSignal.reason);
638
+ externalSignal.addEventListener("abort", onExternalAbort, { once: true });
639
+ const timer = setTimeout(() => {
640
+ const timeoutError = new Error(`Timeout (${timeoutMs}ms)`);
641
+ timeoutError.name = "TimeoutError";
642
+ controller.abort(timeoutError);
643
+ }, timeoutMs);
644
+ return {
645
+ signal: controller.signal,
646
+ cleanup: () => {
647
+ clearTimeout(timer);
648
+ externalSignal.removeEventListener("abort", onExternalAbort);
649
+ }
650
+ };
651
+ }
652
+ async function normalizeUserContext(params, options) {
653
+ const body = {};
654
+ for (const [key, value] of Object.entries(params)) {
655
+ if (value === void 0 || key === "email") continue;
656
+ if (key === "country" && !options.allowCountry) continue;
657
+ body[key] = value;
658
+ }
659
+ const explicitIp = typeof params.user_ip === "string" ? params.user_ip.trim() : "";
660
+ const envIp = readEnv("GRAVITY_INDEX_USER_IP")?.trim() || "";
661
+ body.user_ip = explicitIp || envIp || "caller";
662
+ if (typeof params.user_agent === "string") {
663
+ if (params.user_agent.length > 0) {
664
+ body.user_agent = params.user_agent.slice(0, MAX_USER_AGENT_LENGTH);
665
+ } else {
666
+ delete body.user_agent;
667
+ }
668
+ }
669
+ const explicitHashedEmail = typeof params.hashed_email === "string" ? params.hashed_email.trim() : "";
670
+ if (explicitHashedEmail) {
671
+ body.hashed_email = explicitHashedEmail;
672
+ } else {
673
+ delete body.hashed_email;
674
+ const rawEmail = typeof params.email === "string" ? params.email.trim() : "";
675
+ if (rawEmail) {
676
+ const hashed = await hashPii({ email: rawEmail });
677
+ if (hashed.hashed_email) {
678
+ body.hashed_email = hashed.hashed_email;
679
+ }
680
+ }
681
+ }
682
+ return body;
683
+ }
684
+ function isConsumerSearchResponse(response) {
685
+ return Boolean(response && response.vertical === "consumer");
686
+ }
687
+ function isDeveloperSearchResponse(response) {
688
+ return Boolean(response && response.vertical === "developer");
689
+ }
690
+ var GravityIndex = class {
691
+ constructor(opts = {}) {
692
+ this.opts = opts;
693
+ }
694
+ resolveApiKey(overrides) {
695
+ return (overrides?.apiKey || this.opts.apiKey || readEnv("GRAVITY_PUBLISHER_KEY") || readEnv("GRAVITY_API_KEY") || "").trim();
696
+ }
697
+ resolveIndexUrl() {
698
+ return stripTrailingSlashes(
699
+ this.opts.indexUrl || readEnv("GRAVITY_INDEX_URL") || DEFAULT_INDEX_URL
700
+ );
701
+ }
702
+ async post(path, body, overrides) {
703
+ const apiKey = this.resolveApiKey(overrides);
704
+ if (!apiKey) {
705
+ return {
706
+ ok: false,
707
+ data: null,
708
+ status: 0,
709
+ elapsed: "0",
710
+ error: "Missing Gravity API key (set GRAVITY_PUBLISHER_KEY or GRAVITY_API_KEY, or pass apiKey)"
711
+ };
712
+ }
713
+ const timeoutMs = overrides?.timeoutMs ?? this.opts.timeoutMs ?? DEFAULT_INDEX_TIMEOUT_MS;
714
+ const url = `${this.resolveIndexUrl()}${path}`;
715
+ const start = performance.now();
716
+ const { signal, cleanup } = buildSignal(timeoutMs, overrides?.signal);
717
+ try {
718
+ const res = await fetch(url, {
719
+ method: "POST",
720
+ headers: {
721
+ "Content-Type": "application/json",
722
+ "X-API-Key": apiKey
723
+ },
724
+ body: JSON.stringify(body),
725
+ signal
726
+ });
727
+ const elapsed = (performance.now() - start).toFixed(0);
728
+ const retryAfterSeconds = parseRetryAfter(res.headers);
729
+ if (!res.ok) {
730
+ const errText = await res.text().catch(() => "");
731
+ return {
732
+ ok: false,
733
+ data: null,
734
+ status: res.status,
735
+ elapsed,
736
+ error: extractErrorMessage(errText, res.status),
737
+ ...retryAfterSeconds !== void 0 ? { retryAfterSeconds } : {}
738
+ };
739
+ }
740
+ const data = await res.json();
741
+ return {
742
+ ok: true,
743
+ data,
744
+ status: res.status,
745
+ elapsed,
746
+ ...retryAfterSeconds !== void 0 ? { retryAfterSeconds } : {}
747
+ };
748
+ } catch (err2) {
749
+ const elapsed = (performance.now() - start).toFixed(0);
750
+ const reason = signal.aborted ? signal.reason : void 0;
751
+ const isTimeout = err2 instanceof Error && err2.name === "TimeoutError" || reason instanceof Error && reason.name === "TimeoutError";
752
+ const error = isTimeout ? `Timeout (${timeoutMs}ms)` : err2 instanceof Error ? err2.message : String(err2);
753
+ return { ok: false, data: null, status: 0, elapsed, error };
754
+ } finally {
755
+ cleanup();
756
+ }
757
+ }
758
+ /**
759
+ * Search the Gravity Index for the best developer service (or consumer
760
+ * products when `vertical: 'consumer'` or `filters` are provided).
761
+ *
762
+ * `POST /search`
763
+ */
764
+ async search(params, overrides) {
765
+ const body = await normalizeUserContext(
766
+ params,
767
+ { allowCountry: true }
768
+ );
769
+ return this.post("/search", body, overrides);
770
+ }
771
+ /**
772
+ * Search consumer products that a user can buy, with optional structured
773
+ * filters (brand, merchant, price range, sale status, etc.).
774
+ *
775
+ * `POST /shop/search`
776
+ */
777
+ async shopSearch(params, overrides) {
778
+ const body = await normalizeUserContext(
779
+ params,
780
+ { allowCountry: false }
781
+ );
782
+ return this.post("/shop/search", body, overrides);
783
+ }
784
+ };
785
+
540
786
  // gravity.ts
541
787
  var Gravity = class {
542
788
  /**
543
- * @param opts - Configuration applied to every `getAds()` call.
789
+ * @param opts - Configuration applied to every `getAds()` call and `gravity.index`.
544
790
  *
545
791
  * | Option | Type | Default | Description |
546
792
  * |--------|------|---------|-------------|
@@ -551,10 +797,24 @@ var Gravity = class {
551
797
  * | `timeoutMs` | `number` | `4000` | Request timeout in ms |
552
798
  * | `excludedTopics` | `string[]` | — | Topics to exclude from ad matching |
553
799
  * | `gravityApi` | `string` | production URL | Custom API endpoint |
800
+ * | `index` | `GravityIndexOptions` | — | Optional Gravity Index client overrides |
554
801
  */
555
802
  constructor(opts = {}) {
556
803
  this.opts = opts;
557
804
  }
805
+ /**
806
+ * Gravity Index client sharing this instance's API key (plus any `opts.index`
807
+ * overrides).
808
+ */
809
+ get index() {
810
+ if (!this.indexClient) {
811
+ this.indexClient = new GravityIndex({
812
+ apiKey: this.opts.apiKey,
813
+ ...this.opts.index ?? {}
814
+ });
815
+ }
816
+ return this.indexClient;
817
+ }
558
818
  /**
559
819
  * Fetch ads from the Gravity API. **Never throws.**
560
820
  *
@@ -569,8 +829,9 @@ var Gravity = class {
569
829
  * @returns `{ ads, status, elapsed, requestBody, error? }` — always resolves
570
830
  */
571
831
  async getAds(req, messages, placements, overrides = {}) {
832
+ const { index: _index, ...adOpts } = this.opts;
572
833
  return gravityAds(req, messages, placements, {
573
- ...this.opts,
834
+ ...adOpts,
574
835
  ...overrides
575
836
  });
576
837
  }
@@ -1007,42 +1268,6 @@ var Client = class {
1007
1268
  }
1008
1269
  };
1009
1270
 
1010
- // hash.ts
1011
- async function sha256Hex(value) {
1012
- const subtle = typeof globalThis !== "undefined" && globalThis.crypto?.subtle || void 0;
1013
- if (!subtle) return void 0;
1014
- try {
1015
- const bytes = new TextEncoder().encode(value);
1016
- const digest = await subtle.digest("SHA-256", bytes);
1017
- const hex2 = Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
1018
- return hex2;
1019
- } catch {
1020
- return void 0;
1021
- }
1022
- }
1023
- function normalizeEmail(raw) {
1024
- if (typeof raw !== "string") return void 0;
1025
- const trimmed = raw.trim().toLowerCase();
1026
- return trimmed || void 0;
1027
- }
1028
- function normalizePhone(raw) {
1029
- if (typeof raw !== "string") return void 0;
1030
- const digits = raw.replace(/\D+/g, "");
1031
- return digits || void 0;
1032
- }
1033
- async function hashPii(values) {
1034
- const out = {};
1035
- const emailNorm = normalizeEmail(values.email ?? void 0);
1036
- const phoneNorm = normalizePhone(values.phone ?? void 0);
1037
- const [hashedEmail, hashedPhone] = await Promise.all([
1038
- emailNorm ? sha256Hex(emailNorm) : Promise.resolve(void 0),
1039
- phoneNorm ? sha256Hex(phoneNorm) : Promise.resolve(void 0)
1040
- ]);
1041
- if (hashedEmail) out.hashed_email = hashedEmail;
1042
- if (hashedPhone) out.hashed_phone = hashedPhone;
1043
- return out;
1044
- }
1045
-
1046
1271
  // gravity-pixel.ts
1047
1272
  function uuid(prefix) {
1048
1273
  const hex2 = () => Math.random().toString(36).slice(2, 10);
@@ -1497,7 +1722,10 @@ function gravityPixel(opts) {
1497
1722
  }
1498
1723
  export {
1499
1724
  Client,
1725
+ DEFAULT_INDEX_TIMEOUT_MS,
1726
+ DEFAULT_INDEX_URL,
1500
1727
  Gravity,
1728
+ GravityIndex,
1501
1729
  GravityPixel,
1502
1730
  detectCmpConsent,
1503
1731
  extractClientIp,
@@ -1506,6 +1734,8 @@ export {
1506
1734
  gravityContextAsync,
1507
1735
  gravityPixel,
1508
1736
  hashPii,
1737
+ isConsumerSearchResponse,
1738
+ isDeveloperSearchResponse,
1509
1739
  readCmpConsent,
1510
1740
  toGravityMessages
1511
1741
  };
package/dist/opentui.js CHANGED
@@ -29,7 +29,7 @@ var import_child_process = require("child_process");
29
29
  // viewability.ts
30
30
  var MAX_TRACKED_IMPRESSIONS = 1e3;
31
31
  var SDK = "opentui";
32
- var SDK_VERSION = "1.5.0";
32
+ var SDK_VERSION = "1.6.0";
33
33
  var beaconsSent = /* @__PURE__ */ new Set();
34
34
  function sendViewabilityBeacon(impUrl, ev) {
35
35
  const key = `${ev} ${impUrl}`;
package/dist/opentui.mjs CHANGED
@@ -8,7 +8,7 @@ import { execFile } from "child_process";
8
8
  // viewability.ts
9
9
  var MAX_TRACKED_IMPRESSIONS = 1e3;
10
10
  var SDK = "opentui";
11
- var SDK_VERSION = "1.5.0";
11
+ var SDK_VERSION = "1.6.0";
12
12
  var beaconsSent = /* @__PURE__ */ new Set();
13
13
  function sendViewabilityBeacon(impUrl, ev) {
14
14
  const key = `${ev} ${impUrl}`;