@gravity-ai/api 1.6.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.d.mts CHANGED
@@ -1,5 +1,5 @@
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';
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 Ad, m as AdParams } from './types-DsxvJZVE.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-DsxvJZVE.mjs';
3
3
 
4
4
  declare const DEFAULT_INDEX_URL = "https://index.trygravity.com";
5
5
  declare const DEFAULT_INDEX_TIMEOUT_MS = 30000;
@@ -240,6 +240,77 @@ declare function extractClientIp(req: IncomingAdRequest): string | undefined;
240
240
  */
241
241
  declare function gravityAds(req: IncomingAdRequest, messages: MessageObject[], placements: PlacementObject[], opts?: GravityAdsOptions): Promise<GravityAdsResult>;
242
242
 
243
+ interface InlineAdInput {
244
+ adText?: string | null;
245
+ brandName?: string | null;
246
+ title?: string | null;
247
+ clickUrl?: string | null;
248
+ shortClickUrl?: string | null;
249
+ impUrl?: string | null;
250
+ placement_id?: string | null;
251
+ }
252
+ interface InlineAdOptions {
253
+ /** Show the disclosure label (default: true). */
254
+ showLabel?: boolean;
255
+ /** Disclosure label text (default: "Sponsored"). */
256
+ labelText?: string;
257
+ /** Prefer `shortClickUrl` when present (default: false). */
258
+ useShortUrl?: boolean;
259
+ }
260
+ interface InlineAdParts {
261
+ /** Text before the hyperlinked brand/phrase. */
262
+ before: string;
263
+ /** Hyperlinked text (brand name when available, else full copy). */
264
+ linkText: string;
265
+ /** Text after the hyperlinked brand/phrase. */
266
+ after: string;
267
+ /** Validated http(s) click URL, or null if absent/unsafe. */
268
+ url: string | null;
269
+ /** Disclosure label (e.g. "Sponsored"), or null when `showLabel: false`. */
270
+ label: string | null;
271
+ }
272
+ interface FormatInlineAdOptions extends InlineAdOptions {
273
+ /** Output format (default: "markdown"). */
274
+ format?: 'markdown' | 'plain';
275
+ }
276
+ interface AppendInlineAdOptions extends FormatInlineAdOptions {
277
+ /** Text inserted between the response and the inline ad (default: "\n\n"). */
278
+ separator?: string;
279
+ /** Max ms to wait for a pending ad promise after the stream ends (default: 500). */
280
+ adTimeoutMs?: number;
281
+ /** Pick the ad for a specific `placement_id` when passing a `GravityAdsResult`. */
282
+ placementId?: string;
283
+ /** Fire `impUrl` when the inline ad is appended (default: true). */
284
+ trackImpression?: boolean;
285
+ /** Custom fetch implementation for impression tracking. */
286
+ fetchFn?: (url: string, init?: {
287
+ method?: string;
288
+ }) => Promise<unknown>;
289
+ }
290
+ /**
291
+ * Split an ad into inline text segments so the brand name is hyperlinked
292
+ * inside the copy (no card/box required).
293
+ */
294
+ declare function splitInlineAd(ad: InlineAdInput | null | undefined, options?: InlineAdOptions): InlineAdParts | null;
295
+ /**
296
+ * Format an ad as a single inline Markdown (or plain-text) sentence with the
297
+ * brand name hyperlinked and a `(Sponsored)` disclosure.
298
+ */
299
+ declare function formatInlineAd(ad: InlineAdInput | null | undefined, options?: FormatInlineAdOptions): string;
300
+ /**
301
+ * Fire-and-forget impression pixel for server-side / streaming inline ads
302
+ * where no browser SDK is rendering the ad. Never throws.
303
+ */
304
+ declare function trackInlineImpression(ad: InlineAdInput | null | undefined, fetchFn?: (url: string, init?: {
305
+ method?: string;
306
+ }) => Promise<unknown>): Promise<boolean>;
307
+ type AdSource = Ad | InlineAdInput | GravityAdsResult | null | undefined;
308
+ /**
309
+ * Pass every chunk of a text stream straight through, then append the inline
310
+ * ad sentence when the stream finishes. Never throws on ad errors or timeouts.
311
+ */
312
+ declare function appendInlineAd(stream: AsyncIterable<string>, adOrPromise: AdSource | Promise<AdSource>, options?: AppendInlineAdOptions): AsyncGenerator<string, void, unknown>;
313
+
243
314
  /**
244
315
  * @deprecated Use `Gravity` instead. See README for migration guide.
245
316
  */
