@trustrails/sdk 0.1.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 ADDED
@@ -0,0 +1,155 @@
1
+ # TrustRails TypeScript SDK
2
+
3
+ Official TypeScript/JavaScript client library for the TrustRails API.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install trustrails
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```typescript
14
+ import { TrustRailsClient } from 'trustrails';
15
+
16
+ // Initialize the client
17
+ const client = new TrustRailsClient(
18
+ 'https://api.trustrails.com',
19
+ 'your-api-key'
20
+ );
21
+
22
+ // Search for products
23
+ const results = await client.search({
24
+ query: 'USB-C charger',
25
+ maxPrice: 50
26
+ });
27
+
28
+ console.log(`Found ${results.total} products`);
29
+ results.products.forEach(product => {
30
+ console.log(`${product.title} - $${product.price}`);
31
+ });
32
+
33
+ // Get a specific product
34
+ const product = await client.getProduct('product-id');
35
+ console.log(product);
36
+ ```
37
+
38
+ ## API Reference
39
+
40
+ ### `TrustRailsClient`
41
+
42
+ #### Constructor
43
+
44
+ ```typescript
45
+ new TrustRailsClient(baseUrl: string, apiKey: string)
46
+ ```
47
+
48
+ Or use a config object:
49
+
50
+ ```typescript
51
+ new TrustRailsClient({ baseUrl: string, apiKey: string })
52
+ ```
53
+
54
+ **Parameters:**
55
+ - `baseUrl` - The base URL of the TrustRails API
56
+ - `apiKey` - Your TrustRails API key
57
+
58
+ #### Methods
59
+
60
+ ##### `search(options?: SearchOptions): Promise<SearchResponse>`
61
+
62
+ Search for products.
63
+
64
+ **Parameters:**
65
+ - `options.query?: string` - Search query string
66
+ - `options.maxPrice?: number` - Maximum price filter
67
+
68
+ **Returns:** Promise resolving to `SearchResponse` containing `products` array and `total` count.
69
+
70
+ **Example:**
71
+ ```typescript
72
+ const results = await client.search({
73
+ query: 'laptop',
74
+ maxPrice: 1000
75
+ });
76
+ ```
77
+
78
+ ##### `getProduct(id: string): Promise<Product>`
79
+
80
+ Get a specific product by ID.
81
+
82
+ **Parameters:**
83
+ - `id: string` - The product ID
84
+
85
+ **Returns:** Promise resolving to `Product` object.
86
+
87
+ **Example:**
88
+ ```typescript
89
+ const product = await client.getProduct('prod_123');
90
+ ```
91
+
92
+ ## Types
93
+
94
+ ### `Product`
95
+
96
+ ```typescript
97
+ interface Product {
98
+ id: string;
99
+ title: string;
100
+ brand?: string;
101
+ price: number;
102
+ currency: string;
103
+ availability: "in_stock" | "low_stock" | "out_of_stock";
104
+ stock: number;
105
+ delivery_time: string;
106
+ image_url?: string;
107
+ specs: {
108
+ [key: string]: any;
109
+ };
110
+ provenance: {
111
+ source: string;
112
+ last_updated: string;
113
+ };
114
+ purchase_url: string;
115
+ }
116
+ ```
117
+
118
+ ### `SearchOptions`
119
+
120
+ ```typescript
121
+ interface SearchOptions {
122
+ query?: string;
123
+ maxPrice?: number;
124
+ }
125
+ ```
126
+
127
+ ### `SearchResponse`
128
+
129
+ ```typescript
130
+ interface SearchResponse {
131
+ products: Product[];
132
+ total: number;
133
+ }
134
+ ```
135
+
136
+ ## Error Handling
137
+
138
+ The SDK throws `TrustRailsError` for API-related errors:
139
+
140
+ ```typescript
141
+ import { TrustRailsClient, TrustRailsError } from 'trustrails';
142
+
143
+ try {
144
+ const product = await client.getProduct('invalid-id');
145
+ } catch (error) {
146
+ if (error instanceof TrustRailsError) {
147
+ console.error(`API Error: ${error.message}`);
148
+ console.error(`Status Code: ${error.statusCode}`);
149
+ }
150
+ }
151
+ ```
152
+
153
+ ## License
154
+
155
+ MIT
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Product information returned by TrustRails API
3
+ */
4
+ interface Product {
5
+ id: string;
6
+ title: string;
7
+ brand?: string;
8
+ price: number;
9
+ currency: string;
10
+ availability: "in_stock" | "low_stock" | "out_of_stock";
11
+ stock: number;
12
+ delivery_time: string;
13
+ image_url?: string;
14
+ specs: {
15
+ wattage?: number;
16
+ ports?: number;
17
+ cable_length?: string;
18
+ pd_version?: string;
19
+ [key: string]: any;
20
+ };
21
+ provenance: {
22
+ source: string;
23
+ last_updated: string;
24
+ };
25
+ purchase_url: string;
26
+ }
27
+ /**
28
+ * Options for searching products
29
+ */
30
+ interface SearchOptions {
31
+ query?: string;
32
+ maxPrice?: number;
33
+ }
34
+ /**
35
+ * Response from product search endpoint
36
+ */
37
+ interface SearchResponse {
38
+ products: Product[];
39
+ total: number;
40
+ }
41
+ /**
42
+ * Configuration options for TrustRails client
43
+ */
44
+ interface TrustRailsConfig {
45
+ baseUrl: string;
46
+ apiKey: string;
47
+ }
48
+
49
+ /**
50
+ * TrustRails API Client
51
+ *
52
+ * @example
53
+ * ```typescript
54
+ * const client = new TrustRailsClient('https://api.trustrails.com', 'your-api-key');
55
+ * const results = await client.search({ query: 'laptop', maxPrice: 1000 });
56
+ * ```
57
+ */
58
+ declare class TrustRailsClient {
59
+ private readonly baseUrl;
60
+ private readonly apiKey;
61
+ /**
62
+ * Creates a new TrustRails API client
63
+ *
64
+ * @param baseUrl - The base URL of the TrustRails API
65
+ * @param apiKey - Your TrustRails API key
66
+ */
67
+ constructor(baseUrl: string, apiKey: string);
68
+ constructor(config: TrustRailsConfig);
69
+ /**
70
+ * Search for products
71
+ *
72
+ * @param options - Search parameters
73
+ * @returns Promise resolving to search results
74
+ *
75
+ * @example
76
+ * ```typescript
77
+ * const results = await client.search({
78
+ * query: 'USB-C charger',
79
+ * maxPrice: 50
80
+ * });
81
+ * ```
82
+ */
83
+ search(options?: SearchOptions): Promise<SearchResponse>;
84
+ /**
85
+ * Get a specific product by ID
86
+ *
87
+ * @param id - The product ID
88
+ * @returns Promise resolving to product details
89
+ *
90
+ * @example
91
+ * ```typescript
92
+ * const product = await client.getProduct('prod_123');
93
+ * ```
94
+ */
95
+ getProduct(id: string): Promise<Product>;
96
+ }
97
+
98
+ /**
99
+ * Custom error class for TrustRails API errors
100
+ */
101
+ declare class TrustRailsError extends Error {
102
+ statusCode?: number | undefined;
103
+ response?: any | undefined;
104
+ constructor(message: string, statusCode?: number | undefined, response?: any | undefined);
105
+ }
106
+
107
+ export { type Product, type SearchOptions, type SearchResponse, TrustRailsClient, type TrustRailsConfig, TrustRailsError };
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Product information returned by TrustRails API
3
+ */
4
+ interface Product {
5
+ id: string;
6
+ title: string;
7
+ brand?: string;
8
+ price: number;
9
+ currency: string;
10
+ availability: "in_stock" | "low_stock" | "out_of_stock";
11
+ stock: number;
12
+ delivery_time: string;
13
+ image_url?: string;
14
+ specs: {
15
+ wattage?: number;
16
+ ports?: number;
17
+ cable_length?: string;
18
+ pd_version?: string;
19
+ [key: string]: any;
20
+ };
21
+ provenance: {
22
+ source: string;
23
+ last_updated: string;
24
+ };
25
+ purchase_url: string;
26
+ }
27
+ /**
28
+ * Options for searching products
29
+ */
30
+ interface SearchOptions {
31
+ query?: string;
32
+ maxPrice?: number;
33
+ }
34
+ /**
35
+ * Response from product search endpoint
36
+ */
37
+ interface SearchResponse {
38
+ products: Product[];
39
+ total: number;
40
+ }
41
+ /**
42
+ * Configuration options for TrustRails client
43
+ */
44
+ interface TrustRailsConfig {
45
+ baseUrl: string;
46
+ apiKey: string;
47
+ }
48
+
49
+ /**
50
+ * TrustRails API Client
51
+ *
52
+ * @example
53
+ * ```typescript
54
+ * const client = new TrustRailsClient('https://api.trustrails.com', 'your-api-key');
55
+ * const results = await client.search({ query: 'laptop', maxPrice: 1000 });
56
+ * ```
57
+ */
58
+ declare class TrustRailsClient {
59
+ private readonly baseUrl;
60
+ private readonly apiKey;
61
+ /**
62
+ * Creates a new TrustRails API client
63
+ *
64
+ * @param baseUrl - The base URL of the TrustRails API
65
+ * @param apiKey - Your TrustRails API key
66
+ */
67
+ constructor(baseUrl: string, apiKey: string);
68
+ constructor(config: TrustRailsConfig);
69
+ /**
70
+ * Search for products
71
+ *
72
+ * @param options - Search parameters
73
+ * @returns Promise resolving to search results
74
+ *
75
+ * @example
76
+ * ```typescript
77
+ * const results = await client.search({
78
+ * query: 'USB-C charger',
79
+ * maxPrice: 50
80
+ * });
81
+ * ```
82
+ */
83
+ search(options?: SearchOptions): Promise<SearchResponse>;
84
+ /**
85
+ * Get a specific product by ID
86
+ *
87
+ * @param id - The product ID
88
+ * @returns Promise resolving to product details
89
+ *
90
+ * @example
91
+ * ```typescript
92
+ * const product = await client.getProduct('prod_123');
93
+ * ```
94
+ */
95
+ getProduct(id: string): Promise<Product>;
96
+ }
97
+
98
+ /**
99
+ * Custom error class for TrustRails API errors
100
+ */
101
+ declare class TrustRailsError extends Error {
102
+ statusCode?: number | undefined;
103
+ response?: any | undefined;
104
+ constructor(message: string, statusCode?: number | undefined, response?: any | undefined);
105
+ }
106
+
107
+ export { type Product, type SearchOptions, type SearchResponse, TrustRailsClient, type TrustRailsConfig, TrustRailsError };
package/dist/index.js ADDED
@@ -0,0 +1,131 @@
1
+ 'use strict';
2
+
3
+ // src/errors.ts
4
+ var TrustRailsError = class _TrustRailsError extends Error {
5
+ constructor(message, statusCode, response) {
6
+ super(message);
7
+ this.statusCode = statusCode;
8
+ this.response = response;
9
+ this.name = "TrustRailsError";
10
+ if (Error.captureStackTrace) {
11
+ Error.captureStackTrace(this, _TrustRailsError);
12
+ }
13
+ }
14
+ };
15
+
16
+ // src/client.ts
17
+ var TrustRailsClient = class {
18
+ constructor(baseUrlOrConfig, apiKey) {
19
+ if (typeof baseUrlOrConfig === "string") {
20
+ this.baseUrl = baseUrlOrConfig.endsWith("/") ? baseUrlOrConfig.slice(0, -1) : baseUrlOrConfig;
21
+ this.apiKey = apiKey;
22
+ } else {
23
+ this.baseUrl = baseUrlOrConfig.baseUrl.endsWith("/") ? baseUrlOrConfig.baseUrl.slice(0, -1) : baseUrlOrConfig.baseUrl;
24
+ this.apiKey = baseUrlOrConfig.apiKey;
25
+ }
26
+ if (!this.baseUrl) {
27
+ throw new Error("baseUrl is required");
28
+ }
29
+ if (!this.apiKey) {
30
+ throw new Error("apiKey is required");
31
+ }
32
+ }
33
+ /**
34
+ * Search for products
35
+ *
36
+ * @param options - Search parameters
37
+ * @returns Promise resolving to search results
38
+ *
39
+ * @example
40
+ * ```typescript
41
+ * const results = await client.search({
42
+ * query: 'USB-C charger',
43
+ * maxPrice: 50
44
+ * });
45
+ * ```
46
+ */
47
+ async search(options = {}) {
48
+ const url = new URL(`${this.baseUrl}/api/search`);
49
+ if (options.query) {
50
+ url.searchParams.set("query", options.query);
51
+ }
52
+ if (options.maxPrice) {
53
+ url.searchParams.set("max_price", options.maxPrice.toString());
54
+ }
55
+ try {
56
+ const response = await fetch(url.toString(), {
57
+ method: "GET",
58
+ headers: {
59
+ "Authorization": `Bearer ${this.apiKey}`,
60
+ "Content-Type": "application/json"
61
+ }
62
+ });
63
+ if (!response.ok) {
64
+ throw new TrustRailsError(
65
+ `Search failed: ${response.statusText}`,
66
+ response.status,
67
+ await response.text()
68
+ );
69
+ }
70
+ const data = await response.json();
71
+ return data;
72
+ } catch (error) {
73
+ if (error instanceof TrustRailsError) {
74
+ throw error;
75
+ }
76
+ throw new TrustRailsError(
77
+ `Network error: ${error instanceof Error ? error.message : "Unknown error"}`
78
+ );
79
+ }
80
+ }
81
+ /**
82
+ * Get a specific product by ID
83
+ *
84
+ * @param id - The product ID
85
+ * @returns Promise resolving to product details
86
+ *
87
+ * @example
88
+ * ```typescript
89
+ * const product = await client.getProduct('prod_123');
90
+ * ```
91
+ */
92
+ async getProduct(id) {
93
+ if (!id) {
94
+ throw new Error("Product ID is required");
95
+ }
96
+ const url = `${this.baseUrl}/api/products/${encodeURIComponent(id)}`;
97
+ try {
98
+ const response = await fetch(url, {
99
+ method: "GET",
100
+ headers: {
101
+ "Authorization": `Bearer ${this.apiKey}`,
102
+ "Content-Type": "application/json"
103
+ }
104
+ });
105
+ if (!response.ok) {
106
+ if (response.status === 404) {
107
+ throw new TrustRailsError(`Product not found: ${id}`, 404);
108
+ }
109
+ throw new TrustRailsError(
110
+ `Get product failed: ${response.statusText}`,
111
+ response.status,
112
+ await response.text()
113
+ );
114
+ }
115
+ const product = await response.json();
116
+ return product;
117
+ } catch (error) {
118
+ if (error instanceof TrustRailsError) {
119
+ throw error;
120
+ }
121
+ throw new TrustRailsError(
122
+ `Network error: ${error instanceof Error ? error.message : "Unknown error"}`
123
+ );
124
+ }
125
+ }
126
+ };
127
+
128
+ exports.TrustRailsClient = TrustRailsClient;
129
+ exports.TrustRailsError = TrustRailsError;
130
+ //# sourceMappingURL=index.js.map
131
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/client.ts"],"names":[],"mappings":";;;AAGO,IAAM,eAAA,GAAN,MAAM,gBAAA,SAAwB,KAAA,CAAM;AAAA,EACzC,WAAA,CACE,OAAA,EACO,UAAA,EACA,QAAA,EACP;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAHN,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AACA,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA;AAGP,IAAA,IAAA,CAAK,IAAA,GAAO,iBAAA;AAGZ,IAAA,IAAI,MAAM,iBAAA,EAAmB;AAC3B,MAAA,KAAA,CAAM,iBAAA,CAAkB,MAAM,gBAAe,CAAA;AAAA,IAC/C;AAAA,EACF;AACF;;;ACLO,IAAM,mBAAN,MAAuB;AAAA,EAY5B,WAAA,CAAY,iBAA4C,MAAA,EAAiB;AACvE,IAAA,IAAI,OAAO,oBAAoB,QAAA,EAAU;AACvC,MAAA,IAAA,CAAK,OAAA,GAAU,gBAAgB,QAAA,CAAS,GAAG,IACvC,eAAA,CAAgB,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA,GAC3B,eAAA;AACJ,MAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,IAChB,CAAA,MAAO;AACL,MAAA,IAAA,CAAK,OAAA,GAAU,eAAA,CAAgB,OAAA,CAAQ,QAAA,CAAS,GAAG,CAAA,GAC/C,eAAA,CAAgB,OAAA,CAAQ,KAAA,CAAM,CAAA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CAAA;AAAA,UAC1C,QAAA,CAAS,MAAA;AAAA,UACT,MAAM,SAAS,IAAA;AAAK,SACtB;AAAA,MACF;AAEA,MAAA,MAAM,OAAA,GAAU,MAAM,QAAA,CAAS,IAAA,EAAK;AACpC,MAAA,OAAO,OAAA;AAAA,IACT,SAAS,KAAA,EAAO;AACd,MAAA,IAAI,iBAAiB,eAAA,EAAiB;AACpC,QAAA,MAAM,KAAA;AAAA,MACR;AACA,MAAA,MAAM,IAAI,eAAA;AAAA,QACR,CAAA,eAAA,EAAkB,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,UAAU,eAAe,CAAA;AAAA,OAC5E;AAAA,IACF;AAAA,EACF;AACF","file":"index.js","sourcesContent":["/**\n * Custom error class for TrustRails API errors\n */\nexport class TrustRailsError extends Error {\n constructor(\n message: string,\n public statusCode?: number,\n public response?: any\n ) {\n super(message);\n this.name = 'TrustRailsError';\n\n // Maintains proper stack trace for where our error was thrown (only available on V8)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, TrustRailsError);\n }\n }\n}\n","import { TrustRailsError } from './errors';\nimport type { Product, SearchOptions, SearchResponse, TrustRailsConfig } from './types';\n\n/**\n * TrustRails API Client\n *\n * @example\n * ```typescript\n * const client = new TrustRailsClient('https://api.trustrails.com', 'your-api-key');\n * const results = await client.search({ query: 'laptop', maxPrice: 1000 });\n * ```\n */\nexport class TrustRailsClient {\n private readonly baseUrl: string;\n private readonly apiKey: string;\n\n /**\n * Creates a new TrustRails API client\n *\n * @param baseUrl - The base URL of the TrustRails API\n * @param apiKey - Your TrustRails API key\n */\n constructor(baseUrl: string, apiKey: string);\n constructor(config: TrustRailsConfig);\n constructor(baseUrlOrConfig: string | TrustRailsConfig, apiKey?: string) {\n if (typeof baseUrlOrConfig === 'string') {\n this.baseUrl = baseUrlOrConfig.endsWith('/')\n ? baseUrlOrConfig.slice(0, -1)\n : baseUrlOrConfig;\n this.apiKey = apiKey!;\n } else {\n this.baseUrl = baseUrlOrConfig.baseUrl.endsWith('/')\n ? baseUrlOrConfig.baseUrl.slice(0, -1)\n : baseUrlOrConfig.baseUrl;\n this.apiKey = baseUrlOrConfig.apiKey;\n }\n\n if (!this.baseUrl) {\n throw new Error('baseUrl is required');\n }\n if (!this.apiKey) {\n throw new Error('apiKey is required');\n }\n }\n\n /**\n * Search for products\n *\n * @param options - Search parameters\n * @returns Promise resolving to search results\n *\n * @example\n * ```typescript\n * const results = await client.search({\n * query: 'USB-C charger',\n * maxPrice: 50\n * });\n * ```\n */\n async search(options: SearchOptions = {}): Promise<SearchResponse> {\n const url = new URL(`${this.baseUrl}/api/search`);\n\n if (options.query) {\n url.searchParams.set('query', options.query);\n }\n\n if (options.maxPrice) {\n url.searchParams.set('max_price', options.maxPrice.toString());\n }\n\n try {\n const response = await fetch(url.toString(), {\n method: 'GET',\n headers: {\n 'Authorization': `Bearer ${this.apiKey}`,\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new TrustRailsError(\n `Search failed: ${response.statusText}`,\n response.status,\n await response.text()\n );\n }\n\n const data = await response.json() as SearchResponse;\n return data;\n } catch (error) {\n if (error instanceof TrustRailsError) {\n throw error;\n }\n throw new TrustRailsError(\n `Network error: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n }\n }\n\n /**\n * Get a specific product by ID\n *\n * @param id - The product ID\n * @returns Promise resolving to product details\n *\n * @example\n * ```typescript\n * const product = await client.getProduct('prod_123');\n * ```\n */\n async getProduct(id: string): Promise<Product> {\n if (!id) {\n throw new Error('Product ID is required');\n }\n\n const url = `${this.baseUrl}/api/products/${encodeURIComponent(id)}`;\n\n try {\n const response = await fetch(url, {\n method: 'GET',\n headers: {\n 'Authorization': `Bearer ${this.apiKey}`,\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n if (response.status === 404) {\n throw new TrustRailsError(`Product not found: ${id}`, 404);\n }\n throw new TrustRailsError(\n `Get product failed: ${response.statusText}`,\n response.status,\n await response.text()\n );\n }\n\n const product = await response.json() as Product;\n return product;\n } catch (error) {\n if (error instanceof TrustRailsError) {\n throw error;\n }\n throw new TrustRailsError(\n `Network error: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n }\n }\n}\n"]}
package/dist/index.mjs ADDED
@@ -0,0 +1,128 @@
1
+ // src/errors.ts
2
+ var TrustRailsError = class _TrustRailsError extends Error {
3
+ constructor(message, statusCode, response) {
4
+ super(message);
5
+ this.statusCode = statusCode;
6
+ this.response = response;
7
+ this.name = "TrustRailsError";
8
+ if (Error.captureStackTrace) {
9
+ Error.captureStackTrace(this, _TrustRailsError);
10
+ }
11
+ }
12
+ };
13
+
14
+ // src/client.ts
15
+ var TrustRailsClient = class {
16
+ constructor(baseUrlOrConfig, apiKey) {
17
+ if (typeof baseUrlOrConfig === "string") {
18
+ this.baseUrl = baseUrlOrConfig.endsWith("/") ? baseUrlOrConfig.slice(0, -1) : baseUrlOrConfig;
19
+ this.apiKey = apiKey;
20
+ } else {
21
+ this.baseUrl = baseUrlOrConfig.baseUrl.endsWith("/") ? baseUrlOrConfig.baseUrl.slice(0, -1) : baseUrlOrConfig.baseUrl;
22
+ this.apiKey = baseUrlOrConfig.apiKey;
23
+ }
24
+ if (!this.baseUrl) {
25
+ throw new Error("baseUrl is required");
26
+ }
27
+ if (!this.apiKey) {
28
+ throw new Error("apiKey is required");
29
+ }
30
+ }
31
+ /**
32
+ * Search for products
33
+ *
34
+ * @param options - Search parameters
35
+ * @returns Promise resolving to search results
36
+ *
37
+ * @example
38
+ * ```typescript
39
+ * const results = await client.search({
40
+ * query: 'USB-C charger',
41
+ * maxPrice: 50
42
+ * });
43
+ * ```
44
+ */
45
+ async search(options = {}) {
46
+ const url = new URL(`${this.baseUrl}/api/search`);
47
+ if (options.query) {
48
+ url.searchParams.set("query", options.query);
49
+ }
50
+ if (options.maxPrice) {
51
+ url.searchParams.set("max_price", options.maxPrice.toString());
52
+ }
53
+ try {
54
+ const response = await fetch(url.toString(), {
55
+ method: "GET",
56
+ headers: {
57
+ "Authorization": `Bearer ${this.apiKey}`,
58
+ "Content-Type": "application/json"
59
+ }
60
+ });
61
+ if (!response.ok) {
62
+ throw new TrustRailsError(
63
+ `Search failed: ${response.statusText}`,
64
+ response.status,
65
+ await response.text()
66
+ );
67
+ }
68
+ const data = await response.json();
69
+ return data;
70
+ } catch (error) {
71
+ if (error instanceof TrustRailsError) {
72
+ throw error;
73
+ }
74
+ throw new TrustRailsError(
75
+ `Network error: ${error instanceof Error ? error.message : "Unknown error"}`
76
+ );
77
+ }
78
+ }
79
+ /**
80
+ * Get a specific product by ID
81
+ *
82
+ * @param id - The product ID
83
+ * @returns Promise resolving to product details
84
+ *
85
+ * @example
86
+ * ```typescript
87
+ * const product = await client.getProduct('prod_123');
88
+ * ```
89
+ */
90
+ async getProduct(id) {
91
+ if (!id) {
92
+ throw new Error("Product ID is required");
93
+ }
94
+ const url = `${this.baseUrl}/api/products/${encodeURIComponent(id)}`;
95
+ try {
96
+ const response = await fetch(url, {
97
+ method: "GET",
98
+ headers: {
99
+ "Authorization": `Bearer ${this.apiKey}`,
100
+ "Content-Type": "application/json"
101
+ }
102
+ });
103
+ if (!response.ok) {
104
+ if (response.status === 404) {
105
+ throw new TrustRailsError(`Product not found: ${id}`, 404);
106
+ }
107
+ throw new TrustRailsError(
108
+ `Get product failed: ${response.statusText}`,
109
+ response.status,
110
+ await response.text()
111
+ );
112
+ }
113
+ const product = await response.json();
114
+ return product;
115
+ } catch (error) {
116
+ if (error instanceof TrustRailsError) {
117
+ throw error;
118
+ }
119
+ throw new TrustRailsError(
120
+ `Network error: ${error instanceof Error ? error.message : "Unknown error"}`
121
+ );
122
+ }
123
+ }
124
+ };
125
+
126
+ export { TrustRailsClient, TrustRailsError };
127
+ //# sourceMappingURL=index.mjs.map
128
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/client.ts"],"names":[],"mappings":";AAGO,IAAM,eAAA,GAAN,MAAM,gBA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ACF;AAAA,EACF;AACF","file":"index.mjs","sourcesContent":["/**\n * Custom error class for TrustRails API errors\n */\nexport class TrustRailsError extends Error {\n constructor(\n message: string,\n public statusCode?: number,\n public response?: any\n ) {\n super(message);\n this.name = 'TrustRailsError';\n\n // Maintains proper stack trace for where our error was thrown (only available on V8)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, TrustRailsError);\n }\n }\n}\n","import { TrustRailsError } from './errors';\nimport type { Product, SearchOptions, SearchResponse, TrustRailsConfig } from './types';\n\n/**\n * TrustRails API Client\n *\n * @example\n * ```typescript\n * const client = new TrustRailsClient('https://api.trustrails.com', 'your-api-key');\n * const results = await client.search({ query: 'laptop', maxPrice: 1000 });\n * ```\n */\nexport class TrustRailsClient {\n private readonly baseUrl: string;\n private readonly apiKey: string;\n\n /**\n * Creates a new TrustRails API client\n *\n * @param baseUrl - The base URL of the TrustRails API\n * @param apiKey - Your TrustRails API key\n */\n constructor(baseUrl: string, apiKey: string);\n constructor(config: TrustRailsConfig);\n constructor(baseUrlOrConfig: string | TrustRailsConfig, apiKey?: string) {\n if (typeof baseUrlOrConfig === 'string') {\n this.baseUrl = baseUrlOrConfig.endsWith('/')\n ? baseUrlOrConfig.slice(0, -1)\n : baseUrlOrConfig;\n this.apiKey = apiKey!;\n } else {\n this.baseUrl = baseUrlOrConfig.baseUrl.endsWith('/')\n ? baseUrlOrConfig.baseUrl.slice(0, -1)\n : baseUrlOrConfig.baseUrl;\n this.apiKey = baseUrlOrConfig.apiKey;\n }\n\n if (!this.baseUrl) {\n throw new Error('baseUrl is required');\n }\n if (!this.apiKey) {\n throw new Error('apiKey is required');\n }\n }\n\n /**\n * Search for products\n *\n * @param options - Search parameters\n * @returns Promise resolving to search results\n *\n * @example\n * ```typescript\n * const results = await client.search({\n * query: 'USB-C charger',\n * maxPrice: 50\n * });\n * ```\n */\n async search(options: SearchOptions = {}): Promise<SearchResponse> {\n const url = new URL(`${this.baseUrl}/api/search`);\n\n if (options.query) {\n url.searchParams.set('query', options.query);\n }\n\n if (options.maxPrice) {\n url.searchParams.set('max_price', options.maxPrice.toString());\n }\n\n try {\n const response = await fetch(url.toString(), {\n method: 'GET',\n headers: {\n 'Authorization': `Bearer ${this.apiKey}`,\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new TrustRailsError(\n `Search failed: ${response.statusText}`,\n response.status,\n await response.text()\n );\n }\n\n const data = await response.json() as SearchResponse;\n return data;\n } catch (error) {\n if (error instanceof TrustRailsError) {\n throw error;\n }\n throw new TrustRailsError(\n `Network error: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n }\n }\n\n /**\n * Get a specific product by ID\n *\n * @param id - The product ID\n * @returns Promise resolving to product details\n *\n * @example\n * ```typescript\n * const product = await client.getProduct('prod_123');\n * ```\n */\n async getProduct(id: string): Promise<Product> {\n if (!id) {\n throw new Error('Product ID is required');\n }\n\n const url = `${this.baseUrl}/api/products/${encodeURIComponent(id)}`;\n\n try {\n const response = await fetch(url, {\n method: 'GET',\n headers: {\n 'Authorization': `Bearer ${this.apiKey}`,\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n if (response.status === 404) {\n throw new TrustRailsError(`Product not found: ${id}`, 404);\n }\n throw new TrustRailsError(\n `Get product failed: ${response.statusText}`,\n response.status,\n await response.text()\n );\n }\n\n const product = await response.json() as Product;\n return product;\n } catch (error) {\n if (error instanceof TrustRailsError) {\n throw error;\n }\n throw new TrustRailsError(\n `Network error: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n }\n }\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "@trustrails/sdk",
3
+ "version": "0.1.0",
4
+ "description": "Official TypeScript SDK for TrustRails API",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.mjs",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.mjs",
12
+ "require": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "scripts": {
19
+ "build": "tsup",
20
+ "dev": "tsup --watch",
21
+ "test": "jest",
22
+ "test:watch": "jest --watch",
23
+ "prepublishOnly": "npm run build"
24
+ },
25
+ "keywords": [
26
+ "trustrails",
27
+ "api",
28
+ "sdk",
29
+ "typescript",
30
+ "ecommerce",
31
+ "product-verification"
32
+ ],
33
+ "author": "James Roe",
34
+ "license": "MIT",
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/james-webdev/trustrails.git",
38
+ "directory": "packages/trustrails"
39
+ },
40
+ "homepage": "https://github.com/james-webdev/trustrails#readme",
41
+ "bugs": {
42
+ "url": "https://github.com/james-webdev/trustrails/issues"
43
+ },
44
+ "devDependencies": {
45
+ "@types/jest": "^29.5.0",
46
+ "jest": "^29.7.0",
47
+ "ts-jest": "^29.2.0",
48
+ "tsup": "^8.0.0",
49
+ "typescript": "^5.0.0"
50
+ },
51
+ "engines": {
52
+ "node": ">=18.0.0"
53
+ }
54
+ }