@gravity-ai/api 1.2.1 → 1.3.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
@@ -179,6 +179,10 @@ Fetch ads. **Never throws.** Returns `{ ads: [] }` on any failure.
179
179
 
180
180
  **Returns:** `{ ads: Ad[], status: number, elapsed: string, requestBody: object, error?: string }`
181
181
 
182
+ Set `supportsMcpConnect: true` on a placement only when your app can connect an MCP server on click. Eligible ads then carry `connect: { type: 'mcp', id, serverUrl, name, iconUrl? }` and the button copy in `cta`; the types `McpConnect`, `McpConnectRequest`, `McpConnectResult` and `McpConnectHandler` describe the contract.
183
+
184
+ Each placement also declares the unit capabilities a Gravity renderer draws (`units.v1`, `image`, `frame.gfb1` while frames are on, `action.prompt` and `connect.mcp` when the placement opts in), unless `supportsSpec` is `false`. Ads then may carry a `unit` that `@gravity-ai/react` and `@gravity-ai/ui` draw. When `getAds` runs in a browser it also sends the page's font and theme. Any `slot`, `text`, `theme` or `capabilities` you set on a placement is sent as is; in a browser, `getPlacementContext(element)` from `@gravity-ai/react` fills them from the ad's container.
185
+
182
186
  ### `gravityContext(overrides)`
183
187
 
184
188
  Client-side. Collects device + user context. Returns a plain object to include in your request body.
@@ -6,7 +6,11 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
6
6
  throw Error('Dynamic require of "' + x + '" is not supported');
7
7
  });
8
8
  var __commonJS = (cb, mod) => function __require2() {
9
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9
+ try {
10
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
11
+ } catch (e) {
12
+ throw mod = 0, e;
13
+ }
10
14
  };
11
15
 
