@gravity-ai/api 1.5.0 → 1.7.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.7.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
  }
@@ -850,6 +1111,150 @@ function nodeDevice() {
850
1111
  };
851
1112
  }
852
1113
 
1114
+ // inline.ts
1115
+ function safeHttpUrl(raw) {
1116
+ if (!raw || typeof raw !== "string") return null;
1117
+ const trimmed = raw.trim();
1118
+ if (!trimmed || /[\s\u0000-\u001f\u007f]/.test(trimmed)) return null;
1119
+ try {
1120
+ const parsed = new URL(trimmed);
1121
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
1122
+ return trimmed;
1123
+ } catch {
1124
+ return null;
1125
+ }
1126
+ }
1127
+ function escapeRegExp(s) {
1128
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1129
+ }
1130
+ function escapeMarkdownText(s) {
1131
+ return s.replace(/([\\[\]])/g, "\\$1");
1132
+ }
1133
+ function escapeMarkdownUrl(url) {
1134
+ return url.replace(/\(/g, "%28").replace(/\)/g, "%29");
1135
+ }
1136
+ function splitInlineAd(ad, options = {}) {
1137
+ if (!ad) return null;
1138
+ const text = (ad.adText ?? "").trim();
1139
+ if (!text) return null;
1140
+ const rawUrl = options.useShortUrl ? ad.shortClickUrl || ad.clickUrl : ad.clickUrl || ad.shortClickUrl;
1141
+ const url = safeHttpUrl(rawUrl);
1142
+ const showLabel = options.showLabel !== false;
1143
+ const label = showLabel ? options.labelText?.trim() || "Sponsored" : null;
1144
+ const brand = (ad.brandName ?? "").trim();
1145
+ if (brand) {
1146
+ const escaped = escapeRegExp(brand);
1147
+ const match = new RegExp(`\\b${escaped}\\b`, "i").exec(text) ?? new RegExp(escaped, "i").exec(text);
1148
+ if (match) {
1149
+ const idx = match.index;
1150
+ const len = match[0].length;
1151
+ return {
1152
+ before: text.slice(0, idx),
1153
+ linkText: text.slice(idx, idx + len),
1154
+ after: text.slice(idx + len),
1155
+ url,
1156
+ label
1157
+ };
1158
+ }
1159
+ return {
1160
+ before: "",
1161
+ linkText: brand,
1162
+ after: `: ${text}`,
1163
+ url,
1164
+ label
1165
+ };
1166
+ }
1167
+ return {
1168
+ before: "",
1169
+ linkText: text,
1170
+ after: "",
1171
+ url,
1172
+ label
1173
+ };
1174
+ }
1175
+ function formatInlineAd(ad, options = {}) {
1176
+ const parts = splitInlineAd(ad, options);
1177
+ if (!parts) return "";
1178
+ const format = options.format ?? "markdown";
1179
+ let body;
1180
+ if (format === "plain") {
1181
+ body = `${parts.before}${parts.linkText}${parts.after}`;
1182
+ if (parts.url) {
1183
+ body = `${body} (${parts.url})`;
1184
+ }
1185
+ } else {
1186
+ const linked = parts.url ? `[${escapeMarkdownText(parts.linkText)}](${escapeMarkdownUrl(parts.url)})` : parts.linkText;
1187
+ body = `${parts.before}${linked}${parts.after}`;
1188
+ }
1189
+ if (!parts.label) return body;
1190
+ return format === "plain" ? `${body} (${parts.label})` : `${body} *(${parts.label})*`;
1191
+ }
1192
+ async function trackInlineImpression(ad, fetchFn) {
1193
+ const impUrl = safeHttpUrl(ad?.impUrl);
1194
+ if (!impUrl) return false;
1195
+ const fn = fetchFn ?? globalThis.fetch;
1196
+ if (typeof fn !== "function") return false;
1197
+ try {
1198
+ await fn(impUrl, { method: "GET" });
1199
+ return true;
1200
+ } catch {
1201
+ return false;
1202
+ }
1203
+ }
1204
+ function pickAd(source, placementId) {
1205
+ if (!source) return null;
1206
+ if ("ads" in source && Array.isArray(source.ads)) {
1207
+ if (placementId) {
1208
+ return source.ads.find((a) => a.placement_id === placementId) ?? null;
1209
+ }
1210
+ return source.ads[0] ?? null;
1211
+ }
1212
+ return source;
1213
+ }
1214
+ async function resolveWithTimeout(value, timeoutMs) {
1215
+ let timer;
1216
+ try {
1217
+ if (timeoutMs <= 0) {
1218
+ return await Promise.race([
1219
+ Promise.resolve(value),
1220
+ Promise.resolve(null)
1221
+ ]);
1222
+ }
1223
+ return await Promise.race([
1224
+ Promise.resolve(value),
1225
+ new Promise((resolve) => {
1226
+ timer = setTimeout(() => resolve(null), timeoutMs);
1227
+ })
1228
+ ]);
1229
+ } catch {
1230
+ return null;
1231
+ } finally {
1232
+ if (timer !== void 0) clearTimeout(timer);
1233
+ }
1234
+ }
1235
+ async function* appendInlineAd(stream, adOrPromise, options = {}) {
1236
+ const safeAdPromise = Promise.resolve(adOrPromise).catch(
1237
+ () => null
1238
+ );
1239
+ let hasContent = false;
1240
+ for await (const chunk of stream) {
1241
+ if (chunk) hasContent = true;
1242
+ yield chunk;
1243
+ }
1244
+ const resolved = await resolveWithTimeout(
1245
+ safeAdPromise,
1246
+ options.adTimeoutMs ?? 500
1247
+ );
1248
+ const ad = pickAd(resolved, options.placementId);
1249
+ const formatted = formatInlineAd(ad, options);
1250
+ if (!formatted) return;
1251
+ const separator = hasContent ? options.separator ?? "\n\n" : "";
1252
+ yield `${separator}${formatted}`;
1253
+ if (options.trackImpression !== false) {
1254
+ void trackInlineImpression(ad, options.fetchFn);
1255
+ }
1256
+ }
1257
+
853
1258
  // client.ts