@@ -573,5 +644,5 @@ declare class GravityPixel {
573
644
  */
574
645
  declare function gravityPixel(opts: GravityPixelConfig): GravityPixel;
575
646
 
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 };
577
- export type { ClientParams, ConsentSignal, GravityPixelConfig, HashedIdentity, RawIdentity };
647
+ 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, appendInlineAd, detectCmpConsent, extractClientIp, formatInlineAd, gravityAds, gravityContext, gravityContextAsync, gravityPixel, hashPii, isConsumerSearchResponse, isDeveloperSearchResponse, readCmpConsent, splitInlineAd, toGravityMessages, trackInlineImpression };
648
+ export type { AppendInlineAdOptions, ClientParams, ConsentSignal, FormatInlineAdOptions, GravityPixelConfig, HashedIdentity, InlineAdInput, InlineAdOptions, InlineAdParts, RawIdentity };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
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';
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 Ad, m as AdParams } from './types-DsxvJZVE.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-DsxvJZVE.js';
3
3
 
4
4
  declare const DEFAULT_INDEX_URL = "https://index.trygravity.com";
5
5
  declare const DEFAULT_INDEX_TIMEOUT_MS = 30000;
@@ -240,6 +240,77 @@ declare function extractClientIp(req: IncomingAdRequest): string | undefined;
240
240
  */
241
241
  declare function gravityAds(req: IncomingAdRequest, messages: MessageObject[], placements: PlacementObject[], opts?: GravityAdsOptions): Promise<GravityAdsResult>;
242
242
 
243
+ interface InlineAdInput {
244
+ adText?: string | null;
245
+ brandName?: string | null;
246
+ title?: string | null;
247
+ clickUrl?: string | null;
248
+ shortClickUrl?: string | null;
249
+ impUrl?: string | null;
250
+ placement_id?: string | null;
251
+ }
252
+ interface InlineAdOptions {
253
+ /** Show the disclosure label (default: true). */
254
+ showLabel?: boolean;
255
+ /** Disclosure label text (default: "Sponsored"). */
256
+ labelText?: string;
257
+ /** Prefer `shortClickUrl` when present (default: false). */
258
+ useShortUrl?: boolean;
259
+ }
260
+ interface InlineAdParts {
261
+ /** Text before the hyperlinked brand/phrase. */
262
+ before: string;
263
+ /** Hyperlinked text (brand name when available, else full copy). */
264
+ linkText: string;
265
+ /** Text after the hyperlinked brand/phrase. */
266
+ after: string;
267
+ /** Validated http(s) click URL, or null if absent/unsafe. */
268
+ url: string | null;
269
+ /** Disclosure label (e.g. "Sponsored"), or null when `showLabel: false`. */
270
+ label: string | null;
271
+ }
272
+ interface FormatInlineAdOptions extends InlineAdOptions {
273
+ /** Output format (default: "markdown"). */
274
+ format?: 'markdown' | 'plain';
275
+ }
276
+ interface AppendInlineAdOptions extends FormatInlineAdOptions {
277
+ /** Text inserted between the response and the inline ad (default: "\n\n"). */
278
+ separator?: string;
279
+ /** Max ms to wait for a pending ad promise after the stream ends (default: 500). */
280
+ adTimeoutMs?: number;
281
+ /** Pick the ad for a specific `placement_id` when passing a `GravityAdsResult`. */
282
+ placementId?: string;
283
+ /** Fire `impUrl` when the inline ad is appended (default: true). */
284
+ trackImpression?: boolean;
285
+ /** Custom fetch implementation for impression tracking. */
286
+ fetchFn?: (url: string, init?: {
287
+ method?: string;
288
+ }) => Promise<unknown>;
289
+ }
290
+ /**
291
+ * Split an ad into inline text segments so the brand name is hyperlinked
292
+ * inside the copy (no card/box required).
293
+ */
294
+ declare function splitInlineAd(ad: InlineAdInput | null | undefined, options?: InlineAdOptions): InlineAdParts | null;
295
+ /**
296
+ * Format an ad as a single inline Markdown (or plain-text) sentence with the
297
+ * brand name hyperlinked and a `(Sponsored)` disclosure.
298
+ */
299
+ declare function formatInlineAd(ad: InlineAdInput | null | undefined, options?: FormatInlineAdOptions): string;
300
+ /**
301
+ * Fire-and-forget impression pixel for server-side / streaming inline ads
302
+ * where no browser SDK is rendering the ad. Never throws.
303
+ */
304
+ declare function trackInlineImpression(ad: InlineAdInput | null | undefined, fetchFn?: (url: string, init?: {
305
+ method?: string;
306
+ }) => Promise<unknown>): Promise<boolean>;
307
+ type AdSource = Ad | InlineAdInput | GravityAdsResult | null | undefined;
308
+ /**
309
+ * Pass every chunk of a text stream straight through, then append the inline
310
+ * ad sentence when the stream finishes. Never throws on ad errors or timeouts.
311
+ */
312
+ declare function appendInlineAd(stream: AsyncIterable<string>, adOrPromise: AdSource | Promise<AdSource>, options?: AppendInlineAdOptions): AsyncGenerator<string, void, unknown>;
313
+
243
314
  /**
244
315
  * @deprecated Use `Gravity` instead. See README for migration guide.
245
316
  */
