@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.js CHANGED
@@ -39,7 +39,7 @@ var require_package = __commonJS({
39
39
  "package.json"(exports2, module2) {
40
40
  module2.exports = {
41
41
  name: "@gravity-ai/api",
42
- version: "1.5.0",
42
+ version: "1.7.0",
43
43
  description: "Gravity JS SDK for retrieving targeted advertisements",
44
44
  main: "dist/index.js",
45
45
  module: "dist/index.mjs",
@@ -117,17 +117,26 @@ var require_package = __commonJS({
117
117
  var index_exports = {};
118
118
  __export(index_exports, {
119
119
  Client: () => Client,
120
+ DEFAULT_INDEX_TIMEOUT_MS: () => DEFAULT_INDEX_TIMEOUT_MS,
121
+ DEFAULT_INDEX_URL: () => DEFAULT_INDEX_URL,
120
122
  Gravity: () => Gravity,
123
+ GravityIndex: () => GravityIndex,
121
124
  GravityPixel: () => GravityPixel,
125
+ appendInlineAd: () => appendInlineAd,
122
126
  detectCmpConsent: () => detectCmpConsent,
123
127
  extractClientIp: () => extractClientIp,
128
+ formatInlineAd: () => formatInlineAd,
124
129
  gravityAds: () => gravityAds,
125
130
  gravityContext: () => gravityContext,
126
131
  gravityContextAsync: () => gravityContextAsync,
127
132
  gravityPixel: () => gravityPixel,
128
133
  hashPii: () => hashPii,
134
+ isConsumerSearchResponse: () => isConsumerSearchResponse,
135
+ isDeveloperSearchResponse: () => isDeveloperSearchResponse,
129
136
  readCmpConsent: () => readCmpConsent,
130
- toGravityMessages: () => toGravityMessages
137
+ splitInlineAd: () => splitInlineAd,
138
+ toGravityMessages: () => toGravityMessages,
139
+ trackInlineImpression: () => trackInlineImpression
131
140
  });
132
141
  module.exports = __toCommonJS(index_exports);
133
142
 
@@ -586,10 +595,256 @@ async function gravityAds(req, messages, placements, opts = {}) {
586
595
  }
587
596
  }
588
597
 
598
+ // hash.ts
599
+ async function sha256Hex(value) {
600
+ const subtle = typeof globalThis !== "undefined" && globalThis.crypto?.subtle || void 0;
601
+ if (!subtle) return void 0;
602
+ try {
603
+ const bytes = new TextEncoder().encode(value);
604
+ const digest = await subtle.digest("SHA-256", bytes);
605
+ const hex2 = Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
606
+ return hex2;
607
+ } catch {
608
+ return void 0;
609
+ }
610
+ }
611
+ function normalizeEmail(raw) {
612
+ if (typeof raw !== "string") return void 0;
613
+ const trimmed = raw.trim().toLowerCase();
614
+ return trimmed || void 0;
615
+ }
616
+ function normalizePhone(raw) {
617
+ if (typeof raw !== "string") return void 0;
618
+ const digits = raw.replace(/\D+/g, "");
619
+ return digits || void 0;
620
+ }
621
+ async function hashPii(values) {
622
+ const out = {};
623
+ const emailNorm = normalizeEmail(values.email ?? void 0);
624
+ const phoneNorm = normalizePhone(values.phone ?? void 0);
625
+ const [hashedEmail, hashedPhone] = await Promise.all([
626
+ emailNorm ? sha256Hex(emailNorm) : Promise.resolve(void 0),
627
+ phoneNorm ? sha256Hex(phoneNorm) : Promise.resolve(void 0)
628
+ ]);
629
+ if (hashedEmail) out.hashed_email = hashedEmail;
630
+ if (hashedPhone) out.hashed_phone = hashedPhone;
631
+ return out;
632
+ }
633
+
634
+ // gravity-index.ts
635
+ var DEFAULT_INDEX_URL = "https://index.trygravity.com";
636
+ var DEFAULT_INDEX_TIMEOUT_MS = 3e4;
637
+ var MAX_USER_AGENT_LENGTH = 1024;
638
+ function readEnv(name) {
639
+ return typeof process !== "undefined" ? process.env?.[name] : void 0;
640
+ }
641
+ function stripTrailingSlashes(url) {
642
+ return url.replace(/\/+$/, "");
643
+ }
644
+ function parseRetryAfter(headers) {
645
+ const raw = headers?.get("retry-after");
646
+ if (!raw) return void 0;
647
+ const parsed = Number.parseInt(raw.trim(), 10);
648
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : void 0;
649
+ }
650
+ function extractErrorMessage(rawText, status) {
651
+ const trimmed = rawText.trim();
652
+ if (!trimmed) return `HTTP ${status}`;
653
+ try {
654
+ const parsed = JSON.parse(trimmed);
655
+ if (parsed && typeof parsed === "object") {
656
+ const record = parsed;
657
+ if (typeof record.detail === "string" && record.detail.trim()) {
658
+ return record.detail;
659
+ }
660
+ if (Array.isArray(record.detail) && record.detail.length > 0) {
661
+ const parts = record.detail.map((item) => {
662
+ if (item && typeof item === "object" && "msg" in item) {
663
+ return String(item.msg);
664
+ }
665
+ return typeof item === "string" ? item : JSON.stringify(item);
666
+ }).filter(Boolean);
667
+ if (parts.length > 0) return parts.join("; ");
668
+ }
669
+ if (typeof record.error === "string" && record.error.trim()) {
670
+ return record.error;
671
+ }
672
+ }
673
+ } catch {
674
+ }
675
+ return trimmed;
676
+ }
677
+ function buildSignal(timeoutMs, externalSignal) {
678
+ if (!externalSignal) {
679
+ return { signal: AbortSignal.timeout(timeoutMs), cleanup: () => {
680
+ } };
681
+ }
682
+ if (typeof AbortSignal.any === "function") {
683
+ return {
684
+ signal: AbortSignal.any([AbortSignal.timeout(timeoutMs), externalSignal]),
685
+ cleanup: () => {
686
+ }
687
+ };
688
+ }
689
+ const controller = new AbortController();
690
+ if (externalSignal.aborted) {
691
+ controller.abort(externalSignal.reason);
692
+ return { signal: controller.signal, cleanup: () => {
693
+ } };
694
+ }
695
+ const onExternalAbort = () => controller.abort(externalSignal.reason);
696
+ externalSignal.addEventListener("abort", onExternalAbort, { once: true });
697
+ const timer = setTimeout(() => {
698
+ const timeoutError = new Error(`Timeout (${timeoutMs}ms)`);
699
+ timeoutError.name = "TimeoutError";
700
+ controller.abort(timeoutError);
701
+ }, timeoutMs);
702
+ return {
703
+ signal: controller.signal,
704
+ cleanup: () => {
705
+ clearTimeout(timer);
706
+ externalSignal.removeEventListener("abort", onExternalAbort);
707
+ }
708
+ };
709
+ }
710
+ async function normalizeUserContext(params, options) {
711
+ const body = {};
712
+ for (const [key, value] of Object.entries(params)) {
713
+ if (value === void 0 || key === "email") continue;
714
+ if (key === "country" && !options.allowCountry) continue;
715
+ body[key] = value;
716
+ }
717
+ const explicitIp = typeof params.user_ip === "string" ? params.user_ip.trim() : "";
718
+ const envIp = readEnv("GRAVITY_INDEX_USER_IP")?.trim() || "";
719
+ body.user_ip = explicitIp || envIp || "caller";
720
+ if (typeof params.user_agent === "string") {
721
+ if (params.user_agent.length > 0) {
722
+ body.user_agent = params.user_agent.slice(0, MAX_USER_AGENT_LENGTH);
723
+ } else {
724
+ delete body.user_agent;
725
+ }
726
+ }
727
+ const explicitHashedEmail = typeof params.hashed_email === "string" ? params.hashed_email.trim() : "";
728
+ if (explicitHashedEmail) {
729
+ body.hashed_email = explicitHashedEmail;
730
+ } else {
731
+ delete body.hashed_email;
732
+ const rawEmail = typeof params.email === "string" ? params.email.trim() : "";
733
+ if (rawEmail) {
734
+ const hashed = await hashPii({ email: rawEmail });
735
+ if (hashed.hashed_email) {
736
+ body.hashed_email = hashed.hashed_email;
737
+ }
738
+ }
739
+ }
740
+ return body;
741
+ }
742
+ function isConsumerSearchResponse(response) {
743
+ return Boolean(response && response.vertical === "consumer");
744
+ }
745
+ function isDeveloperSearchResponse(response) {
746
+ return Boolean(response && response.vertical === "developer");
747
+ }
748
+ var GravityIndex = class {
749
+ constructor(opts = {}) {
750
+ this.opts = opts;
751
+ }
752
+ resolveApiKey(overrides) {
753
+ return (overrides?.apiKey || this.opts.apiKey || readEnv("GRAVITY_PUBLISHER_KEY") || readEnv("GRAVITY_API_KEY") || "").trim();
754
+ }
755
+ resolveIndexUrl() {
756
+ return stripTrailingSlashes(
757
+ this.opts.indexUrl || readEnv("GRAVITY_INDEX_URL") || DEFAULT_INDEX_URL
758
+ );
759
+ }
760
+ async post(path, body, overrides) {
761
+ const apiKey = this.resolveApiKey(overrides);
762
+ if (!apiKey) {
763
+ return {
764
+ ok: false,
765
+ data: null,
766
+ status: 0,
767
+ elapsed: "0",
768
+ error: "Missing Gravity API key (set GRAVITY_PUBLISHER_KEY or GRAVITY_API_KEY, or pass apiKey)"
769
+ };
770
+ }
771
+ const timeoutMs = overrides?.timeoutMs ?? this.opts.timeoutMs ?? DEFAULT_INDEX_TIMEOUT_MS;
772
+ const url = `${this.resolveIndexUrl()}${path}`;
773
+ const start = performance.now();
774
+ const { signal, cleanup } = buildSignal(timeoutMs, overrides?.signal);
775
+ try {
776
+ const res = await fetch(url, {
777
+ method: "POST",
778
+ headers: {
779
+ "Content-Type": "application/json",
780
+ "X-API-Key": apiKey
781
+ },
782
+ body: JSON.stringify(body),
783
+ signal
784
+ });
785
+ const elapsed = (performance.now() - start).toFixed(0);
786
+ const retryAfterSeconds = parseRetryAfter(res.headers);
787
+ if (!res.ok) {
788
+ const errText = await res.text().catch(() => "");
789
+ return {
790
+ ok: false,
791
+ data: null,
792
+ status: res.status,
793
+ elapsed,
794
+ error: extractErrorMessage(errText, res.status),
795
+ ...retryAfterSeconds !== void 0 ? { retryAfterSeconds } : {}
796
+ };
797
+ }
798
+ const data = await res.json();
799
+ return {
800
+ ok: true,
801
+ data,
802
+ status: res.status,
803
+ elapsed,
804
+ ...retryAfterSeconds !== void 0 ? { retryAfterSeconds } : {}
805
+ };
806
+ } catch (err2) {
807
+ const elapsed = (performance.now() - start).toFixed(0);
808
+ const reason = signal.aborted ? signal.reason : void 0;
809
+ const isTimeout = err2 instanceof Error && err2.name === "TimeoutError" || reason instanceof Error && reason.name === "TimeoutError";
810
+ const error = isTimeout ? `Timeout (${timeoutMs}ms)` : err2 instanceof Error ? err2.message : String(err2);
811
+ return { ok: false, data: null, status: 0, elapsed, error };
812
+ } finally {
813
+ cleanup();
814
+ }
815
+ }
816
+ /**
817
+ * Search the Gravity Index for the best developer service (or consumer
818
+ * products when `vertical: 'consumer'` or `filters` are provided).
819
+ *
820
+ * `POST /search`
821
+ */
822
+ async search(params, overrides) {
823
+ const body = await normalizeUserContext(
824
+ params,
825
+ { allowCountry: true }
826
+ );
827
+ return this.post("/search", body, overrides);
828
+ }
829
+ /**
830
+ * Search consumer products that a user can buy, with optional structured
831
+ * filters (brand, merchant, price range, sale status, etc.).
832
+ *
833
+ * `POST /shop/search`
834
+ */
835
+ async shopSearch(params, overrides) {
836
+ const body = await normalizeUserContext(
837
+ params,
838
+ { allowCountry: false }
839
+ );
840
+ return this.post("/shop/search", body, overrides);
841
+ }
842
+ };
843
+
589
844
  // gravity.ts
590
845
  var Gravity = class {
591
846
  /**
592
- * @param opts - Configuration applied to every `getAds()` call.
847
+ * @param opts - Configuration applied to every `getAds()` call and `gravity.index`.
593
848
  *
594
849
  * | Option | Type | Default | Description |
595
850
  * |--------|------|---------|-------------|
@@ -600,10 +855,24 @@ var Gravity = class {
600
855
  * | `timeoutMs` | `number` | `4000` | Request timeout in ms |
601
856
  * | `excludedTopics` | `string[]` | — | Topics to exclude from ad matching |
602
857
  * | `gravityApi` | `string` | production URL | Custom API endpoint |
858
+ * | `index` | `GravityIndexOptions` | — | Optional Gravity Index client overrides |
603
859
  */
604
860
  constructor(opts = {}) {
605
861
  this.opts = opts;
606
862
  }
863
+ /**
864
+ * Gravity Index client sharing this instance's API key (plus any `opts.index`
865
+ * overrides).
866
+ */
867
+ get index() {
868
+ if (!this.indexClient) {
869
+ this.indexClient = new GravityIndex({
870
+ apiKey: this.opts.apiKey,
871
+ ...this.opts.index ?? {}
872
+ });
873
+ }
874
+ return this.indexClient;
875
+ }
607
876
  /**
608
877
  * Fetch ads from the Gravity API. **Never throws.**
609
878
  *
@@ -618,8 +887,9 @@ var Gravity = class {
618
887
  * @returns `{ ads, status, elapsed, requestBody, error? }` — always resolves
619
888
  */
620
889
  async getAds(req, messages, placements, overrides = {}) {
890
+ const { index: _index, ...adOpts } = this.opts;
621
891
  return gravityAds(req, messages, placements, {
622
- ...this.opts,
892
+ ...adOpts,
623
893
  ...overrides
624
894
  });
625
895
  }
@@ -899,6 +1169,150 @@ function nodeDevice() {
899
1169
  };
900
1170
  }
901
1171
 
1172
+ // inline.ts
1173
+ function safeHttpUrl(raw) {
1174
+ if (!raw || typeof raw !== "string") return null;
1175
+ const trimmed = raw.trim();
1176
+ if (!trimmed || /[\s\u0000-\u001f\u007f]/.test(trimmed)) return null;
1177
+ try {
1178
+ const parsed = new URL(trimmed);
1179
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
1180
+ return trimmed;
1181
+ } catch {
1182
+ return null;
1183
+ }
1184
+ }
1185
+ function escapeRegExp(s) {
1186
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1187
+ }
1188
+ function escapeMarkdownText(s) {
1189
+ return s.replace(/([\\[\]])/g, "\\$1");
1190
+ }
1191
+ function escapeMarkdownUrl(url) {
1192
+ return url.replace(/\(/g, "%28").replace(/\)/g, "%29");
1193
+ }
1194
+ function splitInlineAd(ad, options = {}) {
1195
+ if (!ad) return null;
1196
+ const text = (ad.adText ?? "").trim();
1197
+ if (!text) return null;
1198
+ const rawUrl = options.useShortUrl ? ad.shortClickUrl || ad.clickUrl : ad.clickUrl || ad.shortClickUrl;
1199
+ const url = safeHttpUrl(rawUrl);
1200
+ const showLabel = options.showLabel !== false;
1201
+ const label = showLabel ? options.labelText?.trim() || "Sponsored" : null;
1202
+ const brand = (ad.brandName ?? "").trim();
1203
+ if (brand) {
1204
+ const escaped = escapeRegExp(brand);
1205
+ const match = new RegExp(`\\b${escaped}\\b`, "i").exec(text) ?? new RegExp(escaped, "i").exec(text);
1206
+ if (match) {
1207
+ const idx = match.index;
1208
+ const len = match[0].length;
1209
+ return {
1210
+ before: text.slice(0, idx),
1211
+ linkText: text.slice(idx, idx + len),
1212
+ after: text.slice(idx + len),
1213
+ url,
1214
+ label
1215
+ };
1216
+ }
1217
+ return {
1218
+ before: "",
1219
+ linkText: brand,
1220
+ after: `: ${text}`,
1221
+ url,
1222
+ label
1223
+ };
1224
+ }
1225
+ return {
1226
+ before: "",
1227
+ linkText: text,
1228
+ after: "",
1229
+ url,
1230
+ label
1231
+ };
1232
+ }
1233
+ function formatInlineAd(ad, options = {}) {
1234
+ const parts = splitInlineAd(ad, options);
1235
+ if (!parts) return "";
1236
+ const format = options.format ?? "markdown";
1237
+ let body;
1238
+ if (format === "plain") {
1239
+ body = `${parts.before}${parts.linkText}${parts.after}`;
1240
+ if (parts.url) {
1241
+ body = `${body} (${parts.url})`;
1242
+ }
1243
+ } else {
1244
+ const linked = parts.url ? `[${escapeMarkdownText(parts.linkText)}](${escapeMarkdownUrl(parts.url)})` : parts.linkText;
1245
+ body = `${parts.before}${linked}${parts.after}`;
1246
+ }
1247
+ if (!parts.label) return body;
1248
+ return format === "plain" ? `${body} (${parts.label})` : `${body} *(${parts.label})*`;
1249
+ }
1250
+ async function trackInlineImpression(ad, fetchFn) {
1251
+ const impUrl = safeHttpUrl(ad?.impUrl);
1252
+ if (!impUrl) return false;
1253
+ const fn = fetchFn ?? globalThis.fetch;
1254
+ if (typeof fn !== "function") return false;
1255
+ try {
1256
+ await fn(impUrl, { method: "GET" });
1257
+ return true;
1258
+ } catch {
1259
+ return false;
1260
+ }
1261
+ }
1262
+ function pickAd(source, placementId) {
1263
+ if (!source) return null;
1264
+ if ("ads" in source && Array.isArray(source.ads)) {
1265
+ if (placementId) {
1266
+ return source.ads.find((a) => a.placement_id === placementId) ?? null;
1267
+ }
1268
+ return source.ads[0] ?? null;
1269
+ }
1270
+ return source;
1271
+ }
1272
+ async function resolveWithTimeout(value, timeoutMs) {
1273
+ let timer;
1274
+ try {
1275
+ if (timeoutMs <= 0) {
1276
+ return await Promise.race([
1277
+ Promise.resolve(value),
1278
+ Promise.resolve(null)
1279
+ ]);
1280
+ }
1281
+ return await Promise.race([
1282
+ Promise.resolve(value),
1283
+ new Promise((resolve) => {
1284
+ timer = setTimeout(() => resolve(null), timeoutMs);
1285
+ })
1286
+ ]);
1287
+ } catch {
1288
+ return null;
1289
+ } finally {
1290
+ if (timer !== void 0) clearTimeout(timer);
1291
+ }
1292
+ }
1293
+ async function* appendInlineAd(stream, adOrPromise, options = {}) {
1294
+ const safeAdPromise = Promise.resolve(adOrPromise).catch(
1295
+ () => null
1296
+ );
1297
+ let hasContent = false;
1298
+ for await (const chunk of stream) {
1299
+ if (chunk) hasContent = true;
1300
+ yield chunk;
1301
+ }
1302
+ const resolved = await resolveWithTimeout(
1303
+ safeAdPromise,
1304
+ options.adTimeoutMs ?? 500
1305
+ );
1306
+ const ad = pickAd(resolved, options.placementId);
1307
+ const formatted = formatInlineAd(ad, options);
1308
+ if (!formatted) return;
1309
+ const separator = hasContent ? options.separator ?? "\n\n" : "";
1310
+ yield `${separator}${formatted}`;
1311
+ if (options.trackImpression !== false) {
1312
+ void trackInlineImpression(ad, options.fetchFn);
1313
+ }
1314
+ }
1315
+
902
1316
  // client.ts
903
1317
  var import_axios = __toESM(require("axios"));
904
1318
  var DEFAULT_ENDPOINT = "https://server.trygravity.ai";
@@ -1056,42 +1470,6 @@ var Client = class {
1056
1470
  }
1057
1471
  };
1058
1472
 
1059
- // hash.ts
1060
- async function sha256Hex(value) {
1061
- const subtle = typeof globalThis !== "undefined" && globalThis.crypto?.subtle || void 0;
1062
- if (!subtle) return void 0;
1063
- try {
1064
- const bytes = new TextEncoder().encode(value);
1065
- const digest = await subtle.digest("SHA-256", bytes);
1066
- const hex2 = Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
1067
- return hex2;
1068
- } catch {
1069
- return void 0;
1070
- }
1071
- }
1072
- function normalizeEmail(raw) {
1073
- if (typeof raw !== "string") return void 0;
1074
- const trimmed = raw.trim().toLowerCase();
1075
- return trimmed || void 0;
1076
- }
1077
- function normalizePhone(raw) {
1078
- if (typeof raw !== "string") return void 0;
1079
- const digits = raw.replace(/\D+/g, "");
1080
- return digits || void 0;
1081
- }
1082
- async function hashPii(values) {
1083
- const out = {};
1084
- const emailNorm = normalizeEmail(values.email ?? void 0);
1085
- const phoneNorm = normalizePhone(values.phone ?? void 0);
1086
- const [hashedEmail, hashedPhone] = await Promise.all([
1087
- emailNorm ? sha256Hex(emailNorm) : Promise.resolve(void 0),
1088
- phoneNorm ? sha256Hex(phoneNorm) : Promise.resolve(void 0)
1089
- ]);
1090
- if (hashedEmail) out.hashed_email = hashedEmail;
1091
- if (hashedPhone) out.hashed_phone = hashedPhone;
1092
- return out;
1093
- }
1094
-
1095
1473
  // gravity-pixel.ts
1096
1474
  function uuid(prefix) {
1097
1475
  const hex2 = () => Math.random().toString(36).slice(2, 10);
@@ -1547,15 +1925,24 @@ function gravityPixel(opts) {
1547
1925
  // Annotate the CommonJS export names for ESM import in node:
1548
1926
  0 && (module.exports = {
1549
1927
  Client,
1928
+ DEFAULT_INDEX_TIMEOUT_MS,
1929
+ DEFAULT_INDEX_URL,
1550
1930
  Gravity,
1931
+ GravityIndex,
1551
1932
  GravityPixel,
1933
+ appendInlineAd,
1552
1934
  detectCmpConsent,
1553
1935
  extractClientIp,
1936
+ formatInlineAd,
1554
1937
  gravityAds,
1555
1938
  gravityContext,
1556
1939
  gravityContextAsync,
1557
1940
  gravityPixel,
1558
1941
  hashPii,
1942
+ isConsumerSearchResponse,
1943
+ isDeveloperSearchResponse,
1559
1944
  readCmpConsent,
1560
- toGravityMessages
1945
+ splitInlineAd,
1946
+ toGravityMessages,
1947
+ trackInlineImpression
1561
1948
  });