12
16
  export {
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
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-CnuFH98L.mjs';
2
- export { e as AdLayout, h as ApiErrorResponse, D as DeviceObject, k as Gender, g as LeadFormConfig, L as LeadFormField, f as LeadFormPrefill, i as Placement, R as RenderEnvelope, j as Role, U as UserObject } from './types-CnuFH98L.mjs';
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-0HZXp9b_.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-0HZXp9b_.mjs';
3
3
 
4
4
  /**
5
5
  * Gravity ad client.
@@ -506,4 +506,5 @@ declare class GravityPixel {
506
506
  */
507
507
  declare function gravityPixel(opts: GravityPixelConfig): GravityPixel;
508
508
 
509
- export { Ad, AdParams, Client, type ClientParams, type ConsentSignal, Gravity, GravityAdsOptions, GravityAdsResult, GravityContext, GravityContextOverrides, GravityPixel, type GravityPixelConfig, type HashedIdentity, IncomingAdRequest, MessageObject, PlacementObject, type RawIdentity, detectCmpConsent, extractClientIp, gravityAds, gravityContext, gravityContextAsync, gravityPixel, hashPii, readCmpConsent, toGravityMessages };
509
+ export { Ad, AdParams, Client, Gravity, GravityAdsOptions, GravityAdsResult, GravityContext, GravityContextOverrides, GravityPixel, IncomingAdRequest, MessageObject, PlacementObject, detectCmpConsent, extractClientIp, gravityAds, gravityContext, gravityContextAsync, gravityPixel, hashPii, readCmpConsent, toGravityMessages };
510
+ export type { ClientParams, ConsentSignal, GravityPixelConfig, HashedIdentity, RawIdentity };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
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-CnuFH98L.js';
2
- export { e as AdLayout, h as ApiErrorResponse, D as DeviceObject, k as Gender, g as LeadFormConfig, L as LeadFormField, f as LeadFormPrefill, i as Placement, R as RenderEnvelope, j as Role, U as UserObject } from './types-CnuFH98L.js';
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-0HZXp9b_.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-0HZXp9b_.js';
3
3
 
4
4
  /**
5
5
  * Gravity ad client.
@@ -506,4 +506,5 @@ declare class GravityPixel {
506
506
  */
507
507
  declare function gravityPixel(opts: GravityPixelConfig): GravityPixel;
508
508
 
509
- export { Ad, AdParams, Client, type ClientParams, type ConsentSignal, Gravity, GravityAdsOptions, GravityAdsResult, GravityContext, GravityContextOverrides, GravityPixel, type GravityPixelConfig, type HashedIdentity, IncomingAdRequest, MessageObject, PlacementObject, type RawIdentity, detectCmpConsent, extractClientIp, gravityAds, gravityContext, gravityContextAsync, gravityPixel, hashPii, readCmpConsent, toGravityMessages };
509
+ export { Ad, AdParams, Client, Gravity, GravityAdsOptions, GravityAdsResult, GravityContext, GravityContextOverrides, GravityPixel, IncomingAdRequest, MessageObject, PlacementObject, detectCmpConsent, extractClientIp, gravityAds, gravityContext, gravityContextAsync, gravityPixel, hashPii, readCmpConsent, toGravityMessages };
510
+ export type { ClientParams, ConsentSignal, GravityPixelConfig, HashedIdentity, RawIdentity };
package/dist/index.js CHANGED
@@ -6,7 +6,11 @@ var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
8
  var __commonJS = (cb, mod) => function __require() {
9
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9
+ try {
10
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
11
+ } catch (e) {
12
+ throw mod = 0, e;
13
+ }
10
14
  };
11
15
  var __export = (target, all) => {
12
16
  for (var name in all)
@@ -35,7 +39,7 @@ var require_package = __commonJS({
35
39
  "package.json"(exports2, module2) {
36
40
  module2.exports = {
37
41
  name: "@gravity-ai/api",
38
- version: "1.2.1",
42
+ version: "1.3.0",
39
43
  description: "Gravity JS SDK for retrieving targeted advertisements",
40
44
  main: "dist/index.js",
41
45
  module: "dist/index.mjs",
@@ -97,13 +101,13 @@ var require_package = __commonJS({
97
101
  }
98
102
  },
99
103
  dependencies: {
100
- axios: "^1.13.2"
104
+ axios: "^1.21.0"
101
105
  },
102
106
  devDependencies: {
103
- "@opentui/core": "^0.1.80",
104
- tsup: "^8.0.1",
107
+ "@opentui/core": "^0.8.0",
108
+ tsup: "^9.0.0",
105
109
  typescript: "^5.3.3",
106
- vitest: "^1.2.1"
110
+ vitest: "^4.1.12"
107
111
  }
108
112
  };
109
113
  }
@@ -127,6 +131,156 @@ __export(index_exports, {
127
131
  });
128
132
  module.exports = __toCommonJS(index_exports);
129
133
 
134
+ // sdk.ts
135
+ var pkg = (() => {
136
+ try {
137
+ return require_package();
138
+ } catch {
139
+ return { name: "@gravity-ai/api", version: "0.0.0" };
140
+ }
141
+ })();
142
+ var SDK = { name: pkg.name, version: pkg.version };
143
+
144
+ // ../ui/src/theme.ts
145
+ var GRAVITY_DARK_VARS = {
146
+ "--gravity-bg": "#1F1F23",
147
+ "--gravity-text": "#FAFAFA",
148
+ "--gravity-text-muted": "#A1A1AA",
149
+ "--gravity-border": "#3F3F46",
150
+ "--gravity-muted": "#27272A",
151
+ "--background": "240 6% 13%",
152
+ "--foreground": "0 0% 98%",
153
+ "--card": "240 6% 13%",
154
+ "--card-foreground": "0 0% 98%",
155
+ "--muted": "240 5% 16%",
156
+ "--muted-foreground": "240 5% 65%",
157
+ "--border": "240 5% 26%"
158
+ };
159
+ var GRAVITY_DARK_WIDGET_VARS = Object.fromEntries(
160
+ Object.entries(GRAVITY_DARK_VARS).filter(
161
+ ([k]) => k.startsWith("--gravity-")
162
+ )
163
+ );
164
+ function parseColor(value) {
165
+ const m = value.match(/rgba?\(([^)]+)\)/);
166
+ if (!m) return null;
167
+ const parts = m[1].split(",").map((p) => parseFloat(p.trim()));
168
+ if (parts.length < 3 || parts.some((n) => Number.isNaN(n))) return null;
169
+ return [parts[0], parts[1], parts[2], parts.length >= 4 ? parts[3] : 1];
170
+ }
171
+ function luminance(r, g, b) {
172
+ return (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
173
+ }
174
+ function effectiveBackground(el) {
175
+ let node = el;
176
+ while (node) {
177
+ if (!node.hasAttribute("data-gravity-ad")) {
178
+ const bg = getComputedStyle(node).backgroundColor;
179
+ const c = bg ? parseColor(bg) : null;
180
+ if (c && c[3] > 0.1) return [c[0], c[1], c[2]];
181
+ }
182
+ node = node.parentElement;
183
+ }
184
+ return null;
185
+ }
186
+ function hostIsDark(el) {
187
+ try {
188
+ const bg = effectiveBackground(el);
189
+ if (bg) return luminance(bg[0], bg[1], bg[2]) < 0.4;
190
+ const text = parseColor(getComputedStyle(el).color);
191
+ if (text) return luminance(text[0], text[1], text[2]) > 0.6;
192
+ return typeof matchMedia === "function" && matchMedia("(prefers-color-scheme: dark)").matches;
193
+ } catch {
194
+ return false;
195
+ }
196
+ }
197
+
198
+ // ../ui/src/units/collect.ts
199
+ var SAMPLE = "Find the right tool for your team and ship your next project faster. Try it free today.";
200
+ var SAMPLE_PX = 100;
201
+ var metricsCache = /* @__PURE__ */ new Map();
202
+ function hasDom() {
203
+ return typeof window !== "undefined" && typeof document !== "undefined";
204
+ }
205
+ function hostElement(el) {
206
+ if (el) return el;
207
+ return hasDom() ? document.body ?? document.documentElement : null;
208
+ }
209
+ function primaryFamily(stack) {
210
+ const first = stack.split(",")[0]?.trim().replace(/^["']|["']$/g, "");
211
+ return first && first.length <= 80 ? first : void 0;
212
+ }
213
+ function hex(value) {
214
+ const v = value.trim();
215
+ if (/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.test(v)) {
216
+ return (v.length === 4 ? "#" + [...v.slice(1)].map((c2) => c2 + c2).join("") : v).toUpperCase();
217
+ }
218
+ const c = parseColor(v);
219
+ if (!c || c[3] === 0) return void 0;
220
+ return "#" + c.slice(0, 3).map((n) => Math.round(Math.min(255, Math.max(0, n))).toString(16).padStart(2, "0")).join("").toUpperCase();
221
+ }
222
+ function px(value, rootPx) {
223
+ const m = /^(-?[\d.]+)(px|rem)$/.exec(value.trim());
224
+ if (!m) return void 0;
225
+ const n = parseFloat(m[1]) * (m[2] === "rem" ? rootPx : 1);
226
+ return Number.isFinite(n) && n >= 0 ? Math.round(n) : void 0;
227
+ }
228
+ function measureText(el) {
229
+ try {
230
+ const node = hostElement(el);
231
+ if (!node) return void 0;
232
+ const stack = getComputedStyle(node).fontFamily;
233
+ const fontFamily = stack ? primaryFamily(stack) : void 0;
234
+ if (!fontFamily) return void 0;
235
+ const cached = metricsCache.get(stack);
236
+ if (cached) return cached;
237
+ const ctx = document.createElement("canvas").getContext("2d");
238
+ if (!ctx) return { fontFamily };
239
+ const measure = (weight) => {
240
+ ctx.font = weight + " " + SAMPLE_PX + "px " + stack;
241
+ return Math.round(ctx.measureText(SAMPLE).width / (SAMPLE.length * SAMPLE_PX) * 1e3) / 1e3;
242
+ };
243
+ const regular = measure(400);
244
+ const bold = measure(700);
245
+ if (!(regular > 0) || !(bold > 0)) return { fontFamily };
246
+ const metrics = { fontFamily, avgCharEm: { regular, bold } };
247
+ const fonts = document.fonts;
248
+ if (typeof fonts?.check !== "function" || fonts.check(SAMPLE_PX + "px " + stack)) metricsCache.set(stack, metrics);
249
+ return metrics;
250
+ } catch {
251
+ return void 0;
252
+ }
253
+ }
254
+ function readHostTheme(el) {
255
+ try {
256
+ const node = hostElement(el);
257
+ if (!node) return void 0;
258
+ const cs = getComputedStyle(node);
259
+ const theme = { scheme: hostIsDark(node) ? "dark" : "light" };
260
+ const bg = effectiveBackground(node);
261
+ if (bg) theme.background = hex("rgb(" + bg.join(",") + ")");
262
+ const fg = hex(cs.color);
263
+ if (fg) theme.foreground = fg;
264
+ const accent = hex(cs.getPropertyValue("--gravity-accent"));
265
+ if (accent) theme.accent = accent;
266
+ const rootPx = parseFloat(getComputedStyle(document.documentElement).fontSize) || 16;
267
+ const radius = px(cs.getPropertyValue("--gravity-radius"), rootPx);
268
+ if (radius !== void 0) theme.radius = radius;
269
+ const family = cs.fontFamily ? primaryFamily(cs.fontFamily) : void 0;
270
+ if (family) theme.fontFamily = family;
271
+ return theme;
272
+ } catch {
273
+ return void 0;
274
+ }
275
+ }
276
+ function capabilitiesFor({ frames = false, promptAction = false, mcpConnect = false } = {}) {
277
+ const caps = ["units.v1", "image"];
278
+ if (frames) caps.push("frame.gfb1");
279
+ if (promptAction) caps.push("action.prompt");
280
+ if (mcpConnect) caps.push("connect.mcp");
281
+ return caps;
282
+ }
283
+
130
284
  // ads.ts
131
285
  var DEFAULT_GRAVITY_API = "https://server.trygravity.ai/api/v1/ad";
132
286
  var DEFAULT_TIMEOUT_MS = 4e3;
@@ -150,6 +304,23 @@ function extractClientIp(req) {
150
304
  if (req.ip) return req.ip;
151
305
  return void 0;
152
306
  }
307
+ function withUnitContext(placements, frames) {
308
+ if (!Array.isArray(placements)) return placements;
309
+ const text = measureText();
310
+ const theme = readHostTheme();
311
+ return placements.map(
312
+ (p) => p && typeof p === "object" ? {
313
+ ...text ? { text } : {},
314
+ ...theme ? { theme } : {},
315
+ capabilities: capabilitiesFor({
316
+ frames,
317
+ promptAction: p.supportsPromptAction === true,
318
+ mcpConnect: p.supportsMcpConnect === true
319
+ }),
320
+ ...p
321
+ } : p
322
+ );
323
+ }
153
324
  async function gravityAds(req, messages, placements, opts = {}) {
154
325
  const apiKey = opts.apiKey || (typeof process !== "undefined" ? process.env?.GRAVITY_API_KEY : void 0);
155
326
  const gravityApi = opts.gravityApi || DEFAULT_GRAVITY_API;
@@ -161,10 +332,13 @@ async function gravityAds(req, messages, placements, opts = {}) {
161
332
  const clientUser = ctx?.user || {};
162
333
  const clientDevice = ctx?.device || {};
163
334
  const clientIp = extractClientIp(req);
335
+ const supportsSpec = opts.supportsSpec ?? true;
336
+ const frames = opts.enableFrames ?? supportsSpec;
164
337
  const body = {
338
+ sdk: SDK,
165
339
  messages: toGravityMessages(messages),
166
340
  sessionId: ctx?.sessionId,
167
- placements,
341
+ placements: supportsSpec ? withUnitContext(placements, frames) : placements,
168
342
  user: {
169
343
  ...clientUser,
170
344
  id: clientUser.id || clientUser.userId || "anonymous"
@@ -180,12 +354,13 @@ async function gravityAds(req, messages, placements, opts = {}) {
180
354
  body.relevancy = opts.relevancy ?? 0.2;
181
355
  body.testAd = opts.production === true ? false : true;
182
356
  if (body.testAd && opts.alwaysReturn === true) body.alwaysReturn = true;
183
- const supportsSpec = opts.supportsSpec ?? true;
357
+ if (body.testAd && opts.testAdFormat === "action") body.testAdFormat = "action";
184
358
  body.supportsSpec = supportsSpec;
185
359
  if (supportsSpec) body.specCapabilities = opts.specCapabilities ?? "web1";
186
- if (opts.enableFrames ?? supportsSpec) body.supportsFrames = true;
360
+ if (frames) body.supportsFrames = true;
187
361
  if (body.testAd && opts.adLayout) body.adLayout = opts.adLayout;
188
362
  if (opts.excludedTopics) body.excludedTopics = opts.excludedTopics;
363
+ if (opts.usage) body.usage = opts.usage;
189
364
  const start = performance.now();
190
365
  try {
191
366
  const res = await fetch(gravityApi, {
@@ -447,7 +622,7 @@ function nodeDevice() {
447
622
  const rows = typeof process !== "undefined" ? process.stdout?.rows || 24 : 24;
448
623
  const env = typeof process !== "undefined" ? process.env : {};
449
624
  return {
450
- ua: `gravity-js/${PKG_VERSION} (${os?.type() || "unknown"} ${os?.arch() || "unknown"}; ${runtimeTag})`,
625
+ ua: `gravity-js/${SDK.version} (${os?.type() || "unknown"} ${os?.arch() || "unknown"}; ${runtimeTag})`,
451
626
  os: os ? `${os.type()} ${os.release()}` : void 0,
452
627
  browser: "cli",
453
628
  device_type: env.CI ? "server" : "desktop",
@@ -467,13 +642,6 @@ function nodeDevice() {
467
642
  is_ci: !!env.CI
468
643
  };
469
644
  }
470
- var PKG_VERSION = (() => {
471
- try {
472
- return require_package().version;
473
- } catch {
474
- return "0.0.0";
475
- }
476
- })();
477
645
 
478
646
  // client.ts
479
647
  var import_axios = __toESM(require("axios"));
@@ -577,6 +745,7 @@ var Client = class {
577
745
  const supportsSpec = params.supportsSpec ?? true;
578
746
  const { enableFrames, ...requestParams } = params;
579
747
  const body = {
748
+ sdk: SDK,
580
749
  ...requestParams,
581
750
  ...enableFrames ?? supportsSpec ? { supportsFrames: true } : {},
582
751
  supportsSpec,
@@ -638,8 +807,8 @@ async function sha256Hex(value) {
638
807
  try {
639
808
  const bytes = new TextEncoder().encode(value);
640
809
  const digest = await subtle.digest("SHA-256", bytes);
641
- const hex = Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
642
- return hex;
810
+ const hex2 = Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
811
+ return hex2;
643
812
  } catch {
644
813
  return void 0;
645
814
  }
@@ -669,8 +838,8 @@ async function hashPii(values) {
669
838
 
670
839
  // gravity-pixel.ts
671
840
  function uuid(prefix) {
672
- const hex = () => Math.random().toString(36).slice(2, 10);
673
- return prefix + hex() + hex();
841
+ const hex2 = () => Math.random().toString(36).slice(2, 10);
842
+ return prefix + hex2() + hex2();
674
843
  }
675
844
  function nowMs() {
676
845
  return Date.now();
package/dist/index.mjs CHANGED
@@ -1,14 +1,14 @@
1
1
  import {
2
2
  __commonJS,
3
3
  __require
4
- } from "./chunk-EBO3CZXG.mjs";
4
+ } from "./chunk-F4FGMBDK.mjs";
5
5
 
6
6
  // package.json
7
7
  var require_package = __commonJS({
8
8
  "package.json"(exports, module) {
9
9
  module.exports = {
10
10
  name: "@gravity-ai/api",
11
- version: "1.2.1",
11
+ version: "1.3.0",
12
12
  description: "Gravity JS SDK for retrieving targeted advertisements",
13
13
  main: "dist/index.js",
14
14
  module: "dist/index.mjs",
@@ -70,18 +70,168 @@ var require_package = __commonJS({
70
70
  }
71
71
  },
72
72
  dependencies: {
73
- axios: "^1.13.2"
73
+ axios: "^1.21.0"
74
74
  },
75
75
  devDependencies: {
76
- "@opentui/core": "^0.1.80",
77
- tsup: "^8.0.1",
76
+ "@opentui/core": "^0.8.0",
77
+ tsup: "^9.0.0",
78
78
  typescript: "^5.3.3",
79
- vitest: "^1.2.1"
79
+ vitest: "^4.1.12"
80
80
  }
81
81
  };
82
82
  }
83
83
  });
84
84
 
85
+ // sdk.ts
86
+ var pkg = (() => {
87
+ try {
88
+ return require_package();
89
+ } catch {
90
+ return { name: "@gravity-ai/api", version: "0.0.0" };
91
+ }
92
+ })();
93
+ var SDK = { name: pkg.name, version: pkg.version };
94
+
95
+ // ../ui/src/theme.ts
96
+ var GRAVITY_DARK_VARS = {
97
+ "--gravity-bg": "#1F1F23",
98
+ "--gravity-text": "#FAFAFA",
99
+ "--gravity-text-muted": "#A1A1AA",
100
+ "--gravity-border": "#3F3F46",
101
+ "--gravity-muted": "#27272A",
102
+ "--background": "240 6% 13%",
103
+ "--foreground": "0 0% 98%",
104
+ "--card": "240 6% 13%",
105
+ "--card-foreground": "0 0% 98%",
106
+ "--muted": "240 5% 16%",
107
+ "--muted-foreground": "240 5% 65%",
108
+ "--border": "240 5% 26%"
109
+ };
110
+ var GRAVITY_DARK_WIDGET_VARS = Object.fromEntries(
111
+ Object.entries(GRAVITY_DARK_VARS).filter(
112
+ ([k]) => k.startsWith("--gravity-")
113
+ )
114
+ );
115
+ function parseColor(value) {
116
+ const m = value.match(/rgba?\(([^)]+)\)/);
117
+ if (!m) return null;
118
+ const parts = m[1].split(",").map((p) => parseFloat(p.trim()));
119
+ if (parts.length < 3 || parts.some((n) => Number.isNaN(n))) return null;
120
+ return [parts[0], parts[1], parts[2], parts.length >= 4 ? parts[3] : 1];
121
+ }
122
+ function luminance(r, g, b) {
123
+ return (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
124
+ }
125
+ function effectiveBackground(el) {
126
+ let node = el;
127
+ while (node) {
128
+ if (!node.hasAttribute("data-gravity-ad")) {
129
+ const bg = getComputedStyle(node).backgroundColor;
130
+ const c = bg ? parseColor(bg) : null;
131
+ if (c && c[3] > 0.1) return [c[0], c[1], c[2]];
132
+ }
133
+ node = node.parentElement;
134
+ }
135
+ return null;
136
+ }
137
+ function hostIsDark(el) {
138
+ try {
139
+ const bg = effectiveBackground(el);
140
+ if (bg) return luminance(bg[0], bg[1], bg[2]) < 0.4;
141
+ const text = parseColor(getComputedStyle(el).color);
142
+ if (text) return luminance(text[0], text[1], text[2]) > 0.6;
143
+ return typeof matchMedia === "function" && matchMedia("(prefers-color-scheme: dark)").matches;
144
+ } catch {
145
+ return false;
146
+ }
147
+ }
148
+
149
+ // ../ui/src/units/collect.ts
150
+ var SAMPLE = "Find the right tool for your team and ship your next project faster. Try it free today.";
151
+ var SAMPLE_PX = 100;
152
+ var metricsCache = /* @__PURE__ */ new Map();
153
+ function hasDom() {
154
+ return typeof window !== "undefined" && typeof document !== "undefined";
155
+ }
156
+ function hostElement(el) {
157
+ if (el) return el;
158
+ return hasDom() ? document.body ?? document.documentElement : null;
159
+ }
160
+ function primaryFamily(stack) {
161
+ const first = stack.split(",")[0]?.trim().replace(/^["']|["']$/g, "");
162
+ return first && first.length <= 80 ? first : void 0;
163
+ }
164
+ function hex(value) {
165
+ const v = value.trim();
166
+ if (/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.test(v)) {
167
+ return (v.length === 4 ? "#" + [...v.slice(1)].map((c2) => c2 + c2).join("") : v).toUpperCase();
168
+ }
169
+ const c = parseColor(v);
170
+ if (!c || c[3] === 0) return void 0;
171
+ return "#" + c.slice(0, 3).map((n) => Math.round(Math.min(255, Math.max(0, n))).toString(16).padStart(2, "0")).join("").toUpperCase();
172
+ }
173
+ function px(value, rootPx) {
174
+ const m = /^(-?[\d.]+)(px|rem)$/.exec(value.trim());
175
+ if (!m) return void 0;
176
+ const n = parseFloat(m[1]) * (m[2] === "rem" ? rootPx : 1);
177
+ return Number.isFinite(n) && n >= 0 ? Math.round(n) : void 0;
178
+ }
179
+ function measureText(el) {
180
+ try {
181
+ const node = hostElement(el);
182
+ if (!node) return void 0;
183
+ const stack = getComputedStyle(node).fontFamily;
184
+ const fontFamily = stack ? primaryFamily(stack) : void 0;
185
+ if (!fontFamily) return void 0;
186
+ const cached = metricsCache.get(stack);
187
+ if (cached) return cached;
188
+ const ctx = document.createElement("canvas").getContext("2d");
189
+ if (!ctx) return { fontFamily };
190
+ const measure = (weight) => {
191
+ ctx.font = weight + " " + SAMPLE_PX + "px " + stack;
192
+ return Math.round(ctx.measureText(SAMPLE).width / (SAMPLE.length * SAMPLE_PX) * 1e3) / 1e3;
193
+ };
194
+ const regular = measure(400);
195
+ const bold = measure(700);
196
+ if (!(regular > 0) || !(bold > 0)) return { fontFamily };
197
+ const metrics = { fontFamily, avgCharEm: { regular, bold } };
198
+ const fonts = document.fonts;
199
+ if (typeof fonts?.check !== "function" || fonts.check(SAMPLE_PX + "px " + stack)) metricsCache.set(stack, metrics);
200
+ return metrics;
201
+ } catch {
202
+ return void 0;
203
+ }
204
+ }
205
+ function readHostTheme(el) {
206
+ try {
207
+ const node = hostElement(el);
208
+ if (!node) return void 0;
209
+ const cs = getComputedStyle(node);
210
+ const theme = { scheme: hostIsDark(node) ? "dark" : "light" };
211
+ const bg = effectiveBackground(node);
212
+ if (bg) theme.background = hex("rgb(" + bg.join(",") + ")");
213
+ const fg = hex(cs.color);
214
+ if (fg) theme.foreground = fg;
215
+ const accent = hex(cs.getPropertyValue("--gravity-accent"));
216
+ if (accent) theme.accent = accent;
217
+ const rootPx = parseFloat(getComputedStyle(document.documentElement).fontSize) || 16;
218
+ const radius = px(cs.getPropertyValue("--gravity-radius"), rootPx);
219
+ if (radius !== void 0) theme.radius = radius;
220
+ const family = cs.fontFamily ? primaryFamily(cs.fontFamily) : void 0;
221
+ if (family) theme.fontFamily = family;
222
+ return theme;
223
+ } catch {
224
+ return void 0;
225
+ }
226
+ }
227
+ function capabilitiesFor({ frames = false, promptAction = false, mcpConnect = false } = {}) {
228
+ const caps = ["units.v1", "image"];
229
+ if (frames) caps.push("frame.gfb1");
230
+ if (promptAction) caps.push("action.prompt");
231
+ if (mcpConnect) caps.push("connect.mcp");
232
+ return caps;
233
+ }
234
+
85
235
  // ads.ts
86
236
  var DEFAULT_GRAVITY_API = "https://server.trygravity.ai/api/v1/ad";
87
237
  var DEFAULT_TIMEOUT_MS = 4e3;
@@ -105,6 +255,23 @@ function extractClientIp(req) {
105
255
  if (req.ip) return req.ip;
106
256
  return void 0;
107
257
  }
258
+ function withUnitContext(placements, frames) {
259
+ if (!Array.isArray(placements)) return placements;
260
+ const text = measureText();
261
+ const theme = readHostTheme();
262
+ return placements.map(
263
+ (p) => p && typeof p === "object" ? {
264
+ ...text ? { text } : {},
265
+ ...theme ? { theme } : {},
266
+ capabilities: capabilitiesFor({
267
+ frames,
268
+ promptAction: p.supportsPromptAction === true,
269
+ mcpConnect: p.supportsMcpConnect === true
270
+ }),
271
+ ...p
272
+ } : p
273
+ );
274
+ }
108
275
  async function gravityAds(req, messages, placements, opts = {}) {
109
276
  const apiKey = opts.apiKey || (typeof process !== "undefined" ? process.env?.GRAVITY_API_KEY : void 0);
110
277
  const gravityApi = opts.gravityApi || DEFAULT_GRAVITY_API;
@@ -116,10 +283,13 @@ async function gravityAds(req, messages, placements, opts = {}) {
116
283
  const clientUser = ctx?.user || {};
117
284
  const clientDevice = ctx?.device || {};
118
285
  const clientIp = extractClientIp(req);
286
+ const supportsSpec = opts.supportsSpec ?? true;
287
+ const frames = opts.enableFrames ?? supportsSpec;
119
288
  const body = {
289
+ sdk: SDK,
120
290
  messages: toGravityMessages(messages),
121
291
  sessionId: ctx?.sessionId,
122
- placements,
292
+ placements: supportsSpec ? withUnitContext(placements, frames) : placements,
123
293
  user: {
124
294
  ...clientUser,
125
295
  id: clientUser.id || clientUser.userId || "anonymous"
@@ -135,12 +305,13 @@ async function gravityAds(req, messages, placements, opts = {}) {
135
305
  body.relevancy = opts.relevancy ?? 0.2;
136
306
  body.testAd = opts.production === true ? false : true;
137
307
  if (body.testAd && opts.alwaysReturn === true) body.alwaysReturn = true;
138
- const supportsSpec = opts.supportsSpec ?? true;
308
+ if (body.testAd && opts.testAdFormat === "action") body.testAdFormat = "action";
139
309
  body.supportsSpec = supportsSpec;
140
310
  if (supportsSpec) body.specCapabilities = opts.specCapabilities ?? "web1";
141
- if (opts.enableFrames ?? supportsSpec) body.supportsFrames = true;
311
+ if (frames) body.supportsFrames = true;
142
312
  if (body.testAd && opts.adLayout) body.adLayout = opts.adLayout;
143
313
  if (opts.excludedTopics) body.excludedTopics = opts.excludedTopics;
314
+ if (opts.usage) body.usage = opts.usage;
144
315
  const start = performance.now();
145
316
  try {
146
317
  const res = await fetch(gravityApi, {
@@ -402,7 +573,7 @@ function nodeDevice() {
402
573
  const rows = typeof process !== "undefined" ? process.stdout?.rows || 24 : 24;
403
574
  const env = typeof process !== "undefined" ? process.env : {};
404
575
  return {
405
- ua: `gravity-js/${PKG_VERSION} (${os?.type() || "unknown"} ${os?.arch() || "unknown"}; ${runtimeTag})`,
576
+ ua: `gravity-js/${SDK.version} (${os?.type() || "unknown"} ${os?.arch() || "unknown"}; ${runtimeTag})`,
406
577
  os: os ? `${os.type()} ${os.release()}` : void 0,
407
578
  browser: "cli",
408
579
  device_type: env.CI ? "server" : "desktop",
@@ -422,13 +593,6 @@ function nodeDevice() {
422
593
  is_ci: !!env.CI
423
594
  };
424
595
  }
425
- var PKG_VERSION = (() => {
426
- try {
427
- return require_package().version;
428
- } catch {
429
- return "0.0.0";
430
- }
431
- })();
432
596
 
433
597
  // client.ts
434
598
  import axios from "axios";
@@ -532,6 +696,7 @@ var Client = class {
532
696
  const supportsSpec = params.supportsSpec ?? true;
533
697
  const { enableFrames, ...requestParams } = params;
534
698
  const body = {
699
+ sdk: SDK,
535
700
  ...requestParams,
536
701
  ...enableFrames ?? supportsSpec ? { supportsFrames: true } : {},
537
702
  supportsSpec,
@@ -593,8 +758,8 @@ async function sha256Hex(value) {
593
758
  try {
594
759
  const bytes = new TextEncoder().encode(value);
595
760
  const digest = await subtle.digest("SHA-256", bytes);
596
- const hex = Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
597
- return hex;
761
+ const hex2 = Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
762
+ return hex2;
598
763
  } catch {
599
764
  return void 0;
600
765
  }
@@ -624,8 +789,8 @@ async function hashPii(values) {
624
789
 
625
790
  // gravity-pixel.ts
626
791
  function uuid(prefix) {
627
- const hex = () => Math.random().toString(36).slice(2, 10);
628
- return prefix + hex() + hex();
792
+ const hex2 = () => Math.random().toString(36).slice(2, 10);
793
+ return prefix + hex2() + hex2();
629
794
  }
630
795
  function nowMs() {
631
796
  return Date.now();
@@ -1,4 +1,4 @@
1
- import { d as Ad } from './types-CnuFH98L.mjs';
1
+ import { Ad } from './index.mjs';
2
2
 
3
3
  /**
4
4
  * @gravity-ai/api/opentui — Gravity ad rendering + tracking for OpenTUI terminals
@@ -180,4 +180,5 @@ interface GravityAdCard {
180
180
  */
181
181
  declare function createGravityAdCard(options: GravityAdCardOptions): GravityAdCard;
182
182
 
183
- export { type GravityAdCard, type GravityAdCardOptions, type GravityAdCardStyleProps, type GravityAdTracking, type GravityAdTrackingOptions, createGravityAdCard, gravityAdTracking };
183
+ export { createGravityAdCard, gravityAdTracking };
184
+ export type { GravityAdCard, GravityAdCardOptions, GravityAdCardStyleProps, GravityAdTracking, GravityAdTrackingOptions };