@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/README.md CHANGED
@@ -302,6 +302,51 @@ if (ad) {
302
302
 
303
303
  ---
304
304
 
305
+ ## Gravity Index
306
+
307
+ Use `gravity.index` on an existing `Gravity` instance, or instantiate `GravityIndex` standalone to search developer services (`POST /search`) and consumer products (`POST /shop/search`).
308
+
309
+ ```ts
310
+ import { Gravity, GravityIndex, isDeveloperSearchResponse } from '@gravity-ai/api';
311
+
312
+ // Via existing Gravity client (shares apiKey):
313
+ const gravity = new Gravity({ production: true });
314
+ const res = await gravity.index.search({
315
+ query: 'serverless Postgres database with a free tier',
316
+ user_ip: '203.0.113.7', // real end-user IP for hosted servers (fallback: GRAVITY_INDEX_USER_IP || 'caller')
317
+ session_id: 'chat_8f3a',
318
+ email: 'alice@example.com', // SHA-256 hashed locally into hashed_email; never sent raw
319
+ user_agent: req.headers['user-agent'], // automatically capped at 1024 chars
320
+ country: 'US',
321
+ external_user_id_hash: 'sha256_user_id',
322
+ });
323
+
324
+ if (res.ok && isDeveloperSearchResponse(res.data)) {
325
+ console.log(res.data.recommendation?.name, res.data.click_url);
326
+ }
327
+
328
+ // Or standalone (reads GRAVITY_PUBLISHER_KEY || GRAVITY_API_KEY):
329
+ const index = new GravityIndex();
330
+ const products = await index.shopSearch({
331
+ query: 'running shoes for wide feet',
332
+ user_ip: '203.0.113.7',
333
+ session_id: 'chat_8f3a',
334
+ price_max: 150,
335
+ max_results: 3,
336
+ });
337
+ ```
338
+
339
+ Every method resolves to `IndexResult<T>` (`{ ok, data, status, elapsed, error?, retryAfterSeconds? }`) and never throws.
340
+
341
+ | Method | Endpoint | Purpose |
342
+ |--------|----------|---------|
343
+ | `search(params)` | `POST /search` | Recommend a developer service (or consumer products with `vertical: 'consumer'` / `filters`) |
344
+ | `shopSearch(params)` | `POST /shop/search` | Search consumer products with structured filters and facets |
345
+
346
+ **End-user context (CPM payouts & geo targeting):** Hosted servers should pass the end user's real `user_ip` (falls back to `GRAVITY_INDEX_USER_IP`, else `'caller'`), `session_id`, `user_agent` (capped at 1,024 chars), `hashed_email` (or raw `email`, which is trimmed, lowercased, and SHA-256 hashed locally and never transmitted raw), `external_user_id_hash`, and `country` (ISO 3166-1 alpha-2 on `search`).
347
+
348
+ ---
349
+
305
350
  ## License
306
351
 
307
352
  MIT
package/dist/index.d.mts CHANGED
@@ -1,5 +1,55 @@
1
- import { G as GravityAdsOptions, I as IncomingAdRequest, M as MessageObject, P as PlacementObject, a as GravityAdsResult, b as GravityContextOverrides, c as GravityContext, A as AdParams, d as Ad } from './types-FOlyOpps.mjs';
2
- export { e as AdAction, f as AdLayout, g as AdUnit, h as ApiErrorResponse, D as DeviceObject, F as FrameSize, i as Gender, H as HostTheme, L as LeadFormConfig, j as LeadFormField, k as LeadFormPrefill, l as McpConnect, m as McpConnectHandler, n as McpConnectRequest, o as McpConnectResult, p as ModelUsage, q as Placement, r as PromptAction, R as RenderEnvelope, s as Role, S as SlotSize, T as TextMetrics, U as UnitCapability, t as UnknownAdAction, u as UserObject } from './types-FOlyOpps.mjs';
1
+ import { G as GravityIndexOptions, I as IndexSearchParams, a as IndexRequestOptions, b as IndexResult, c as IndexSearchResponse, d as IndexShopSearchParams, e as IndexShopSearchResponse, f as IndexDeveloperSearchResponse, g as GravityOptions, h as IncomingAdRequest, M as MessageObject, P as PlacementObject, i as GravityAdsOptions, j as GravityAdsResult, k as GravityContextOverrides, l as GravityContext, A as AdParams, m as Ad } from './types-DlHD2n-z.mjs';
2
+ export { n as AdAction, o as AdLayout, p as AdUnit, q as ApiErrorResponse, D as DeviceObject, F as FrameSize, r as Gender, H as HostTheme, s as IndexAlternative, t as IndexContextMessage, u as IndexCredentialRequest, v as IndexGender, w as IndexInstallInstructions, x as IndexInstallStep, y as IndexMcpConnect, z as IndexMonetization, B as IndexMppCheckout, C as IndexPriceRange, E as IndexProduct, J as IndexRecommendation, K as IndexSearchContext, L as IndexSearchOption, N as IndexShopFacets, O as IndexShopFilters, Q as IndexUcpCheckout, R as IndexVertical, S as IndexWebResult, T as LeadFormConfig, U as LeadFormField, V as LeadFormPrefill, W as McpConnect, X as McpConnectHandler, Y as McpConnectRequest, Z as McpConnectResult, _ as ModelUsage, $ as Placement, a0 as PromptAction, a1 as RenderEnvelope, a2 as Role, a3 as SlotSize, a4 as TextMetrics, a5 as UnitCapability, a6 as UnknownAdAction, a7 as UserObject } from './types-DlHD2n-z.mjs';
3
+
4
+ declare const DEFAULT_INDEX_URL = "https://index.trygravity.com";
5
+ declare const DEFAULT_INDEX_TIMEOUT_MS = 30000;
6
+ /** Type guard: checks whether a `search()` payload is a consumer product response. */
7
+ declare function isConsumerSearchResponse(response: IndexSearchResponse | null | undefined): response is IndexShopSearchResponse;
8
+ /** Type guard: checks whether a `search()` payload is a developer service response. */
9
+ declare function isDeveloperSearchResponse(response: IndexSearchResponse | null | undefined): response is IndexDeveloperSearchResponse;
10
+ /**
11
+ * Client for the Gravity Index search APIs (`POST /search` and `POST /shop/search`).
12
+ *
13
+ * Every method resolves to `IndexResult<T>` and **never throws**.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * import { GravityIndex, isDeveloperSearchResponse } from '@gravity-ai/api';
18
+ *
19
+ * const index = new GravityIndex(); // reads GRAVITY_PUBLISHER_KEY or GRAVITY_API_KEY
20
+ *
21
+ * const res = await index.search({
22
+ * query: 'serverless Postgres database with a free tier',
23
+ * user_ip: '203.0.113.7',
24
+ * session_id: 'chat_8f3a',
25
+ * email: 'alice@example.com', // SHA-256 hashed locally; never sent raw
26
+ * });
27
+ * if (res.ok && isDeveloperSearchResponse(res.data)) {
28
+ * console.log(res.data.recommendation?.name, res.data.click_url);
29
+ * }
30
+ * ```
31
+ */
32
+ declare class GravityIndex {
33
+ private readonly opts;
34
+ constructor(opts?: GravityIndexOptions);
35
+ private resolveApiKey;
36
+ private resolveIndexUrl;
37
+ private post;
38
+ /**
39
+ * Search the Gravity Index for the best developer service (or consumer
40
+ * products when `vertical: 'consumer'` or `filters` are provided).
41
+ *
42
+ * `POST /search`
43
+ */
44
+ search(params: IndexSearchParams, overrides?: IndexRequestOptions): Promise<IndexResult<IndexSearchResponse>>;
45
+ /**
46
+ * Search consumer products that a user can buy, with optional structured
47
+ * filters (brand, merchant, price range, sale status, etc.).
48
+ *
49
+ * `POST /shop/search`
50
+ */
51
+ shopSearch(params: IndexShopSearchParams, overrides?: IndexRequestOptions): Promise<IndexResult<IndexShopSearchResponse>>;
52
+ }
3
53
 
4
54
  /**
5
55
  * Gravity ad client.
@@ -30,8 +80,9 @@ export { e as AdAction, f as AdLayout, g as AdUnit, h as ApiErrorResponse, D as
30
80
  */
31
81
  declare class Gravity {
32
82
  private opts;
83
+ private indexClient?;
33
84
  /**
34
- * @param opts - Configuration applied to every `getAds()` call.
85
+ * @param opts - Configuration applied to every `getAds()` call and `gravity.index`.
35
86
  *
36
87
  * | Option | Type | Default | Description |
37
88
  * |--------|------|---------|-------------|
@@ -42,8 +93,14 @@ declare class Gravity {
42
93
  * | `timeoutMs` | `number` | `4000` | Request timeout in ms |
43
94
  * | `excludedTopics` | `string[]` | — | Topics to exclude from ad matching |
44
95
  * | `gravityApi` | `string` | production URL | Custom API endpoint |
96
+ * | `index` | `GravityIndexOptions` | — | Optional Gravity Index client overrides |
97
+ */
98
+ constructor(opts?: GravityOptions);
99
+ /**
100
+ * Gravity Index client sharing this instance's API key (plus any `opts.index`
101
+ * overrides).
45
102
  */
46
- constructor(opts?: GravityAdsOptions);
103
+ get index(): GravityIndex;
47
104
  /**
48
105
  * Fetch ads from the Gravity API. **Never throws.**
49
106
  *
@@ -516,5 +573,5 @@ declare class GravityPixel {
516
573
  */
517
574
  declare function gravityPixel(opts: GravityPixelConfig): GravityPixel;
518
575
 
519
- export { Ad, AdParams, Client, Gravity, GravityAdsOptions, GravityAdsResult, GravityContext, GravityContextOverrides, GravityPixel, IncomingAdRequest, MessageObject, PlacementObject, detectCmpConsent, extractClientIp, gravityAds, gravityContext, gravityContextAsync, gravityPixel, hashPii, readCmpConsent, toGravityMessages };
576
+ export { Ad, AdParams, Client, DEFAULT_INDEX_TIMEOUT_MS, DEFAULT_INDEX_URL, Gravity, GravityAdsOptions, GravityAdsResult, GravityContext, GravityContextOverrides, GravityIndex, GravityIndexOptions, GravityOptions, GravityPixel, IncomingAdRequest, IndexDeveloperSearchResponse, IndexRequestOptions, IndexResult, IndexSearchParams, IndexSearchResponse, IndexShopSearchParams, IndexShopSearchResponse, MessageObject, PlacementObject, detectCmpConsent, extractClientIp, gravityAds, gravityContext, gravityContextAsync, gravityPixel, hashPii, isConsumerSearchResponse, isDeveloperSearchResponse, readCmpConsent, toGravityMessages };
520
577
  export type { ClientParams, ConsentSignal, GravityPixelConfig, HashedIdentity, RawIdentity };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,55 @@
1
- import { G as GravityAdsOptions, I as IncomingAdRequest, M as MessageObject, P as PlacementObject, a as GravityAdsResult, b as GravityContextOverrides, c as GravityContext, A as AdParams, d as Ad } from './types-FOlyOpps.js';
2
- export { e as AdAction, f as AdLayout, g as AdUnit, h as ApiErrorResponse, D as DeviceObject, F as FrameSize, i as Gender, H as HostTheme, L as LeadFormConfig, j as LeadFormField, k as LeadFormPrefill, l as McpConnect, m as McpConnectHandler, n as McpConnectRequest, o as McpConnectResult, p as ModelUsage, q as Placement, r as PromptAction, R as RenderEnvelope, s as Role, S as SlotSize, T as TextMetrics, U as UnitCapability, t as UnknownAdAction, u as UserObject } from './types-FOlyOpps.js';
1
+ import { G as GravityIndexOptions, I as IndexSearchParams, a as IndexRequestOptions, b as IndexResult, c as IndexSearchResponse, d as IndexShopSearchParams, e as IndexShopSearchResponse, f as IndexDeveloperSearchResponse, g as GravityOptions, h as IncomingAdRequest, M as MessageObject, P as PlacementObject, i as GravityAdsOptions, j as GravityAdsResult, k as GravityContextOverrides, l as GravityContext, A as AdParams, m as Ad } from './types-DlHD2n-z.js';
2
+ export { n as AdAction, o as AdLayout, p as AdUnit, q as ApiErrorResponse, D as DeviceObject, F as FrameSize, r as Gender, H as HostTheme, s as IndexAlternative, t as IndexContextMessage, u as IndexCredentialRequest, v as IndexGender, w as IndexInstallInstructions, x as IndexInstallStep, y as IndexMcpConnect, z as IndexMonetization, B as IndexMppCheckout, C as IndexPriceRange, E as IndexProduct, J as IndexRecommendation, K as IndexSearchContext, L as IndexSearchOption, N as IndexShopFacets, O as IndexShopFilters, Q as IndexUcpCheckout, R as IndexVertical, S as IndexWebResult, T as LeadFormConfig, U as LeadFormField, V as LeadFormPrefill, W as McpConnect, X as McpConnectHandler, Y as McpConnectRequest, Z as McpConnectResult, _ as ModelUsage, $ as Placement, a0 as PromptAction, a1 as RenderEnvelope, a2 as Role, a3 as SlotSize, a4 as TextMetrics, a5 as UnitCapability, a6 as UnknownAdAction, a7 as UserObject } from './types-DlHD2n-z.js';
3
+
4
+ declare const DEFAULT_INDEX_URL = "https://index.trygravity.com";
5
+ declare const DEFAULT_INDEX_TIMEOUT_MS = 30000;
6
+ /** Type guard: checks whether a `search()` payload is a consumer product response. */
7
+ declare function isConsumerSearchResponse(response: IndexSearchResponse | null | undefined): response is IndexShopSearchResponse;
8
+ /** Type guard: checks whether a `search()` payload is a developer service response. */
9
+ declare function isDeveloperSearchResponse(response: IndexSearchResponse | null | undefined): response is IndexDeveloperSearchResponse;
10
+ /**
11
+ * Client for the Gravity Index search APIs (`POST /search` and `POST /shop/search`).
12
+ *
13
+ * Every method resolves to `IndexResult<T>` and **never throws**.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * import { GravityIndex, isDeveloperSearchResponse } from '@gravity-ai/api';
18
+ *
19
+ * const index = new GravityIndex(); // reads GRAVITY_PUBLISHER_KEY or GRAVITY_API_KEY
20
+ *
21
+ * const res = await index.search({
22
+ * query: 'serverless Postgres database with a free tier',
23
+ * user_ip: '203.0.113.7',
24
+ * session_id: 'chat_8f3a',
25
+ * email: 'alice@example.com', // SHA-256 hashed locally; never sent raw
26
+ * });
27
+ * if (res.ok && isDeveloperSearchResponse(res.data)) {
28
+ * console.log(res.data.recommendation?.name, res.data.click_url);
29
+ * }
30
+ * ```
31
+ */
32
+ declare class GravityIndex {
33
+ private readonly opts;
34
+ constructor(opts?: GravityIndexOptions);
35
+ private resolveApiKey;
36
+ private resolveIndexUrl;
37
+ private post;
38
+ /**
39
+ * Search the Gravity Index for the best developer service (or consumer
40
+ * products when `vertical: 'consumer'` or `filters` are provided).
41
+ *
42
+ * `POST /search`
43
+ */
44
+ search(params: IndexSearchParams, overrides?: IndexRequestOptions): Promise<IndexResult<IndexSearchResponse>>;
45
+ /**
46
+ * Search consumer products that a user can buy, with optional structured
47
+ * filters (brand, merchant, price range, sale status, etc.).
48
+ *
49
+ * `POST /shop/search`
50
+ */
51
+ shopSearch(params: IndexShopSearchParams, overrides?: IndexRequestOptions): Promise<IndexResult<IndexShopSearchResponse>>;
52
+ }
3
53
 
4
54
  /**
5
55
  * Gravity ad client.
@@ -30,8 +80,9 @@ export { e as AdAction, f as AdLayout, g as AdUnit, h as ApiErrorResponse, D as
30
80
  */
31
81
  declare class Gravity {
32
82
  private opts;
83
+ private indexClient?;
33
84
  /**
34
- * @param opts - Configuration applied to every `getAds()` call.
85
+ * @param opts - Configuration applied to every `getAds()` call and `gravity.index`.
35
86
  *
36
87
  * | Option | Type | Default | Description |
37
88
  * |--------|------|---------|-------------|
@@ -42,8 +93,14 @@ declare class Gravity {
42
93
  * | `timeoutMs` | `number` | `4000` | Request timeout in ms |
43
94
  * | `excludedTopics` | `string[]` | — | Topics to exclude from ad matching |
44
95
  * | `gravityApi` | `string` | production URL | Custom API endpoint |
96
+ * | `index` | `GravityIndexOptions` | — | Optional Gravity Index client overrides |
97
+ */
98
+ constructor(opts?: GravityOptions);
99
+ /**
100
+ * Gravity Index client sharing this instance's API key (plus any `opts.index`
101
+ * overrides).
45
102
  */
46
- constructor(opts?: GravityAdsOptions);
103
+ get index(): GravityIndex;
47
104
  /**
48
105
  * Fetch ads from the Gravity API. **Never throws.**
49
106
  *
@@ -516,5 +573,5 @@ declare class GravityPixel {
516
573
  */
517
574
  declare function gravityPixel(opts: GravityPixelConfig): GravityPixel;
518
575
 
519
- export { Ad, AdParams, Client, Gravity, GravityAdsOptions, GravityAdsResult, GravityContext, GravityContextOverrides, GravityPixel, IncomingAdRequest, MessageObject, PlacementObject, detectCmpConsent, extractClientIp, gravityAds, gravityContext, gravityContextAsync, gravityPixel, hashPii, readCmpConsent, toGravityMessages };
576
+ export { Ad, AdParams, Client, DEFAULT_INDEX_TIMEOUT_MS, DEFAULT_INDEX_URL, Gravity, GravityAdsOptions, GravityAdsResult, GravityContext, GravityContextOverrides, GravityIndex, GravityIndexOptions, GravityOptions, GravityPixel, IncomingAdRequest, IndexDeveloperSearchResponse, IndexRequestOptions, IndexResult, IndexSearchParams, IndexSearchResponse, IndexShopSearchParams, IndexShopSearchResponse, MessageObject, PlacementObject, detectCmpConsent, extractClientIp, gravityAds, gravityContext, gravityContextAsync, gravityPixel, hashPii, isConsumerSearchResponse, isDeveloperSearchResponse, readCmpConsent, toGravityMessages };
520
577
  export type { ClientParams, ConsentSignal, GravityPixelConfig, HashedIdentity, RawIdentity };
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.6.0",
43
43
  description: "Gravity JS SDK for retrieving targeted advertisements",
44
44
  main: "dist/index.js",
45
45
  module: "dist/index.mjs",
@@ -117,7 +117,10 @@ 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,
122
125
  detectCmpConsent: () => detectCmpConsent,
123
126
  extractClientIp: () => extractClientIp,
@@ -126,6 +129,8 @@ __export(index_exports, {
126
129
  gravityContextAsync: () => gravityContextAsync,
127
130
  gravityPixel: () => gravityPixel,
128
131
  hashPii: () => hashPii,
132
+ isConsumerSearchResponse: () => isConsumerSearchResponse,
133
+ isDeveloperSearchResponse: () => isDeveloperSearchResponse,
129
134
  readCmpConsent: () => readCmpConsent,
130
135
  toGravityMessages: () => toGravityMessages
131
136
  });
@@ -586,10 +591,256 @@ async function gravityAds(req, messages, placements, opts = {}) {
586
591
  }
587
592
  }
588
593
 
594
+ // hash.ts
595
+ async function sha256Hex(value) {
596
+ const subtle = typeof globalThis !== "undefined" && globalThis.crypto?.subtle || void 0;
597
+ if (!subtle) return void 0;
598
+ try {
599
+ const bytes = new TextEncoder().encode(value);
600
+ const digest = await subtle.digest("SHA-256", bytes);
601
+ const hex2 = Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
602
+ return hex2;
603
+ } catch {
604
+ return void 0;
605
+ }
606
+ }
607
+ function normalizeEmail(raw) {
608
+ if (typeof raw !== "string") return void 0;
609
+ const trimmed = raw.trim().toLowerCase();
610
+ return trimmed || void 0;
611
+ }
612
+ function normalizePhone(raw) {
613
+ if (typeof raw !== "string") return void 0;
614
+ const digits = raw.replace(/\D+/g, "");
615
+ return digits || void 0;
616
+ }
617
+ async function hashPii(values) {
618
+ const out = {};
619
+ const emailNorm = normalizeEmail(values.email ?? void 0);
620
+ const phoneNorm = normalizePhone(values.phone ?? void 0);
621
+ const [hashedEmail, hashedPhone] = await Promise.all([
622
+ emailNorm ? sha256Hex(emailNorm) : Promise.resolve(void 0),
623
+ phoneNorm ? sha256Hex(phoneNorm) : Promise.resolve(void 0)
624
+ ]);
625
+ if (hashedEmail) out.hashed_email = hashedEmail;
626
+ if (hashedPhone) out.hashed_phone = hashedPhone;
627
+ return out;
628
+ }
629
+
630
+ // gravity-index.ts
631
+ var DEFAULT_INDEX_URL = "https://index.trygravity.com";
632
+ var DEFAULT_INDEX_TIMEOUT_MS = 3e4;
633
+ var MAX_USER_AGENT_LENGTH = 1024;
634
+ function readEnv(name) {
635
+ return typeof process !== "undefined" ? process.env?.[name] : void 0;
636
+ }
637
+ function stripTrailingSlashes(url) {
638
+ return url.replace(/\/+$/, "");
639
+ }
640
+ function parseRetryAfter(headers) {
641
+ const raw = headers?.get("retry-after");
642
+ if (!raw) return void 0;
643
+ const parsed = Number.parseInt(raw.trim(), 10);
644
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : void 0;
645
+ }
646
+ function extractErrorMessage(rawText, status) {
647
+ const trimmed = rawText.trim();
648
+ if (!trimmed) return `HTTP ${status}`;
649
+ try {
650
+ const parsed = JSON.parse(trimmed);
651
+ if (parsed && typeof parsed === "object") {
652
+ const record = parsed;
653
+ if (typeof record.detail === "string" && record.detail.trim()) {
654
+ return record.detail;
655
+ }
656
+ if (Array.isArray(record.detail) && record.detail.length > 0) {
657
+ const parts = record.detail.map((item) => {
658
+ if (item && typeof item === "object" && "msg" in item) {
659
+ return String(item.msg);
660
+ }
661
+ return typeof item === "string" ? item : JSON.stringify(item);
662
+ }).filter(Boolean);
663
+ if (parts.length > 0) return parts.join("; ");
664
+ }
665
+ if (typeof record.error === "string" && record.error.trim()) {
666
+ return record.error;
667
+ }
668
+ }
669
+ } catch {
670
+ }
671
+ return trimmed;
672
+ }
673
+ function buildSignal(timeoutMs, externalSignal) {
674
+ if (!externalSignal) {
675
+ return { signal: AbortSignal.timeout(timeoutMs), cleanup: () => {
676
+ } };
677
+ }
678
+ if (typeof AbortSignal.any === "function") {
679
+ return {
680
+ signal: AbortSignal.any([AbortSignal.timeout(timeoutMs), externalSignal]),
681
+ cleanup: () => {
682
+ }
683
+ };
684
+ }
685
+ const controller = new AbortController();
686
+ if (externalSignal.aborted) {
687
+ controller.abort(externalSignal.reason);
688
+ return { signal: controller.signal, cleanup: () => {
689
+ } };
690
+ }
691
+ const onExternalAbort = () => controller.abort(externalSignal.reason);
692
+ externalSignal.addEventListener("abort", onExternalAbort, { once: true });
693
+ const timer = setTimeout(() => {
694
+ const timeoutError = new Error(`Timeout (${timeoutMs}ms)`);
695
+ timeoutError.name = "TimeoutError";
696
+ controller.abort(timeoutError);
697
+ }, timeoutMs);
698
+ return {
699
+ signal: controller.signal,
700
+ cleanup: () => {
701
+ clearTimeout(timer);
702
+ externalSignal.removeEventListener("abort", onExternalAbort);
703
+ }
704
+ };
705
+ }
706
+ async function normalizeUserContext(params, options) {
707
+ const body = {};
708
+ for (const [key, value] of Object.entries(params)) {
709
+ if (value === void 0 || key === "email") continue;
710
+ if (key === "country" && !options.allowCountry) continue;
711
+ body[key] = value;
712
+ }
713
+ const explicitIp = typeof params.user_ip === "string" ? params.user_ip.trim() : "";
714
+ const envIp = readEnv("GRAVITY_INDEX_USER_IP")?.trim() || "";
715
+ body.user_ip = explicitIp || envIp || "caller";
716
+ if (typeof params.user_agent === "string") {
717
+ if (params.user_agent.length > 0) {
718
+ body.user_agent = params.user_agent.slice(0, MAX_USER_AGENT_LENGTH);
719
+ } else {
720
+ delete body.user_agent;
721
+ }
722
+ }
723
+ const explicitHashedEmail = typeof params.hashed_email === "string" ? params.hashed_email.trim() : "";
724
+ if (explicitHashedEmail) {
725
+ body.hashed_email = explicitHashedEmail;
726
+ } else {
727
+ delete body.hashed_email;
728
+ const rawEmail = typeof params.email === "string" ? params.email.trim() : "";
729
+ if (rawEmail) {
730
+ const hashed = await hashPii({ email: rawEmail });
731
+ if (hashed.hashed_email) {
732
+ body.hashed_email = hashed.hashed_email;
733
+ }
734
+ }
735
+ }
736
+ return body;
737
+ }
738
+ function isConsumerSearchResponse(response) {
739
+ return Boolean(response && response.vertical === "consumer");
740
+ }
741
+ function isDeveloperSearchResponse(response) {
742
+ return Boolean(response && response.vertical === "developer");
743
+ }
744
+ var GravityIndex = class {
745
+ constructor(opts = {}) {
746
+ this.opts = opts;
747
+ }
748
+ resolveApiKey(overrides) {
749
+ return (overrides?.apiKey || this.opts.apiKey || readEnv("GRAVITY_PUBLISHER_KEY") || readEnv("GRAVITY_API_KEY") || "").trim();
750
+ }
751
+ resolveIndexUrl() {
752
+ return stripTrailingSlashes(
753
+ this.opts.indexUrl || readEnv("GRAVITY_INDEX_URL") || DEFAULT_INDEX_URL
754
+ );
755
+ }
756
+ async post(path, body, overrides) {
757
+ const apiKey = this.resolveApiKey(overrides);
758
+ if (!apiKey) {
759
+ return {
760
+ ok: false,
761
+ data: null,
762
+ status: 0,
763
+ elapsed: "0",
764
+ error: "Missing Gravity API key (set GRAVITY_PUBLISHER_KEY or GRAVITY_API_KEY, or pass apiKey)"
765
+ };
766
+ }
767
+ const timeoutMs = overrides?.timeoutMs ?? this.opts.timeoutMs ?? DEFAULT_INDEX_TIMEOUT_MS;
768
+ const url = `${this.resolveIndexUrl()}${path}`;
769
+ const start = performance.now();
770
+ const { signal, cleanup } = buildSignal(timeoutMs, overrides?.signal);
771
+ try {
772
+ const res = await fetch(url, {
773
+ method: "POST",
774
+ headers: {
775
+ "Content-Type": "application/json",
776
+ "X-API-Key": apiKey
777
+ },
778
+ body: JSON.stringify(body),
779
+ signal
780
+ });
781
+ const elapsed = (performance.now() - start).toFixed(0);
782
+ const retryAfterSeconds = parseRetryAfter(res.headers);
783
+ if (!res.ok) {
784
+ const errText = await res.text().catch(() => "");
785
+ return {
786
+ ok: false,
787
+ data: null,
788
+ status: res.status,
789
+ elapsed,
790
+ error: extractErrorMessage(errText, res.status),
791
+ ...retryAfterSeconds !== void 0 ? { retryAfterSeconds } : {}
792
+ };
793
+ }
794
+ const data = await res.json();
795
+ return {
796
+ ok: true,
797
+ data,
798
+ status: res.status,
799
+ elapsed,
800
+ ...retryAfterSeconds !== void 0 ? { retryAfterSeconds } : {}
801
+ };
802
+ } catch (err2) {
803
+ const elapsed = (performance.now() - start).toFixed(0);
804
+ const reason = signal.aborted ? signal.reason : void 0;
805
+ const isTimeout = err2 instanceof Error && err2.name === "TimeoutError" || reason instanceof Error && reason.name === "TimeoutError";
806
+ const error = isTimeout ? `Timeout (${timeoutMs}ms)` : err2 instanceof Error ? err2.message : String(err2);
807
+ return { ok: false, data: null, status: 0, elapsed, error };
808
+ } finally {
809
+ cleanup();
810
+ }
811
+ }
812
+ /**
813
+ * Search the Gravity Index for the best developer service (or consumer
814
+ * products when `vertical: 'consumer'` or `filters` are provided).
815
+ *
816
+ * `POST /search`
817
+ */
818
+ async search(params, overrides) {
819
+ const body = await normalizeUserContext(
820
+ params,
821
+ { allowCountry: true }
822
+ );
823
+ return this.post("/search", body, overrides);
824
+ }
825
+ /**
826
+ * Search consumer products that a user can buy, with optional structured
827
+ * filters (brand, merchant, price range, sale status, etc.).
828
+ *
829
+ * `POST /shop/search`
830
+ */
831
+ async shopSearch(params, overrides) {
832
+ const body = await normalizeUserContext(
833
+ params,
834
+ { allowCountry: false }
835
+ );
836
+ return this.post("/shop/search", body, overrides);
837
+ }
838
+ };
839
+
589
840
  // gravity.ts
590
841
  var Gravity = class {
591
842
  /**
592
- * @param opts - Configuration applied to every `getAds()` call.
843
+ * @param opts - Configuration applied to every `getAds()` call and `gravity.index`.
593
844
  *
594
845
  * | Option | Type | Default | Description |
595
846
  * |--------|------|---------|-------------|
@@ -600,10 +851,24 @@ var Gravity = class {
600
851
  * | `timeoutMs` | `number` | `4000` | Request timeout in ms |
601
852
  * | `excludedTopics` | `string[]` | — | Topics to exclude from ad matching |
602
853
  * | `gravityApi` | `string` | production URL | Custom API endpoint |
854
+ * | `index` | `GravityIndexOptions` | — | Optional Gravity Index client overrides |
603
855
  */
604
856
  constructor(opts = {}) {
605
857
  this.opts = opts;
606
858
  }
859
+ /**
860
+ * Gravity Index client sharing this instance's API key (plus any `opts.index`
861
+ * overrides).
862
+ */
863
+ get index() {
864
+ if (!this.indexClient) {
865
+ this.indexClient = new GravityIndex({
866
+ apiKey: this.opts.apiKey,
867
+ ...this.opts.index ?? {}
868
+ });
869
+ }
870
+ return this.indexClient;
871
+ }
607
872
  /**
608
873
  * Fetch ads from the Gravity API. **Never throws.**
609
874
  *
@@ -618,8 +883,9 @@ var Gravity = class {
618
883
  * @returns `{ ads, status, elapsed, requestBody, error? }` — always resolves
619
884
  */
620
885
  async getAds(req, messages, placements, overrides = {}) {
886
+ const { index: _index, ...adOpts } = this.opts;
621
887
  return gravityAds(req, messages, placements, {
622
- ...this.opts,
888
+ ...adOpts,
623
889
  ...overrides
624
890
  });
625
891
  }
@@ -1056,42 +1322,6 @@ var Client = class {
1056
1322
  }
1057
1323
  };
1058
1324
 
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
1325
  // gravity-pixel.ts
1096
1326
  function uuid(prefix) {
1097
1327
  const hex2 = () => Math.random().toString(36).slice(2, 10);
@@ -1547,7 +1777,10 @@ function gravityPixel(opts) {
1547
1777
  // Annotate the CommonJS export names for ESM import in node:
1548
1778
  0 && (module.exports = {
1549
1779
  Client,
1780
+ DEFAULT_INDEX_TIMEOUT_MS,
1781
+ DEFAULT_INDEX_URL,
1550
1782
  Gravity,
1783
+ GravityIndex,
1551
1784
  GravityPixel,
1552
1785
  detectCmpConsent,
1553
1786
  extractClientIp,
@@ -1556,6 +1789,8 @@ function gravityPixel(opts) {
1556
1789
  gravityContextAsync,
1557
1790
  gravityPixel,
1558
1791
  hashPii,
1792
+ isConsumerSearchResponse,
1793
+ isDeveloperSearchResponse,
1559
1794
  readCmpConsent,
1560
1795
  toGravityMessages
1561
1796
  });