@@ -573,5 +644,5 @@ declare class GravityPixel {
573
644
  */
574
645
  declare function gravityPixel(opts: GravityPixelConfig): GravityPixel;
575
646
 
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 };
577
- export type { ClientParams, ConsentSignal, GravityPixelConfig, HashedIdentity, RawIdentity };
647
+ 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, appendInlineAd, detectCmpConsent, extractClientIp, formatInlineAd, gravityAds, gravityContext, gravityContextAsync, gravityPixel, hashPii, isConsumerSearchResponse, isDeveloperSearchResponse, readCmpConsent, splitInlineAd, toGravityMessages, trackInlineImpression };
648
+ export type { AppendInlineAdOptions, ClientParams, ConsentSignal, FormatInlineAdOptions, GravityPixelConfig, HashedIdentity, InlineAdInput, InlineAdOptions, InlineAdParts, 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.6.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",
@@ -122,8 +122,10 @@ __export(index_exports, {
122
122
  Gravity: () => Gravity,
123
123
  GravityIndex: () => GravityIndex,
124
124
  GravityPixel: () => GravityPixel,
125
+ appendInlineAd: () => appendInlineAd,
125
126
  detectCmpConsent: () => detectCmpConsent,
126
127
  extractClientIp: () => extractClientIp,
128
+ formatInlineAd: () => formatInlineAd,
127
129
  gravityAds: () => gravityAds,
128
130
  gravityContext: () => gravityContext,
129
131
  gravityContextAsync: () => gravityContextAsync,
@@ -132,7 +134,9 @@ __export(index_exports, {
132
134
  isConsumerSearchResponse: () => isConsumerSearchResponse,
133
135
  isDeveloperSearchResponse: () => isDeveloperSearchResponse,
134
136
  readCmpConsent: () => readCmpConsent,
135
- toGravityMessages: () => toGravityMessages
137
+ splitInlineAd: () => splitInlineAd,
138
+ toGravityMessages: () => toGravityMessages,
139
+ trackInlineImpression: () => trackInlineImpression
136
140
  });
137
141
  module.exports = __toCommonJS(index_exports);
138
142
 
@@ -1165,6 +1169,150 @@ function nodeDevice() {
1165
1169
  };
1166
1170
  }
1167
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
+
1168
1316
  // client.ts
1169
1317
  var import_axios = __toESM(require("axios"));
1170
1318
  var DEFAULT_ENDPOINT = "https://server.trygravity.ai";
@@ -1782,8 +1930,10 @@ function gravityPixel(opts) {
1782
1930
  Gravity,
1783
1931
  GravityIndex,
1784
1932
  GravityPixel,
1933
+ appendInlineAd,
1785
1934
  detectCmpConsent,
1786
1935
  extractClientIp,
1936
+ formatInlineAd,
1787
1937
  gravityAds,
1788
1938
  gravityContext,
1789
1939
  gravityContextAsync,
@@ -1792,5 +1942,7 @@ function gravityPixel(opts) {
1792
1942
  isConsumerSearchResponse,
1793
1943
  isDeveloperSearchResponse,
1794
1944
  readCmpConsent,
1795
- toGravityMessages
1945
+ splitInlineAd,
1946
+ toGravityMessages,
1947
+ trackInlineImpression
1796
1948
  });
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.6.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",
@@ -1111,6 +1111,150 @@ function nodeDevice() {
1111
1111
  };
1112
1112
  }
1113
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
+
1114
1258
  // client.ts
1115
1259
  import axios from "axios";
1116
1260
  var DEFAULT_ENDPOINT = "https://server.trygravity.ai";
@@ -1727,8 +1871,10 @@ export {
1727
1871
  Gravity,
1728
1872
  GravityIndex,
1729
1873
  GravityPixel,
1874
+ appendInlineAd,
1730
1875
  detectCmpConsent,
1731
1876
  extractClientIp,
1877
+ formatInlineAd,
1732
1878
  gravityAds,
1733
1879
  gravityContext,
1734
1880
  gravityContextAsync,
@@ -1737,5 +1883,7 @@ export {
1737
1883
  isConsumerSearchResponse,
1738
1884
  isDeveloperSearchResponse,
1739
1885
  readCmpConsent,
1740
- toGravityMessages
1886
+ splitInlineAd,
1887
+ toGravityMessages,
1888
+ trackInlineImpression
1741
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.6.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.6.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}`;
@@ -1124,4 +1124,4 @@ interface IncomingAdRequest {
1124
1124
  ip?: string;
1125
1125
  }
1126
1126
 
1127
- export type { Placement as $, AdParams as A, IndexMppCheckout as B, IndexPriceRange as C, DeviceObject as D, IndexProduct as E, FrameSize as F, GravityIndexOptions as G, HostTheme as H, IndexSearchParams as I, IndexRecommendation as J, IndexSearchContext as K, IndexSearchOption as L, MessageObject as M, IndexShopFacets as N, IndexShopFilters as O, PlacementObject as P, IndexUcpCheckout as Q, IndexVertical as R, IndexWebResult as S, LeadFormConfig as T, LeadFormField as U, LeadFormPrefill as V, McpConnect as W, McpConnectHandler as X, McpConnectRequest as Y, McpConnectResult as Z, ModelUsage as _, IndexRequestOptions as a, PromptAction as a0, RenderEnvelope as a1, Role as a2, SlotSize as a3, TextMetrics as a4, UnitCapability as a5, UnknownAdAction as a6, UserObject as a7, IndexResult as b, IndexSearchResponse as c, IndexShopSearchParams as d, IndexShopSearchResponse as e, IndexDeveloperSearchResponse as f, GravityOptions as g, IncomingAdRequest as h, GravityAdsOptions as i, GravityAdsResult as j, GravityContextOverrides as k, GravityContext as l, Ad as m, AdAction as n, AdLayout as o, AdUnit as p, ApiErrorResponse as q, Gender as r, IndexAlternative as s, IndexContextMessage as t, IndexCredentialRequest as u, IndexGender as v, IndexInstallInstructions as w, IndexInstallStep as x, IndexMcpConnect as y, IndexMonetization as z };
1127
+ export type { Placement as $, Ad as A, IndexMppCheckout as B, IndexPriceRange as C, DeviceObject as D, IndexProduct as E, FrameSize as F, GravityIndexOptions as G, HostTheme as H, IndexSearchParams as I, IndexRecommendation as J, IndexSearchContext as K, IndexSearchOption as L, MessageObject as M, IndexShopFacets as N, IndexShopFilters as O, PlacementObject as P, IndexUcpCheckout as Q, IndexVertical as R, IndexWebResult as S, LeadFormConfig as T, LeadFormField as U, LeadFormPrefill as V, McpConnect as W, McpConnectHandler as X, McpConnectRequest as Y, McpConnectResult as Z, ModelUsage as _, IndexRequestOptions as a, PromptAction as a0, RenderEnvelope as a1, Role as a2, SlotSize as a3, TextMetrics as a4, UnitCapability as a5, UnknownAdAction as a6, UserObject as a7, IndexResult as b, IndexSearchResponse as c, IndexShopSearchParams as d, IndexShopSearchResponse as e, IndexDeveloperSearchResponse as f, GravityOptions as g, IncomingAdRequest as h, GravityAdsOptions as i, GravityAdsResult as j, GravityContextOverrides as k, GravityContext as l, AdParams as m, AdAction as n, AdLayout as o, AdUnit as p, ApiErrorResponse as q, Gender as r, IndexAlternative as s, IndexContextMessage as t, IndexCredentialRequest as u, IndexGender as v, IndexInstallInstructions as w, IndexInstallStep as x, IndexMcpConnect as y, IndexMonetization as z };
@@ -1124,4 +1124,4 @@ interface IncomingAdRequest {
1124
1124
  ip?: string;
1125
1125
  }
1126
1126
 
1127
- export type { Placement as $, AdParams as A, IndexMppCheckout as B, IndexPriceRange as C, DeviceObject as D, IndexProduct as E, FrameSize as F, GravityIndexOptions as G, HostTheme as H, IndexSearchParams as I, IndexRecommendation as J, IndexSearchContext as K, IndexSearchOption as L, MessageObject as M, IndexShopFacets as N, IndexShopFilters as O, PlacementObject as P, IndexUcpCheckout as Q, IndexVertical as R, IndexWebResult as S, LeadFormConfig as T, LeadFormField as U, LeadFormPrefill as V, McpConnect as W, McpConnectHandler as X, McpConnectRequest as Y, McpConnectResult as Z, ModelUsage as _, IndexRequestOptions as a, PromptAction as a0, RenderEnvelope as a1, Role as a2, SlotSize as a3, TextMetrics as a4, UnitCapability as a5, UnknownAdAction as a6, UserObject as a7, IndexResult as b, IndexSearchResponse as c, IndexShopSearchParams as d, IndexShopSearchResponse as e, IndexDeveloperSearchResponse as f, GravityOptions as g, IncomingAdRequest as h, GravityAdsOptions as i, GravityAdsResult as j, GravityContextOverrides as k, GravityContext as l, Ad as m, AdAction as n, AdLayout as o, AdUnit as p, ApiErrorResponse as q, Gender as r, IndexAlternative as s, IndexContextMessage as t, IndexCredentialRequest as u, IndexGender as v, IndexInstallInstructions as w, IndexInstallStep as x, IndexMcpConnect as y, IndexMonetization as z };
1127
+ export type { Placement as $, Ad as A, IndexMppCheckout as B, IndexPriceRange as C, DeviceObject as D, IndexProduct as E, FrameSize as F, GravityIndexOptions as G, HostTheme as H, IndexSearchParams as I, IndexRecommendation as J, IndexSearchContext as K, IndexSearchOption as L, MessageObject as M, IndexShopFacets as N, IndexShopFilters as O, PlacementObject as P, IndexUcpCheckout as Q, IndexVertical as R, IndexWebResult as S, LeadFormConfig as T, LeadFormField as U, LeadFormPrefill as V, McpConnect as W, McpConnectHandler as X, McpConnectRequest as Y, McpConnectResult as Z, ModelUsage as _, IndexRequestOptions as a, PromptAction as a0, RenderEnvelope as a1, Role as a2, SlotSize as a3, TextMetrics as a4, UnitCapability as a5, UnknownAdAction as a6, UserObject as a7, IndexResult as b, IndexSearchResponse as c, IndexShopSearchParams as d, IndexShopSearchResponse as e, IndexDeveloperSearchResponse as f, GravityOptions as g, IncomingAdRequest as h, GravityAdsOptions as i, GravityAdsResult as j, GravityContextOverrides as k, GravityContext as l, AdParams as m, AdAction as n, AdLayout as o, AdUnit as p, ApiErrorResponse as q, Gender as r, IndexAlternative as s, IndexContextMessage as t, IndexCredentialRequest as u, IndexGender as v, IndexInstallInstructions as w, IndexInstallStep as x, IndexMcpConnect as y, IndexMonetization as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gravity-ai/api",
3
- "version": "1.6.0",
3
+ "version": "1.7.0",
4
4
  "description": "Gravity JS SDK for retrieving targeted advertisements",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",