854
1259
  import axios from "axios";
855
1260
  var DEFAULT_ENDPOINT = "https://server.trygravity.ai";
@@ -1007,42 +1412,6 @@ var Client = class {
1007
1412
  }
1008
1413
  };
1009
1414
 
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
1415
  // gravity-pixel.ts
1047
1416
  function uuid(prefix) {
1048
1417
  const hex2 = () => Math.random().toString(36).slice(2, 10);
@@ -1497,15 +1866,24 @@ function gravityPixel(opts) {
1497
1866
  }
1498
1867
  export {
1499
1868
  Client,
1869
+ DEFAULT_INDEX_TIMEOUT_MS,
1870
+ DEFAULT_INDEX_URL,
1500
1871
  Gravity,
1872
+ GravityIndex,
1501
1873
  GravityPixel,
1874
+ appendInlineAd,
1502
1875
  detectCmpConsent,
1503
1876
  extractClientIp,
1877
+ formatInlineAd,
1504
1878
  gravityAds,
1505
1879
  gravityContext,
1506
1880
  gravityContextAsync,
1507
1881
  gravityPixel,
1508
1882
  hashPii,
1883
+ isConsumerSearchResponse,
1884
+ isDeveloperSearchResponse,
1509
1885
  readCmpConsent,
1510
- toGravityMessages
1886
+ splitInlineAd,
1887
+ toGravityMessages,
1888
+ trackInlineImpression
1511
1889
  };
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.7.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.7.0";
12
12
  var beaconsSent = /* @__PURE__ */ new Set();
13
13
  function sendViewabilityBeacon(impUrl, ev) {
14
14
  const key = `${ev} ${impUrl}`;