@gravity-ai/api 0.0.1

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 ADDED
@@ -0,0 +1,70 @@
1
+ # @gravity-ai/api
2
+
3
+ The official Node.js/TypeScript SDK for the Gravity API.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @gravity-ai/api
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ First, import and initialize the client with your API key.
14
+
15
+ ```typescript
16
+ import { Client } from '@gravity-ai/api';
17
+
18
+ const client = new Client('YOUR_API_KEY');
19
+ ```
20
+
21
+ ### Fetching an Ad
22
+
23
+ To request an ad, you need to pass the conversation context (messages). You can also provide optional user or device information to improve targeting.
24
+
25
+ ```typescript
26
+ const ad = await client.getAd({
27
+ messages: [
28
+ { role: 'user', content: 'I need help finding a new laptop.' },
29
+ { role: 'assistant', content: 'What is your budget?' }
30
+ ],
31
+ // User context
32
+ user: {
33
+ gender: 'male',
34
+ age: '25-34'
35
+ },
36
+ // Device info
37
+ device: {
38
+ ip: '1.2.3.4',
39
+ country: 'US',
40
+ ua: 'UA'
41
+ },
42
+ // Optional additional context
43
+ interests: ["coding", "apple", "software development"],
44
+ summary: "User is building software on his windows laptop but wants an apple laptop"
45
+ });
46
+
47
+ if (ad) {
48
+ console.log('Ad Text:', ad.adText);
49
+ console.log('Impression URL:', ad.impUrl);
50
+ console.log("Click URL:", ad.clickUrl);
51
+ console.log("Payout", ad.payout)
52
+ } else {
53
+ console.log('No ad available for this context.');
54
+ }
55
+ ```
56
+
57
+ ### Advanced Configuration
58
+
59
+ You can override the default API endpoint or provide global excluded topics during initialization.
60
+
61
+ ```typescript
62
+ const client = new Client('YOUR_API_KEY', {
63
+ endpoint: 'https://custom.gravity.server',
64
+ excludedTopics: ['politics', 'religion']
65
+ });
66
+ ```
67
+
68
+ ## License
69
+
70
+ MIT
@@ -0,0 +1,70 @@
1
+ type Role = 'user' | 'assistant';
2
+ type Gender = 'male' | 'female' | 'other';
3
+ interface MessageObject {
4
+ role: Role;
5
+ content: string;
6
+ }
7
+ interface DeviceObject {
8
+ ip: string;
9
+ country: string;
10
+ ua: string;
11
+ os?: string;
12
+ ifa?: string;
13
+ }
14
+ interface UserObject {
15
+ uid?: string;
16
+ gender?: Gender;
17
+ age?: string;
18
+ keywords?: string;
19
+ }
20
+ interface AdParams {
21
+ apiKey?: string;
22
+ messages: MessageObject[];
23
+ device?: DeviceObject;
24
+ user?: UserObject;
25
+ excludedTopics?: string[];
26
+ [key: string]: any;
27
+ }
28
+ interface AdResponse {
29
+ adText: string;
30
+ impUrl?: string;
31
+ clickUrl?: string;
32
+ payout?: number;
33
+ }
34
+ /**
35
+ * API error response structure
36
+ */
37
+ interface ApiErrorResponse {
38
+ error: string;
39
+ message?: string;
40
+ statusCode?: number;
41
+ }
42
+
43
+ interface ClientParams {
44
+ endpoint?: string;
45
+ excludedTopics?: string[];
46
+ }
47
+ /**
48
+ * Client for the Gravity API
49
+ */
50
+ declare class Client {
51
+ private apiKey;
52
+ private endpoint?;
53
+ private excludedTopics?;
54
+ private axios;
55
+ constructor(apiKey: string, params?: ClientParams);
56
+ /**
57
+ * Request a text advertisement. Returns null if there is no relevant ad found.
58
+ * @param params - AdParams matching the server schema
59
+ * @returns Promise<BidResponse | null>
60
+ */
61
+ getAd(params: AdParams): Promise<AdResponse | null>;
62
+ /**
63
+ * Handle API errors with logging
64
+ * @param error - The error object
65
+ * @param method - The method name where error occurred
66
+ */
67
+ private handleError;
68
+ }
69
+
70
+ export { type AdParams, type AdResponse, type ApiErrorResponse, Client, type ClientParams };
@@ -0,0 +1,70 @@
1
+ type Role = 'user' | 'assistant';
2
+ type Gender = 'male' | 'female' | 'other';
3
+ interface MessageObject {
4
+ role: Role;
5
+ content: string;
6
+ }
7
+ interface DeviceObject {
8
+ ip: string;
9
+ country: string;
10
+ ua: string;
11
+ os?: string;
12
+ ifa?: string;
13
+ }
14
+ interface UserObject {
15
+ uid?: string;
16
+ gender?: Gender;
17
+ age?: string;
18
+ keywords?: string;
19
+ }
20
+ interface AdParams {
21
+ apiKey?: string;
22
+ messages: MessageObject[];
23
+ device?: DeviceObject;
24
+ user?: UserObject;
25
+ excludedTopics?: string[];
26
+ [key: string]: any;
27
+ }
28
+ interface AdResponse {
29
+ adText: string;
30
+ impUrl?: string;
31
+ clickUrl?: string;
32
+ payout?: number;
33
+ }
34
+ /**
35
+ * API error response structure
36
+ */
37
+ interface ApiErrorResponse {
38
+ error: string;
39
+ message?: string;
40
+ statusCode?: number;
41
+ }
42
+
43
+ interface ClientParams {
44
+ endpoint?: string;
45
+ excludedTopics?: string[];
46
+ }
47
+ /**
48
+ * Client for the Gravity API
49
+ */
50
+ declare class Client {
51
+ private apiKey;
52
+ private endpoint?;
53
+ private excludedTopics?;
54
+ private axios;
55
+ constructor(apiKey: string, params?: ClientParams);
56
+ /**
57
+ * Request a text advertisement. Returns null if there is no relevant ad found.
58
+ * @param params - AdParams matching the server schema
59
+ * @returns Promise<BidResponse | null>
60
+ */
61
+ getAd(params: AdParams): Promise<AdResponse | null>;
62
+ /**
63
+ * Handle API errors with logging
64
+ * @param error - The error object
65
+ * @param method - The method name where error occurred
66
+ */
67
+ private handleError;
68
+ }
69
+
70
+ export { type AdParams, type AdResponse, type ApiErrorResponse, Client, type ClientParams };
package/dist/index.js ADDED
@@ -0,0 +1,114 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ Client: () => Client
34
+ });
35
+ module.exports = __toCommonJS(index_exports);
36
+
37
+ // client.ts
38
+ var import_axios = __toESM(require("axios"));
39
+ var Client = class {
40
+ constructor(apiKey, params = {}) {
41
+ this.apiKey = apiKey;
42
+ this.endpoint = params.endpoint || "https://server.trygravity.ai";
43
+ this.excludedTopics = params.excludedTopics || [];
44
+ this.axios = import_axios.default.create({
45
+ baseURL: this.endpoint,
46
+ timeout: 1e4,
47
+ headers: {
48
+ "Authorization": `Bearer ${this.apiKey}`,
49
+ "Content-Type": "application/json"
50
+ }
51
+ });
52
+ }
53
+ /**
54
+ * Request a text advertisement. Returns null if there is no relevant ad found.
55
+ * @param params - AdParams matching the server schema
56
+ * @returns Promise<BidResponse | null>
57
+ */
58
+ async getAd(params) {
59
+ try {
60
+ const body = {
61
+ ...params,
62
+ // prefer explicit apiKey in params, else default to client's apiKey
63
+ apiKey: params.apiKey ?? this.apiKey,
64
+ // supply top-level excludedTopics if not provided
65
+ excludedTopics: params.excludedTopics ?? this.excludedTopics
66
+ };
67
+ const response = await this.axios.post("/ad", body);
68
+ if (response.status === 204) return null;
69
+ if (response.data && response.data.adText) {
70
+ const payload = response.data;
71
+ return {
72
+ adText: payload.adText,
73
+ impUrl: payload.impUrl,
74
+ clickUrl: payload.clickUrl,
75
+ payout: payload.payout
76
+ };
77
+ }
78
+ } catch (error) {
79
+ this.handleError(error, "getAd");
80
+ return null;
81
+ }
82
+ return null;
83
+ }
84
+ /**
85
+ * Handle API errors with logging
86
+ * @param error - The error object
87
+ * @param method - The method name where error occurred
88
+ */
89
+ handleError(error, method) {
90
+ if (import_axios.default.isAxiosError(error)) {
91
+ const axiosError = error;
92
+ if (axiosError.response) {
93
+ console.error(`[GravityClient.${method}] API Error:`, {
94
+ status: axiosError.response.status,
95
+ statusText: axiosError.response.statusText,
96
+ data: axiosError.response.data
97
+ });
98
+ } else if (axiosError.request) {
99
+ console.error(`[GravityClient.${method}] Network Error:`, {
100
+ message: "No response received from server",
101
+ code: axiosError.code
102
+ });
103
+ } else {
104
+ console.error(`[GravityClient.${method}] Request Error:`, axiosError.message);
105
+ }
106
+ } else {
107
+ console.error(`[GravityClient.${method}] Unexpected Error:`, error);
108
+ }
109
+ }
110
+ };
111
+ // Annotate the CommonJS export names for ESM import in node:
112
+ 0 && (module.exports = {
113
+ Client
114
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,77 @@
1
+ // client.ts
2
+ import axios from "axios";
3
+ var Client = class {
4
+ constructor(apiKey, params = {}) {
5
+ this.apiKey = apiKey;
6
+ this.endpoint = params.endpoint || "https://server.trygravity.ai";
7
+ this.excludedTopics = params.excludedTopics || [];
8
+ this.axios = axios.create({
9
+ baseURL: this.endpoint,
10
+ timeout: 1e4,
11
+ headers: {
12
+ "Authorization": `Bearer ${this.apiKey}`,
13
+ "Content-Type": "application/json"
14
+ }
15
+ });
16
+ }
17
+ /**
18
+ * Request a text advertisement. Returns null if there is no relevant ad found.
19
+ * @param params - AdParams matching the server schema
20
+ * @returns Promise<BidResponse | null>
21
+ */
22
+ async getAd(params) {
23
+ try {
24
+ const body = {
25
+ ...params,
26
+ // prefer explicit apiKey in params, else default to client's apiKey
27
+ apiKey: params.apiKey ?? this.apiKey,
28
+ // supply top-level excludedTopics if not provided
29
+ excludedTopics: params.excludedTopics ?? this.excludedTopics
30
+ };
31
+ const response = await this.axios.post("/ad", body);
32
+ if (response.status === 204) return null;
33
+ if (response.data && response.data.adText) {
34
+ const payload = response.data;
35
+ return {
36
+ adText: payload.adText,
37
+ impUrl: payload.impUrl,
38
+ clickUrl: payload.clickUrl,
39
+ payout: payload.payout
40
+ };
41
+ }
42
+ } catch (error) {
43
+ this.handleError(error, "getAd");
44
+ return null;
45
+ }
46
+ return null;
47
+ }
48
+ /**
49
+ * Handle API errors with logging
50
+ * @param error - The error object
51
+ * @param method - The method name where error occurred
52
+ */
53
+ handleError(error, method) {
54
+ if (axios.isAxiosError(error)) {
55
+ const axiosError = error;
56
+ if (axiosError.response) {
57
+ console.error(`[GravityClient.${method}] API Error:`, {
58
+ status: axiosError.response.status,
59
+ statusText: axiosError.response.statusText,
60
+ data: axiosError.response.data
61
+ });
62
+ } else if (axiosError.request) {
63
+ console.error(`[GravityClient.${method}] Network Error:`, {
64
+ message: "No response received from server",
65
+ code: axiosError.code
66
+ });
67
+ } else {
68
+ console.error(`[GravityClient.${method}] Request Error:`, axiosError.message);
69
+ }
70
+ } else {
71
+ console.error(`[GravityClient.${method}] Unexpected Error:`, error);
72
+ }
73
+ }
74
+ };
75
+ export {
76
+ Client
77
+ };
package/package.json ADDED
@@ -0,0 +1,67 @@
1
+ {
2
+ "name": "@gravity-ai/api",
3
+ "version": "0.0.1",
4
+ "description": "Gravity JS SDK for retrieving targeted advertisements",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.mjs",
7
+ "types": "dist/index.d.ts",
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "require": "./dist/index.js",
15
+ "import": "./dist/index.mjs"
16
+ }
17
+ },
18
+ "scripts": {
19
+ "build": "tsup index.ts --format cjs,esm --dts",
20
+ "clean": "rm -rf dist",
21
+ "dev": "tsup index.ts --format cjs,esm --watch --dts",
22
+ "lint": "tsc --noEmit",
23
+ "test": "vitest run",
24
+ "prepublishOnly": "npm run clean && npm run build",
25
+ "version:patch": "npm version patch",
26
+ "version:minor": "npm version minor",
27
+ "version:major": "npm version major",
28
+ "publish:patch": "npm run version:patch && npm publish",
29
+ "publish:minor": "npm run version:minor && npm publish",
30
+ "publish:major": "npm run version:major && npm publish"
31
+ },
32
+ "keywords": [
33
+ "gravity",
34
+ "advertising",
35
+ "api",
36
+ "client",
37
+ "ads",
38
+ "typescript",
39
+ "contextual-advertising",
40
+ "ai-ads"
41
+ ],
42
+ "author": "Gravity Team",
43
+ "license": "MIT",
44
+ "homepage": "https://github.com/Try-Gravity/gravity-js#readme",
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "git+https://github.com/Try-Gravity/gravity-js.git",
48
+ "directory": "packages/api"
49
+ },
50
+ "bugs": {
51
+ "url": "https://github.com/Try-Gravity/gravity-js/issues"
52
+ },
53
+ "publishConfig": {
54
+ "access": "public"
55
+ },
56
+ "engines": {
57
+ "node": ">=18.0.0"
58
+ },
59
+ "dependencies": {
60
+ "axios": "^1.13.2"
61
+ },
62
+ "devDependencies": {
63
+ "tsup": "^8.0.1",
64
+ "typescript": "^5.3.3",
65
+ "vitest": "^1.2.1"
66
+ }
67
+ }