@yassirbenmoussa/aicommerce-sdk 1.0.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 +163 -0
- package/dist/ai-commerce.min.js +4 -0
- package/dist/index.cjs +203 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.mts +224 -0
- package/dist/index.d.ts +224 -0
- package/dist/index.min.js.map +1 -0
- package/dist/index.mjs +201 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +50 -0
package/README.md
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
# AI Commerce SDK
|
|
2
|
+
|
|
3
|
+
AI-powered product recommendations for e-commerce. This SDK allows you to easily integrate AI Commerce into your website or application.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
### npm / yarn / pnpm
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @ai-commerce/sdk
|
|
11
|
+
# or
|
|
12
|
+
yarn add @ai-commerce/sdk
|
|
13
|
+
# or
|
|
14
|
+
pnpm add @ai-commerce/sdk
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
### Script Tag (CDN)
|
|
18
|
+
|
|
19
|
+
```html
|
|
20
|
+
<script src="https://cdn.aicommerce.dev/sdk/ai-commerce.min.js"></script>
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Quick Start
|
|
24
|
+
|
|
25
|
+
### ES Modules / TypeScript
|
|
26
|
+
|
|
27
|
+
```typescript
|
|
28
|
+
import { AICommerce } from '@ai-commerce/sdk';
|
|
29
|
+
|
|
30
|
+
// Initialize the client
|
|
31
|
+
const client = new AICommerce({
|
|
32
|
+
apiKey: 'your-api-key',
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
// Send a message and get product recommendations
|
|
36
|
+
const response = await client.chat('I need a laptop under $1000');
|
|
37
|
+
|
|
38
|
+
console.log(response.reply); // AI response text
|
|
39
|
+
console.log(response.products); // Recommended products
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
### CommonJS
|
|
43
|
+
|
|
44
|
+
```javascript
|
|
45
|
+
const { AICommerce } = require('@ai-commerce/sdk');
|
|
46
|
+
|
|
47
|
+
const client = new AICommerce({
|
|
48
|
+
apiKey: 'your-api-key',
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
client.chat('I need a laptop').then(response => {
|
|
52
|
+
console.log(response.products);
|
|
53
|
+
});
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
### Script Tag
|
|
57
|
+
|
|
58
|
+
```html
|
|
59
|
+
<script src="https://cdn.aicommerce.dev/sdk/ai-commerce.min.js"></script>
|
|
60
|
+
<script>
|
|
61
|
+
const client = new AICommerceSDK.AICommerce({
|
|
62
|
+
apiKey: 'your-api-key'
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
client.chat('I need a laptop').then(response => {
|
|
66
|
+
console.log(response.products);
|
|
67
|
+
});
|
|
68
|
+
</script>
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## API Reference
|
|
72
|
+
|
|
73
|
+
### `new AICommerce(config)`
|
|
74
|
+
|
|
75
|
+
Create a new AI Commerce client.
|
|
76
|
+
|
|
77
|
+
| Option | Type | Required | Description |
|
|
78
|
+
|--------|------|----------|-------------|
|
|
79
|
+
| `apiKey` | `string` | Yes | Your API key from the dashboard |
|
|
80
|
+
| `baseUrl` | `string` | No | API base URL (defaults to auto-detect) |
|
|
81
|
+
| `timeout` | `number` | No | Request timeout in ms (default: 30000) |
|
|
82
|
+
|
|
83
|
+
### `client.chat(message, context?)`
|
|
84
|
+
|
|
85
|
+
Send a message and get product recommendations.
|
|
86
|
+
|
|
87
|
+
```typescript
|
|
88
|
+
const response = await client.chat('I need running shoes', {
|
|
89
|
+
budget: { max: 150, currency: 'USD' },
|
|
90
|
+
preferences: ['comfortable', 'lightweight']
|
|
91
|
+
});
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
**Returns:**
|
|
95
|
+
|
|
96
|
+
```typescript
|
|
97
|
+
{
|
|
98
|
+
reply: string; // AI response text
|
|
99
|
+
products: Product[]; // Recommended products
|
|
100
|
+
sessionToken: string; // For follow-up messages
|
|
101
|
+
suggestions?: string[]; // Suggested follow-up questions
|
|
102
|
+
confidence?: number; // AI confidence score (0-1)
|
|
103
|
+
}
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### `client.createSession()`
|
|
107
|
+
|
|
108
|
+
Create a new chat session explicitly.
|
|
109
|
+
|
|
110
|
+
```typescript
|
|
111
|
+
const session = await client.createSession();
|
|
112
|
+
console.log(session.token);
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### `client.clearSession()`
|
|
116
|
+
|
|
117
|
+
Clear the current session token.
|
|
118
|
+
|
|
119
|
+
### `AICommerce.quickChat(options)`
|
|
120
|
+
|
|
121
|
+
Static method for one-off requests without creating a client instance.
|
|
122
|
+
|
|
123
|
+
```typescript
|
|
124
|
+
const response = await AICommerce.quickChat({
|
|
125
|
+
apiKey: 'your-api-key',
|
|
126
|
+
message: 'I need a laptop',
|
|
127
|
+
context: { budget: { max: 1000 } }
|
|
128
|
+
});
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
## TypeScript Support
|
|
132
|
+
|
|
133
|
+
Full TypeScript support with exported types:
|
|
134
|
+
|
|
135
|
+
```typescript
|
|
136
|
+
import type {
|
|
137
|
+
AICommerceConfig,
|
|
138
|
+
ChatRequest,
|
|
139
|
+
ChatResponse,
|
|
140
|
+
Product,
|
|
141
|
+
ChatContext
|
|
142
|
+
} from '@ai-commerce/sdk';
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
## Error Handling
|
|
146
|
+
|
|
147
|
+
```typescript
|
|
148
|
+
import { AICommerce, AICommerceError } from '@ai-commerce/sdk';
|
|
149
|
+
|
|
150
|
+
try {
|
|
151
|
+
const response = await client.chat('Hello');
|
|
152
|
+
} catch (error) {
|
|
153
|
+
if (error instanceof AICommerceError) {
|
|
154
|
+
console.log(error.code); // Error code (e.g., 'UNAUTHORIZED')
|
|
155
|
+
console.log(error.status); // HTTP status code
|
|
156
|
+
console.log(error.message); // Error message
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
## License
|
|
162
|
+
|
|
163
|
+
MIT
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
var AICommerceSDK=(function(exports){'use strict';/*! AI Commerce SDK v1.0.0 | MIT License | https://aicommerce.dev */
|
|
2
|
+
var m=Object.defineProperty;var y=Object.getOwnPropertyDescriptor;var C=Object.getOwnPropertyNames;var T=Object.prototype.hasOwnProperty;var w=(s,e)=>()=>(s&&(e=s(s=0)),e);var g=(s,e)=>{for(var t in e)m(s,t,{get:e[t],enumerable:true});},f=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of C(e))!T.call(s,r)&&r!==t&&m(s,r,{get:()=>e[r],enumerable:!(n=y(e,r))||n.enumerable});return s};var d=s=>f(m({},"__esModule",{value:true}),s);var p={};g(p,{AICommerce:()=>exports.AICommerce,AICommerceError:()=>exports.AICommerceError});exports.AICommerce=void 0;exports.AICommerceError=void 0;var c=w(()=>{exports.AICommerce=class s{constructor(e){this.sessionToken=null;if(!e.apiKey)throw new Error("AICommerce: apiKey is required");this.apiKey=e.apiKey,this.baseUrl=this.normalizeUrl(e.baseUrl||this.detectBaseUrl()),this.timeout=e.timeout||3e4;}detectBaseUrl(){return typeof window<"u"?window.location.origin:"https://api.aicommerce.dev"}normalizeUrl(e){return e.replace(/\/$/,"")}async request(e,t={}){let n=`${this.baseUrl}${e}`,r=new AbortController,l=setTimeout(()=>r.abort(),this.timeout);try{let o=await fetch(n,{...t,signal:r.signal,headers:{"Content-Type":"application/json","X-API-Key":this.apiKey,...this.sessionToken&&{"X-Session-Token":this.sessionToken},...t.headers}});if(clearTimeout(l),!o.ok){let h=await o.json().catch(()=>({})),u={code:h.code||"UNKNOWN_ERROR",message:h.message||h.error||`HTTP ${o.status}`,status:o.status};throw new exports.AICommerceError(u.message,u.code,u.status)}return o.json()}catch(o){throw clearTimeout(l),o instanceof exports.AICommerceError?o:o instanceof Error&&o.name==="AbortError"?new exports.AICommerceError("Request timeout","TIMEOUT",408):new exports.AICommerceError(o instanceof Error?o.message:"Unknown error","NETWORK_ERROR",0)}}async chat(e,t){let n=typeof e=="string"?{message:e,context:t,sessionToken:this.sessionToken||void 0}:{...e,sessionToken:e.sessionToken||this.sessionToken||void 0},r=await this.request("/api/v1/chat",{method:"POST",body:JSON.stringify(n)});return r.sessionToken&&(this.sessionToken=r.sessionToken),r}async createSession(){let e=await this.request("/api/v1/chat/session",{method:"POST"});return this.sessionToken=e.session.token,e.session}clearSession(){this.sessionToken=null;}getSessionToken(){return this.sessionToken}setSessionToken(e){this.sessionToken=e;}static async quickChat(e){return new s({apiKey:e.apiKey,baseUrl:e.baseUrl}).chat(e.message,e.context)}},exports.AICommerceError=class s extends Error{constructor(e,t,n){super(e),this.name="AICommerceError",this.code=t,this.status=n,Object.setPrototypeOf(this,s.prototype);}};});c();var R="1.0.0";typeof window<"u"&&(window.AICommerce=(c(),d(p)).AICommerce,window.AICommerceError=(c(),d(p)).AICommerceError);
|
|
3
|
+
exports.VERSION=R;return exports;})({});//# sourceMappingURL=index.min.js.map
|
|
4
|
+
//# sourceMappingURL=index.min.js.map
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __esm = (fn, res) => function __init() {
|
|
8
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
9
|
+
};
|
|
10
|
+
var __export = (target, all) => {
|
|
11
|
+
for (var name in all)
|
|
12
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
13
|
+
};
|
|
14
|
+
var __copyProps = (to, from, except, desc) => {
|
|
15
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
16
|
+
for (let key of __getOwnPropNames(from))
|
|
17
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
18
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
19
|
+
}
|
|
20
|
+
return to;
|
|
21
|
+
};
|
|
22
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
23
|
+
|
|
24
|
+
// src/client.ts
|
|
25
|
+
var client_exports = {};
|
|
26
|
+
__export(client_exports, {
|
|
27
|
+
AICommerce: () => exports.AICommerce,
|
|
28
|
+
AICommerceError: () => exports.AICommerceError
|
|
29
|
+
});
|
|
30
|
+
exports.AICommerce = void 0; exports.AICommerceError = void 0;
|
|
31
|
+
var init_client = __esm({
|
|
32
|
+
"src/client.ts"() {
|
|
33
|
+
exports.AICommerce = class _AICommerce {
|
|
34
|
+
constructor(config) {
|
|
35
|
+
this.sessionToken = null;
|
|
36
|
+
if (!config.apiKey) {
|
|
37
|
+
throw new Error("AICommerce: apiKey is required");
|
|
38
|
+
}
|
|
39
|
+
this.apiKey = config.apiKey;
|
|
40
|
+
this.baseUrl = this.normalizeUrl(config.baseUrl || this.detectBaseUrl());
|
|
41
|
+
this.timeout = config.timeout || 3e4;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Detect the base URL based on environment
|
|
45
|
+
*/
|
|
46
|
+
detectBaseUrl() {
|
|
47
|
+
if (typeof window !== "undefined") {
|
|
48
|
+
return window.location.origin;
|
|
49
|
+
}
|
|
50
|
+
return "https://api.aicommerce.dev";
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Normalize URL (remove trailing slash)
|
|
54
|
+
*/
|
|
55
|
+
normalizeUrl(url) {
|
|
56
|
+
return url.replace(/\/$/, "");
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Make an API request
|
|
60
|
+
*/
|
|
61
|
+
async request(endpoint, options = {}) {
|
|
62
|
+
const url = `${this.baseUrl}${endpoint}`;
|
|
63
|
+
const controller = new AbortController();
|
|
64
|
+
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
65
|
+
try {
|
|
66
|
+
const response = await fetch(url, {
|
|
67
|
+
...options,
|
|
68
|
+
signal: controller.signal,
|
|
69
|
+
headers: {
|
|
70
|
+
"Content-Type": "application/json",
|
|
71
|
+
"X-API-Key": this.apiKey,
|
|
72
|
+
...this.sessionToken && { "X-Session-Token": this.sessionToken },
|
|
73
|
+
...options.headers
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
clearTimeout(timeoutId);
|
|
77
|
+
if (!response.ok) {
|
|
78
|
+
const errorData = await response.json().catch(() => ({}));
|
|
79
|
+
const error = {
|
|
80
|
+
code: errorData.code || "UNKNOWN_ERROR",
|
|
81
|
+
message: errorData.message || errorData.error || `HTTP ${response.status}`,
|
|
82
|
+
status: response.status
|
|
83
|
+
};
|
|
84
|
+
throw new exports.AICommerceError(error.message, error.code, error.status);
|
|
85
|
+
}
|
|
86
|
+
return response.json();
|
|
87
|
+
} catch (error) {
|
|
88
|
+
clearTimeout(timeoutId);
|
|
89
|
+
if (error instanceof exports.AICommerceError) {
|
|
90
|
+
throw error;
|
|
91
|
+
}
|
|
92
|
+
if (error instanceof Error && error.name === "AbortError") {
|
|
93
|
+
throw new exports.AICommerceError("Request timeout", "TIMEOUT", 408);
|
|
94
|
+
}
|
|
95
|
+
throw new exports.AICommerceError(
|
|
96
|
+
error instanceof Error ? error.message : "Unknown error",
|
|
97
|
+
"NETWORK_ERROR",
|
|
98
|
+
0
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Send a chat message and get product recommendations
|
|
104
|
+
*
|
|
105
|
+
* @param message - The user's message or full ChatRequest object
|
|
106
|
+
* @param context - Optional context for better recommendations
|
|
107
|
+
* @returns Chat response with AI reply and products
|
|
108
|
+
*
|
|
109
|
+
* @example
|
|
110
|
+
* ```typescript
|
|
111
|
+
* // Simple usage
|
|
112
|
+
* const response = await client.chat('I need running shoes');
|
|
113
|
+
*
|
|
114
|
+
* // With context
|
|
115
|
+
* const response = await client.chat('I need running shoes', {
|
|
116
|
+
* budget: { max: 150 },
|
|
117
|
+
* preferences: ['comfortable', 'lightweight']
|
|
118
|
+
* });
|
|
119
|
+
* ```
|
|
120
|
+
*/
|
|
121
|
+
async chat(message, context) {
|
|
122
|
+
const request = typeof message === "string" ? { message, context, sessionToken: this.sessionToken || void 0 } : { ...message, sessionToken: message.sessionToken || this.sessionToken || void 0 };
|
|
123
|
+
const response = await this.request("/api/v1/chat", {
|
|
124
|
+
method: "POST",
|
|
125
|
+
body: JSON.stringify(request)
|
|
126
|
+
});
|
|
127
|
+
if (response.sessionToken) {
|
|
128
|
+
this.sessionToken = response.sessionToken;
|
|
129
|
+
}
|
|
130
|
+
return response;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Create a new chat session
|
|
134
|
+
*
|
|
135
|
+
* @returns Session information with token
|
|
136
|
+
*/
|
|
137
|
+
async createSession() {
|
|
138
|
+
const response = await this.request("/api/v1/chat/session", {
|
|
139
|
+
method: "POST"
|
|
140
|
+
});
|
|
141
|
+
this.sessionToken = response.session.token;
|
|
142
|
+
return response.session;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Clear the current session
|
|
146
|
+
*/
|
|
147
|
+
clearSession() {
|
|
148
|
+
this.sessionToken = null;
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Get the current session token
|
|
152
|
+
*/
|
|
153
|
+
getSessionToken() {
|
|
154
|
+
return this.sessionToken;
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Set a session token (for restoring sessions)
|
|
158
|
+
*/
|
|
159
|
+
setSessionToken(token) {
|
|
160
|
+
this.sessionToken = token;
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Static method for one-off chat requests
|
|
164
|
+
*
|
|
165
|
+
* @example
|
|
166
|
+
* ```typescript
|
|
167
|
+
* const response = await AICommerce.quickChat({
|
|
168
|
+
* apiKey: 'your-api-key',
|
|
169
|
+
* message: 'I need a laptop'
|
|
170
|
+
* });
|
|
171
|
+
* ```
|
|
172
|
+
*/
|
|
173
|
+
static async quickChat(options) {
|
|
174
|
+
const client = new _AICommerce({
|
|
175
|
+
apiKey: options.apiKey,
|
|
176
|
+
baseUrl: options.baseUrl
|
|
177
|
+
});
|
|
178
|
+
return client.chat(options.message, options.context);
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
exports.AICommerceError = class _AICommerceError extends Error {
|
|
182
|
+
constructor(message, code, status) {
|
|
183
|
+
super(message);
|
|
184
|
+
this.name = "AICommerceError";
|
|
185
|
+
this.code = code;
|
|
186
|
+
this.status = status;
|
|
187
|
+
Object.setPrototypeOf(this, _AICommerceError.prototype);
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
// src/index.ts
|
|
194
|
+
init_client();
|
|
195
|
+
var VERSION = "1.0.0";
|
|
196
|
+
if (typeof window !== "undefined") {
|
|
197
|
+
window.AICommerce = (init_client(), __toCommonJS(client_exports)).AICommerce;
|
|
198
|
+
window.AICommerceError = (init_client(), __toCommonJS(client_exports)).AICommerceError;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
exports.VERSION = VERSION;
|
|
202
|
+
//# sourceMappingURL=index.cjs.map
|
|
203
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client.ts","../src/index.ts"],"names":["AICommerce","AICommerceError"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;A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A,CAAO,kBAAkB,CAAA,WAAA,EAAA,EAAA,YAAA,CAAA,cAAA,CAAA,EAAoB,eAAA;AACjD","file":"index.cjs","sourcesContent":["import type {\r\n AICommerceConfig,\r\n ChatRequest,\r\n ChatResponse,\r\n ChatContext,\r\n Session,\r\n APIError,\r\n} from './types';\r\n\r\n/**\r\n * AI Commerce SDK Client\r\n * \r\n * @example\r\n * ```typescript\r\n * import { AICommerce } from '@ai-commerce/sdk';\r\n * \r\n * const client = new AICommerce({ apiKey: 'your-api-key' });\r\n * const response = await client.chat('I need a laptop under $1000');\r\n * console.log(response.products);\r\n * ```\r\n */\r\nexport class AICommerce {\r\n private readonly apiKey: string;\r\n private readonly baseUrl: string;\r\n private readonly timeout: number;\r\n private sessionToken: string | null = null;\r\n\r\n constructor(config: AICommerceConfig) {\r\n if (!config.apiKey) {\r\n throw new Error('AICommerce: apiKey is required');\r\n }\r\n\r\n this.apiKey = config.apiKey;\r\n this.baseUrl = this.normalizeUrl(config.baseUrl || this.detectBaseUrl());\r\n this.timeout = config.timeout || 30000;\r\n }\r\n\r\n /**\r\n * Detect the base URL based on environment\r\n */\r\n private detectBaseUrl(): string {\r\n // Browser environment\r\n if (typeof window !== 'undefined') {\r\n return window.location.origin;\r\n }\r\n // Node.js or default\r\n return 'https://api.aicommerce.dev';\r\n }\r\n\r\n /**\r\n * Normalize URL (remove trailing slash)\r\n */\r\n private normalizeUrl(url: string): string {\r\n return url.replace(/\\/$/, '');\r\n }\r\n\r\n /**\r\n * Make an API request\r\n */\r\n private async request<T>(\r\n endpoint: string,\r\n options: RequestInit = {}\r\n ): Promise<T> {\r\n const url = `${this.baseUrl}${endpoint}`;\r\n\r\n const controller = new AbortController();\r\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\r\n\r\n try {\r\n const response = await fetch(url, {\r\n ...options,\r\n signal: controller.signal,\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n 'X-API-Key': this.apiKey,\r\n ...(this.sessionToken && { 'X-Session-Token': this.sessionToken }),\r\n ...options.headers,\r\n },\r\n });\r\n\r\n clearTimeout(timeoutId);\r\n\r\n if (!response.ok) {\r\n const errorData = await response.json().catch(() => ({}));\r\n const error: APIError = {\r\n code: errorData.code || 'UNKNOWN_ERROR',\r\n message: errorData.message || errorData.error || `HTTP ${response.status}`,\r\n status: response.status,\r\n };\r\n throw new AICommerceError(error.message, error.code, error.status);\r\n }\r\n\r\n return response.json();\r\n } catch (error) {\r\n clearTimeout(timeoutId);\r\n\r\n if (error instanceof AICommerceError) {\r\n throw error;\r\n }\r\n\r\n if (error instanceof Error && error.name === 'AbortError') {\r\n throw new AICommerceError('Request timeout', 'TIMEOUT', 408);\r\n }\r\n\r\n throw new AICommerceError(\r\n error instanceof Error ? error.message : 'Unknown error',\r\n 'NETWORK_ERROR',\r\n 0\r\n );\r\n }\r\n }\r\n\r\n /**\r\n * Send a chat message and get product recommendations\r\n * \r\n * @param message - The user's message or full ChatRequest object\r\n * @param context - Optional context for better recommendations\r\n * @returns Chat response with AI reply and products\r\n * \r\n * @example\r\n * ```typescript\r\n * // Simple usage\r\n * const response = await client.chat('I need running shoes');\r\n * \r\n * // With context\r\n * const response = await client.chat('I need running shoes', {\r\n * budget: { max: 150 },\r\n * preferences: ['comfortable', 'lightweight']\r\n * });\r\n * ```\r\n */\r\n async chat(\r\n message: string | ChatRequest,\r\n context?: ChatContext\r\n ): Promise<ChatResponse> {\r\n const request: ChatRequest = typeof message === 'string'\r\n ? { message, context, sessionToken: this.sessionToken || undefined }\r\n : { ...message, sessionToken: message.sessionToken || this.sessionToken || undefined };\r\n\r\n const response = await this.request<ChatResponse>('/api/v1/chat', {\r\n method: 'POST',\r\n body: JSON.stringify(request),\r\n });\r\n\r\n // Store session token for follow-up messages\r\n if (response.sessionToken) {\r\n this.sessionToken = response.sessionToken;\r\n }\r\n\r\n return response;\r\n }\r\n\r\n /**\r\n * Create a new chat session\r\n * \r\n * @returns Session information with token\r\n */\r\n async createSession(): Promise<Session> {\r\n const response = await this.request<{ session: Session }>('/api/v1/chat/session', {\r\n method: 'POST',\r\n });\r\n\r\n this.sessionToken = response.session.token;\r\n return response.session;\r\n }\r\n\r\n /**\r\n * Clear the current session\r\n */\r\n clearSession(): void {\r\n this.sessionToken = null;\r\n }\r\n\r\n /**\r\n * Get the current session token\r\n */\r\n getSessionToken(): string | null {\r\n return this.sessionToken;\r\n }\r\n\r\n /**\r\n * Set a session token (for restoring sessions)\r\n */\r\n setSessionToken(token: string): void {\r\n this.sessionToken = token;\r\n }\r\n\r\n /**\r\n * Static method for one-off chat requests\r\n * \r\n * @example\r\n * ```typescript\r\n * const response = await AICommerce.quickChat({\r\n * apiKey: 'your-api-key',\r\n * message: 'I need a laptop'\r\n * });\r\n * ```\r\n */\r\n static async quickChat(options: {\r\n apiKey: string;\r\n message: string;\r\n baseUrl?: string;\r\n context?: ChatContext;\r\n }): Promise<ChatResponse> {\r\n const client = new AICommerce({\r\n apiKey: options.apiKey,\r\n baseUrl: options.baseUrl,\r\n });\r\n return client.chat(options.message, options.context);\r\n }\r\n}\r\n\r\n/**\r\n * Custom error class for AI Commerce SDK\r\n */\r\nexport class AICommerceError extends Error {\r\n readonly code: string;\r\n readonly status: number;\r\n\r\n constructor(message: string, code: string, status: number) {\r\n super(message);\r\n this.name = 'AICommerceError';\r\n this.code = code;\r\n this.status = status;\r\n\r\n // Maintain proper prototype chain\r\n Object.setPrototypeOf(this, AICommerceError.prototype);\r\n }\r\n}\r\n","/**\r\n * AI Commerce SDK\r\n * \r\n * AI-powered product recommendations for e-commerce\r\n * \r\n * @packageDocumentation\r\n * @module @ai-commerce/sdk\r\n * \r\n * @example\r\n * ```typescript\r\n * // npm usage\r\n * import { AICommerce } from '@ai-commerce/sdk';\r\n * \r\n * const client = new AICommerce({ apiKey: 'your-api-key' });\r\n * const response = await client.chat('I need a laptop');\r\n * console.log(response.products);\r\n * ```\r\n * \r\n * @example\r\n * ```html\r\n * <!-- Script tag usage -->\r\n * <script src=\"https://cdn.aicommerce.dev/sdk.min.js\"></script>\r\n * <script>\r\n * const client = new AICommerce({ apiKey: 'your-api-key' });\r\n * client.chat('I need a laptop').then(response => {\r\n * console.log(response.products);\r\n * });\r\n * </script>\r\n * ```\r\n */\r\n\r\n// Export main client\r\nexport { AICommerce, AICommerceError } from './client';\r\n\r\n// Export all types\r\nexport type {\r\n AICommerceConfig,\r\n ChatRequest,\r\n ChatResponse,\r\n ChatContext,\r\n Product,\r\n Session,\r\n APIError,\r\n EventType,\r\n EventCallback,\r\n} from './types';\r\n\r\n// Version\r\nexport const VERSION = '1.0.0';\r\n\r\n// For UMD builds, attach to window\r\nif (typeof window !== 'undefined') {\r\n // @ts-expect-error - Attaching to window for UMD\r\n window.AICommerce = require('./client').AICommerce;\r\n // @ts-expect-error - Attaching to window for UMD\r\n window.AICommerceError = require('./client').AICommerceError;\r\n}\r\n"]}
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AI Commerce SDK Types
|
|
3
|
+
*/
|
|
4
|
+
/** SDK Configuration options */
|
|
5
|
+
interface AICommerceConfig {
|
|
6
|
+
/** Your API key from the AI Commerce dashboard */
|
|
7
|
+
apiKey: string;
|
|
8
|
+
/** Base URL for the API (defaults to current origin or https://api.aicommerce.dev) */
|
|
9
|
+
baseUrl?: string;
|
|
10
|
+
/** Request timeout in milliseconds (default: 30000) */
|
|
11
|
+
timeout?: number;
|
|
12
|
+
}
|
|
13
|
+
/** Chat message request */
|
|
14
|
+
interface ChatRequest {
|
|
15
|
+
/** The user's message */
|
|
16
|
+
message: string;
|
|
17
|
+
/** Optional session token for conversation continuity */
|
|
18
|
+
sessionToken?: string;
|
|
19
|
+
/** Optional context for better recommendations */
|
|
20
|
+
context?: ChatContext;
|
|
21
|
+
}
|
|
22
|
+
/** Additional context for chat requests */
|
|
23
|
+
interface ChatContext {
|
|
24
|
+
/** Budget range */
|
|
25
|
+
budget?: {
|
|
26
|
+
min?: number;
|
|
27
|
+
max?: number;
|
|
28
|
+
currency?: string;
|
|
29
|
+
};
|
|
30
|
+
/** User preferences */
|
|
31
|
+
preferences?: string[];
|
|
32
|
+
/** Category to focus on */
|
|
33
|
+
category?: string;
|
|
34
|
+
/** Additional metadata */
|
|
35
|
+
metadata?: Record<string, unknown>;
|
|
36
|
+
}
|
|
37
|
+
/** Chat response from the API */
|
|
38
|
+
interface ChatResponse {
|
|
39
|
+
/** AI-generated response text */
|
|
40
|
+
reply: string;
|
|
41
|
+
/** Recommended products */
|
|
42
|
+
products: Product[];
|
|
43
|
+
/** Session token for follow-up messages */
|
|
44
|
+
sessionToken: string;
|
|
45
|
+
/** Suggested follow-up questions */
|
|
46
|
+
suggestions?: string[];
|
|
47
|
+
/** AI confidence score (0-1) */
|
|
48
|
+
confidence?: number;
|
|
49
|
+
}
|
|
50
|
+
/** Product information */
|
|
51
|
+
interface Product {
|
|
52
|
+
/** Unique product ID */
|
|
53
|
+
id: string;
|
|
54
|
+
/** Product name */
|
|
55
|
+
name: string;
|
|
56
|
+
/** Product description */
|
|
57
|
+
description?: string;
|
|
58
|
+
/** Price in the store's currency */
|
|
59
|
+
price: number;
|
|
60
|
+
/** Currency code */
|
|
61
|
+
currency?: string;
|
|
62
|
+
/** Primary image URL */
|
|
63
|
+
imageUrl?: string;
|
|
64
|
+
/** All image URLs */
|
|
65
|
+
images?: string[];
|
|
66
|
+
/** Product category */
|
|
67
|
+
category?: string;
|
|
68
|
+
/** Product attributes */
|
|
69
|
+
attributes?: Record<string, string>;
|
|
70
|
+
/** Relevance score (0-1) */
|
|
71
|
+
relevanceScore?: number;
|
|
72
|
+
/** Product URL */
|
|
73
|
+
url?: string;
|
|
74
|
+
}
|
|
75
|
+
/** Session information */
|
|
76
|
+
interface Session {
|
|
77
|
+
/** Session token */
|
|
78
|
+
token: string;
|
|
79
|
+
/** Session expiration time */
|
|
80
|
+
expiresAt?: string;
|
|
81
|
+
}
|
|
82
|
+
/** API Error response */
|
|
83
|
+
interface APIError {
|
|
84
|
+
/** Error code */
|
|
85
|
+
code: string;
|
|
86
|
+
/** Error message */
|
|
87
|
+
message: string;
|
|
88
|
+
/** HTTP status code */
|
|
89
|
+
status: number;
|
|
90
|
+
}
|
|
91
|
+
/** Event types for callbacks */
|
|
92
|
+
type EventType = 'message' | 'products' | 'error' | 'session';
|
|
93
|
+
/** Event callback */
|
|
94
|
+
type EventCallback<T = unknown> = (data: T) => void;
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* AI Commerce SDK Client
|
|
98
|
+
*
|
|
99
|
+
* @example
|
|
100
|
+
* ```typescript
|
|
101
|
+
* import { AICommerce } from '@ai-commerce/sdk';
|
|
102
|
+
*
|
|
103
|
+
* const client = new AICommerce({ apiKey: 'your-api-key' });
|
|
104
|
+
* const response = await client.chat('I need a laptop under $1000');
|
|
105
|
+
* console.log(response.products);
|
|
106
|
+
* ```
|
|
107
|
+
*/
|
|
108
|
+
declare class AICommerce {
|
|
109
|
+
private readonly apiKey;
|
|
110
|
+
private readonly baseUrl;
|
|
111
|
+
private readonly timeout;
|
|
112
|
+
private sessionToken;
|
|
113
|
+
constructor(config: AICommerceConfig);
|
|
114
|
+
/**
|
|
115
|
+
* Detect the base URL based on environment
|
|
116
|
+
*/
|
|
117
|
+
private detectBaseUrl;
|
|
118
|
+
/**
|
|
119
|
+
* Normalize URL (remove trailing slash)
|
|
120
|
+
*/
|
|
121
|
+
private normalizeUrl;
|
|
122
|
+
/**
|
|
123
|
+
* Make an API request
|
|
124
|
+
*/
|
|
125
|
+
private request;
|
|
126
|
+
/**
|
|
127
|
+
* Send a chat message and get product recommendations
|
|
128
|
+
*
|
|
129
|
+
* @param message - The user's message or full ChatRequest object
|
|
130
|
+
* @param context - Optional context for better recommendations
|
|
131
|
+
* @returns Chat response with AI reply and products
|
|
132
|
+
*
|
|
133
|
+
* @example
|
|
134
|
+
* ```typescript
|
|
135
|
+
* // Simple usage
|
|
136
|
+
* const response = await client.chat('I need running shoes');
|
|
137
|
+
*
|
|
138
|
+
* // With context
|
|
139
|
+
* const response = await client.chat('I need running shoes', {
|
|
140
|
+
* budget: { max: 150 },
|
|
141
|
+
* preferences: ['comfortable', 'lightweight']
|
|
142
|
+
* });
|
|
143
|
+
* ```
|
|
144
|
+
*/
|
|
145
|
+
chat(message: string | ChatRequest, context?: ChatContext): Promise<ChatResponse>;
|
|
146
|
+
/**
|
|
147
|
+
* Create a new chat session
|
|
148
|
+
*
|
|
149
|
+
* @returns Session information with token
|
|
150
|
+
*/
|
|
151
|
+
createSession(): Promise<Session>;
|
|
152
|
+
/**
|
|
153
|
+
* Clear the current session
|
|
154
|
+
*/
|
|
155
|
+
clearSession(): void;
|
|
156
|
+
/**
|
|
157
|
+
* Get the current session token
|
|
158
|
+
*/
|
|
159
|
+
getSessionToken(): string | null;
|
|
160
|
+
/**
|
|
161
|
+
* Set a session token (for restoring sessions)
|
|
162
|
+
*/
|
|
163
|
+
setSessionToken(token: string): void;
|
|
164
|
+
/**
|
|
165
|
+
* Static method for one-off chat requests
|
|
166
|
+
*
|
|
167
|
+
* @example
|
|
168
|
+
* ```typescript
|
|
169
|
+
* const response = await AICommerce.quickChat({
|
|
170
|
+
* apiKey: 'your-api-key',
|
|
171
|
+
* message: 'I need a laptop'
|
|
172
|
+
* });
|
|
173
|
+
* ```
|
|
174
|
+
*/
|
|
175
|
+
static quickChat(options: {
|
|
176
|
+
apiKey: string;
|
|
177
|
+
message: string;
|
|
178
|
+
baseUrl?: string;
|
|
179
|
+
context?: ChatContext;
|
|
180
|
+
}): Promise<ChatResponse>;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Custom error class for AI Commerce SDK
|
|
184
|
+
*/
|
|
185
|
+
declare class AICommerceError extends Error {
|
|
186
|
+
readonly code: string;
|
|
187
|
+
readonly status: number;
|
|
188
|
+
constructor(message: string, code: string, status: number);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* AI Commerce SDK
|
|
193
|
+
*
|
|
194
|
+
* AI-powered product recommendations for e-commerce
|
|
195
|
+
*
|
|
196
|
+
* @packageDocumentation
|
|
197
|
+
* @module @ai-commerce/sdk
|
|
198
|
+
*
|
|
199
|
+
* @example
|
|
200
|
+
* ```typescript
|
|
201
|
+
* // npm usage
|
|
202
|
+
* import { AICommerce } from '@ai-commerce/sdk';
|
|
203
|
+
*
|
|
204
|
+
* const client = new AICommerce({ apiKey: 'your-api-key' });
|
|
205
|
+
* const response = await client.chat('I need a laptop');
|
|
206
|
+
* console.log(response.products);
|
|
207
|
+
* ```
|
|
208
|
+
*
|
|
209
|
+
* @example
|
|
210
|
+
* ```html
|
|
211
|
+
* <!-- Script tag usage -->
|
|
212
|
+
* <script src="https://cdn.aicommerce.dev/sdk.min.js"></script>
|
|
213
|
+
* <script>
|
|
214
|
+
* const client = new AICommerce({ apiKey: 'your-api-key' });
|
|
215
|
+
* client.chat('I need a laptop').then(response => {
|
|
216
|
+
* console.log(response.products);
|
|
217
|
+
* });
|
|
218
|
+
* </script>
|
|
219
|
+
* ```
|
|
220
|
+
*/
|
|
221
|
+
|
|
222
|
+
declare const VERSION = "1.0.0";
|
|
223
|
+
|
|
224
|
+
export { AICommerce, type AICommerceConfig, AICommerceError, type APIError, type ChatContext, type ChatRequest, type ChatResponse, type EventCallback, type EventType, type Product, type Session, VERSION };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AI Commerce SDK Types
|
|
3
|
+
*/
|
|
4
|
+
/** SDK Configuration options */
|
|
5
|
+
interface AICommerceConfig {
|
|
6
|
+
/** Your API key from the AI Commerce dashboard */
|
|
7
|
+
apiKey: string;
|
|
8
|
+
/** Base URL for the API (defaults to current origin or https://api.aicommerce.dev) */
|
|
9
|
+
baseUrl?: string;
|
|
10
|
+
/** Request timeout in milliseconds (default: 30000) */
|
|
11
|
+
timeout?: number;
|
|
12
|
+
}
|
|
13
|
+
/** Chat message request */
|
|
14
|
+
interface ChatRequest {
|
|
15
|
+
/** The user's message */
|
|
16
|
+
message: string;
|
|
17
|
+
/** Optional session token for conversation continuity */
|
|
18
|
+
sessionToken?: string;
|
|
19
|
+
/** Optional context for better recommendations */
|
|
20
|
+
context?: ChatContext;
|
|
21
|
+
}
|
|
22
|
+
/** Additional context for chat requests */
|
|
23
|
+
interface ChatContext {
|
|
24
|
+
/** Budget range */
|
|
25
|
+
budget?: {
|
|
26
|
+
min?: number;
|
|
27
|
+
max?: number;
|
|
28
|
+
currency?: string;
|
|
29
|
+
};
|
|
30
|
+
/** User preferences */
|
|
31
|
+
preferences?: string[];
|
|
32
|
+
/** Category to focus on */
|
|
33
|
+
category?: string;
|
|
34
|
+
/** Additional metadata */
|
|
35
|
+
metadata?: Record<string, unknown>;
|
|
36
|
+
}
|
|
37
|
+
/** Chat response from the API */
|
|
38
|
+
interface ChatResponse {
|
|
39
|
+
/** AI-generated response text */
|
|
40
|
+
reply: string;
|
|
41
|
+
/** Recommended products */
|
|
42
|
+
products: Product[];
|
|
43
|
+
/** Session token for follow-up messages */
|
|
44
|
+
sessionToken: string;
|
|
45
|
+
/** Suggested follow-up questions */
|
|
46
|
+
suggestions?: string[];
|
|
47
|
+
/** AI confidence score (0-1) */
|
|
48
|
+
confidence?: number;
|
|
49
|
+
}
|
|
50
|
+
/** Product information */
|
|
51
|
+
interface Product {
|
|
52
|
+
/** Unique product ID */
|
|
53
|
+
id: string;
|
|
54
|
+
/** Product name */
|
|
55
|
+
name: string;
|
|
56
|
+
/** Product description */
|
|
57
|
+
description?: string;
|
|
58
|
+
/** Price in the store's currency */
|
|
59
|
+
price: number;
|
|
60
|
+
/** Currency code */
|
|
61
|
+
currency?: string;
|
|
62
|
+
/** Primary image URL */
|
|
63
|
+
imageUrl?: string;
|
|
64
|
+
/** All image URLs */
|
|
65
|
+
images?: string[];
|
|
66
|
+
/** Product category */
|
|
67
|
+
category?: string;
|
|
68
|
+
/** Product attributes */
|
|
69
|
+
attributes?: Record<string, string>;
|
|
70
|
+
/** Relevance score (0-1) */
|
|
71
|
+
relevanceScore?: number;
|
|
72
|
+
/** Product URL */
|
|
73
|
+
url?: string;
|
|
74
|
+
}
|
|
75
|
+
/** Session information */
|
|
76
|
+
interface Session {
|
|
77
|
+
/** Session token */
|
|
78
|
+
token: string;
|
|
79
|
+
/** Session expiration time */
|
|
80
|
+
expiresAt?: string;
|
|
81
|
+
}
|
|
82
|
+
/** API Error response */
|
|
83
|
+
interface APIError {
|
|
84
|
+
/** Error code */
|
|
85
|
+
code: string;
|
|
86
|
+
/** Error message */
|
|
87
|
+
message: string;
|
|
88
|
+
/** HTTP status code */
|
|
89
|
+
status: number;
|
|
90
|
+
}
|
|
91
|
+
/** Event types for callbacks */
|
|
92
|
+
type EventType = 'message' | 'products' | 'error' | 'session';
|
|
93
|
+
/** Event callback */
|
|
94
|
+
type EventCallback<T = unknown> = (data: T) => void;
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* AI Commerce SDK Client
|
|
98
|
+
*
|
|
99
|
+
* @example
|
|
100
|
+
* ```typescript
|
|
101
|
+
* import { AICommerce } from '@ai-commerce/sdk';
|
|
102
|
+
*
|
|
103
|
+
* const client = new AICommerce({ apiKey: 'your-api-key' });
|
|
104
|
+
* const response = await client.chat('I need a laptop under $1000');
|
|
105
|
+
* console.log(response.products);
|
|
106
|
+
* ```
|
|
107
|
+
*/
|
|
108
|
+
declare class AICommerce {
|
|
109
|
+
private readonly apiKey;
|
|
110
|
+
private readonly baseUrl;
|
|
111
|
+
private readonly timeout;
|
|
112
|
+
private sessionToken;
|
|
113
|
+
constructor(config: AICommerceConfig);
|
|
114
|
+
/**
|
|
115
|
+
* Detect the base URL based on environment
|
|
116
|
+
*/
|
|
117
|
+
private detectBaseUrl;
|
|
118
|
+
/**
|
|
119
|
+
* Normalize URL (remove trailing slash)
|
|
120
|
+
*/
|
|
121
|
+
private normalizeUrl;
|
|
122
|
+
/**
|
|
123
|
+
* Make an API request
|
|
124
|
+
*/
|
|
125
|
+
private request;
|
|
126
|
+
/**
|
|
127
|
+
* Send a chat message and get product recommendations
|
|
128
|
+
*
|
|
129
|
+
* @param message - The user's message or full ChatRequest object
|
|
130
|
+
* @param context - Optional context for better recommendations
|
|
131
|
+
* @returns Chat response with AI reply and products
|
|
132
|
+
*
|
|
133
|
+
* @example
|
|
134
|
+
* ```typescript
|
|
135
|
+
* // Simple usage
|
|
136
|
+
* const response = await client.chat('I need running shoes');
|
|
137
|
+
*
|
|
138
|
+
* // With context
|
|
139
|
+
* const response = await client.chat('I need running shoes', {
|
|
140
|
+
* budget: { max: 150 },
|
|
141
|
+
* preferences: ['comfortable', 'lightweight']
|
|
142
|
+
* });
|
|
143
|
+
* ```
|
|
144
|
+
*/
|
|
145
|
+
chat(message: string | ChatRequest, context?: ChatContext): Promise<ChatResponse>;
|
|
146
|
+
/**
|
|
147
|
+
* Create a new chat session
|
|
148
|
+
*
|
|
149
|
+
* @returns Session information with token
|
|
150
|
+
*/
|
|
151
|
+
createSession(): Promise<Session>;
|
|
152
|
+
/**
|
|
153
|
+
* Clear the current session
|
|
154
|
+
*/
|
|
155
|
+
clearSession(): void;
|
|
156
|
+
/**
|
|
157
|
+
* Get the current session token
|
|
158
|
+
*/
|
|
159
|
+
getSessionToken(): string | null;
|
|
160
|
+
/**
|
|
161
|
+
* Set a session token (for restoring sessions)
|
|
162
|
+
*/
|
|
163
|
+
setSessionToken(token: string): void;
|
|
164
|
+
/**
|
|
165
|
+
* Static method for one-off chat requests
|
|
166
|
+
*
|
|
167
|
+
* @example
|
|
168
|
+
* ```typescript
|
|
169
|
+
* const response = await AICommerce.quickChat({
|
|
170
|
+
* apiKey: 'your-api-key',
|
|
171
|
+
* message: 'I need a laptop'
|
|
172
|
+
* });
|
|
173
|
+
* ```
|
|
174
|
+
*/
|
|
175
|
+
static quickChat(options: {
|
|
176
|
+
apiKey: string;
|
|
177
|
+
message: string;
|
|
178
|
+
baseUrl?: string;
|
|
179
|
+
context?: ChatContext;
|
|
180
|
+
}): Promise<ChatResponse>;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Custom error class for AI Commerce SDK
|
|
184
|
+
*/
|
|
185
|
+
declare class AICommerceError extends Error {
|
|
186
|
+
readonly code: string;
|
|
187
|
+
readonly status: number;
|
|
188
|
+
constructor(message: string, code: string, status: number);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* AI Commerce SDK
|
|
193
|
+
*
|
|
194
|
+
* AI-powered product recommendations for e-commerce
|
|
195
|
+
*
|
|
196
|
+
* @packageDocumentation
|
|
197
|
+
* @module @ai-commerce/sdk
|
|
198
|
+
*
|
|
199
|
+
* @example
|
|
200
|
+
* ```typescript
|
|
201
|
+
* // npm usage
|
|
202
|
+
* import { AICommerce } from '@ai-commerce/sdk';
|
|
203
|
+
*
|
|
204
|
+
* const client = new AICommerce({ apiKey: 'your-api-key' });
|
|
205
|
+
* const response = await client.chat('I need a laptop');
|
|
206
|
+
* console.log(response.products);
|
|
207
|
+
* ```
|
|
208
|
+
*
|
|
209
|
+
* @example
|
|
210
|
+
* ```html
|
|
211
|
+
* <!-- Script tag usage -->
|
|
212
|
+
* <script src="https://cdn.aicommerce.dev/sdk.min.js"></script>
|
|
213
|
+
* <script>
|
|
214
|
+
* const client = new AICommerce({ apiKey: 'your-api-key' });
|
|
215
|
+
* client.chat('I need a laptop').then(response => {
|
|
216
|
+
* console.log(response.products);
|
|
217
|
+
* });
|
|
218
|
+
* </script>
|
|
219
|
+
* ```
|
|
220
|
+
*/
|
|
221
|
+
|
|
222
|
+
declare const VERSION = "1.0.0";
|
|
223
|
+
|
|
224
|
+
export { AICommerce, type AICommerceConfig, AICommerceError, type APIError, type ChatContext, type ChatRequest, type ChatResponse, type EventCallback, type EventType, type Product, type Session, VERSION };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client.ts","../src/index.ts"],"names":["client_exports","__export","AICommerce","AICommerceError","init_client","__esmMin","_AICommerce","config","url","endpoint","options","controller","timeoutId","response","errorData","error","message","context","request","token","_AICommerceError","code","status","VERSION"],"mappings":";ocAAA,IAAAA,CAAAA,CAAA,GAAAC,CAAAA,CAAAD,CAAAA,CAAA,gBAAAE,kBAAAA,CAAA,eAAA,CAAA,IAAAC,0BAqBaD,yBAAAA,CAkMAC,mCAvNbC,CAAAA,CAAAC,CAAAA,CAAA,KAqBaH,kBAAAA,CAAN,MAAMI,CAAW,CAMpB,WAAA,CAAYC,EAA0B,CAFtC,IAAA,CAAQ,aAA8B,IAAA,CAGlC,GAAI,CAACA,CAAAA,CAAO,MAAA,CACR,MAAM,IAAI,KAAA,CAAM,gCAAgC,CAAA,CAGpD,IAAA,CAAK,OAASA,CAAAA,CAAO,MAAA,CACrB,KAAK,OAAA,CAAU,IAAA,CAAK,aAAaA,CAAAA,CAAO,OAAA,EAAW,KAAK,aAAA,EAAe,EACvE,IAAA,CAAK,OAAA,CAAUA,EAAO,OAAA,EAAW,IACrC,CAKQ,aAAA,EAAwB,CAE5B,OAAI,OAAO,MAAA,CAAW,IACX,MAAA,CAAO,QAAA,CAAS,OAGpB,4BACX,CAKQ,aAAaC,CAAAA,CAAqB,CACtC,OAAOA,CAAAA,CAAI,OAAA,CAAQ,MAAO,EAAE,CAChC,CAKA,MAAc,OAAA,CACVC,EACAC,CAAAA,CAAuB,GACb,CACV,IAAMF,EAAM,CAAA,EAAG,IAAA,CAAK,OAAO,CAAA,EAAGC,CAAQ,GAEhCE,CAAAA,CAAa,IAAI,gBACjBC,CAAAA,CAAY,UAAA,CAAW,IAAMD,CAAAA,CAAW,KAAA,GAAS,IAAA,CAAK,OAAO,EAEnE,GAAI,CACA,IAAME,CAAAA,CAAW,MAAM,MAAML,CAAAA,CAAK,CAC9B,GAAGE,CAAAA,CACH,MAAA,CAAQC,EAAW,MAAA,CACnB,OAAA,CAAS,CACL,cAAA,CAAgB,kBAAA,CAChB,YAAa,IAAA,CAAK,MAAA,CAClB,GAAI,IAAA,C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AkB,CAAA,CAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAoB,eAAA,CAAA","file":"index.min.js","sourcesContent":["import type {\r\n AICommerceConfig,\r\n ChatRequest,\r\n ChatResponse,\r\n ChatContext,\r\n Session,\r\n APIError,\r\n} from './types';\r\n\r\n/**\r\n * AI Commerce SDK Client\r\n * \r\n * @example\r\n * ```typescript\r\n * import { AICommerce } from '@ai-commerce/sdk';\r\n * \r\n * const client = new AICommerce({ apiKey: 'your-api-key' });\r\n * const response = await client.chat('I need a laptop under $1000');\r\n * console.log(response.products);\r\n * ```\r\n */\r\nexport class AICommerce {\r\n private readonly apiKey: string;\r\n private readonly baseUrl: string;\r\n private readonly timeout: number;\r\n private sessionToken: string | null = null;\r\n\r\n constructor(config: AICommerceConfig) {\r\n if (!config.apiKey) {\r\n throw new Error('AICommerce: apiKey is required');\r\n }\r\n\r\n this.apiKey = config.apiKey;\r\n this.baseUrl = this.normalizeUrl(config.baseUrl || this.detectBaseUrl());\r\n this.timeout = config.timeout || 30000;\r\n }\r\n\r\n /**\r\n * Detect the base URL based on environment\r\n */\r\n private detectBaseUrl(): string {\r\n // Browser environment\r\n if (typeof window !== 'undefined') {\r\n return window.location.origin;\r\n }\r\n // Node.js or default\r\n return 'https://api.aicommerce.dev';\r\n }\r\n\r\n /**\r\n * Normalize URL (remove trailing slash)\r\n */\r\n private normalizeUrl(url: string): string {\r\n return url.replace(/\\/$/, '');\r\n }\r\n\r\n /**\r\n * Make an API request\r\n */\r\n private async request<T>(\r\n endpoint: string,\r\n options: RequestInit = {}\r\n ): Promise<T> {\r\n const url = `${this.baseUrl}${endpoint}`;\r\n\r\n const controller = new AbortController();\r\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\r\n\r\n try {\r\n const response = await fetch(url, {\r\n ...options,\r\n signal: controller.signal,\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n 'X-API-Key': this.apiKey,\r\n ...(this.sessionToken && { 'X-Session-Token': this.sessionToken }),\r\n ...options.headers,\r\n },\r\n });\r\n\r\n clearTimeout(timeoutId);\r\n\r\n if (!response.ok) {\r\n const errorData = await response.json().catch(() => ({}));\r\n const error: APIError = {\r\n code: errorData.code || 'UNKNOWN_ERROR',\r\n message: errorData.message || errorData.error || `HTTP ${response.status}`,\r\n status: response.status,\r\n };\r\n throw new AICommerceError(error.message, error.code, error.status);\r\n }\r\n\r\n return response.json();\r\n } catch (error) {\r\n clearTimeout(timeoutId);\r\n\r\n if (error instanceof AICommerceError) {\r\n throw error;\r\n }\r\n\r\n if (error instanceof Error && error.name === 'AbortError') {\r\n throw new AICommerceError('Request timeout', 'TIMEOUT', 408);\r\n }\r\n\r\n throw new AICommerceError(\r\n error instanceof Error ? error.message : 'Unknown error',\r\n 'NETWORK_ERROR',\r\n 0\r\n );\r\n }\r\n }\r\n\r\n /**\r\n * Send a chat message and get product recommendations\r\n * \r\n * @param message - The user's message or full ChatRequest object\r\n * @param context - Optional context for better recommendations\r\n * @returns Chat response with AI reply and products\r\n * \r\n * @example\r\n * ```typescript\r\n * // Simple usage\r\n * const response = await client.chat('I need running shoes');\r\n * \r\n * // With context\r\n * const response = await client.chat('I need running shoes', {\r\n * budget: { max: 150 },\r\n * preferences: ['comfortable', 'lightweight']\r\n * });\r\n * ```\r\n */\r\n async chat(\r\n message: string | ChatRequest,\r\n context?: ChatContext\r\n ): Promise<ChatResponse> {\r\n const request: ChatRequest = typeof message === 'string'\r\n ? { message, context, sessionToken: this.sessionToken || undefined }\r\n : { ...message, sessionToken: message.sessionToken || this.sessionToken || undefined };\r\n\r\n const response = await this.request<ChatResponse>('/api/v1/chat', {\r\n method: 'POST',\r\n body: JSON.stringify(request),\r\n });\r\n\r\n // Store session token for follow-up messages\r\n if (response.sessionToken) {\r\n this.sessionToken = response.sessionToken;\r\n }\r\n\r\n return response;\r\n }\r\n\r\n /**\r\n * Create a new chat session\r\n * \r\n * @returns Session information with token\r\n */\r\n async createSession(): Promise<Session> {\r\n const response = await this.request<{ session: Session }>('/api/v1/chat/session', {\r\n method: 'POST',\r\n });\r\n\r\n this.sessionToken = response.session.token;\r\n return response.session;\r\n }\r\n\r\n /**\r\n * Clear the current session\r\n */\r\n clearSession(): void {\r\n this.sessionToken = null;\r\n }\r\n\r\n /**\r\n * Get the current session token\r\n */\r\n getSessionToken(): string | null {\r\n return this.sessionToken;\r\n }\r\n\r\n /**\r\n * Set a session token (for restoring sessions)\r\n */\r\n setSessionToken(token: string): void {\r\n this.sessionToken = token;\r\n }\r\n\r\n /**\r\n * Static method for one-off chat requests\r\n * \r\n * @example\r\n * ```typescript\r\n * const response = await AICommerce.quickChat({\r\n * apiKey: 'your-api-key',\r\n * message: 'I need a laptop'\r\n * });\r\n * ```\r\n */\r\n static async quickChat(options: {\r\n apiKey: string;\r\n message: string;\r\n baseUrl?: string;\r\n context?: ChatContext;\r\n }): Promise<ChatResponse> {\r\n const client = new AICommerce({\r\n apiKey: options.apiKey,\r\n baseUrl: options.baseUrl,\r\n });\r\n return client.chat(options.message, options.context);\r\n }\r\n}\r\n\r\n/**\r\n * Custom error class for AI Commerce SDK\r\n */\r\nexport class AICommerceError extends Error {\r\n readonly code: string;\r\n readonly status: number;\r\n\r\n constructor(message: string, code: string, status: number) {\r\n super(message);\r\n this.name = 'AICommerceError';\r\n this.code = code;\r\n this.status = status;\r\n\r\n // Maintain proper prototype chain\r\n Object.setPrototypeOf(this, AICommerceError.prototype);\r\n }\r\n}\r\n","/**\r\n * AI Commerce SDK\r\n * \r\n * AI-powered product recommendations for e-commerce\r\n * \r\n * @packageDocumentation\r\n * @module @ai-commerce/sdk\r\n * \r\n * @example\r\n * ```typescript\r\n * // npm usage\r\n * import { AICommerce } from '@ai-commerce/sdk';\r\n * \r\n * const client = new AICommerce({ apiKey: 'your-api-key' });\r\n * const response = await client.chat('I need a laptop');\r\n * console.log(response.products);\r\n * ```\r\n * \r\n * @example\r\n * ```html\r\n * <!-- Script tag usage -->\r\n * <script src=\"https://cdn.aicommerce.dev/sdk.min.js\"></script>\r\n * <script>\r\n * const client = new AICommerce({ apiKey: 'your-api-key' });\r\n * client.chat('I need a laptop').then(response => {\r\n * console.log(response.products);\r\n * });\r\n * </script>\r\n * ```\r\n */\r\n\r\n// Export main client\r\nexport { AICommerce, AICommerceError } from './client';\r\n\r\n// Export all types\r\nexport type {\r\n AICommerceConfig,\r\n ChatRequest,\r\n ChatResponse,\r\n ChatContext,\r\n Product,\r\n Session,\r\n APIError,\r\n EventType,\r\n EventCallback,\r\n} from './types';\r\n\r\n// Version\r\nexport const VERSION = '1.0.0';\r\n\r\n// For UMD builds, attach to window\r\nif (typeof window !== 'undefined') {\r\n // @ts-expect-error - Attaching to window for UMD\r\n window.AICommerce = require('./client').AICommerce;\r\n // @ts-expect-error - Attaching to window for UMD\r\n window.AICommerceError = require('./client').AICommerceError;\r\n}\r\n"]}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __esm = (fn, res) => function __init() {
|
|
6
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
7
|
+
};
|
|
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
21
|
+
|
|
22
|
+
// src/client.ts
|
|
23
|
+
var client_exports = {};
|
|
24
|
+
__export(client_exports, {
|
|
25
|
+
AICommerce: () => AICommerce,
|
|
26
|
+
AICommerceError: () => AICommerceError
|
|
27
|
+
});
|
|
28
|
+
var AICommerce, AICommerceError;
|
|
29
|
+
var init_client = __esm({
|
|
30
|
+
"src/client.ts"() {
|
|
31
|
+
AICommerce = class _AICommerce {
|
|
32
|
+
constructor(config) {
|
|
33
|
+
this.sessionToken = null;
|
|
34
|
+
if (!config.apiKey) {
|
|
35
|
+
throw new Error("AICommerce: apiKey is required");
|
|
36
|
+
}
|
|
37
|
+
this.apiKey = config.apiKey;
|
|
38
|
+
this.baseUrl = this.normalizeUrl(config.baseUrl || this.detectBaseUrl());
|
|
39
|
+
this.timeout = config.timeout || 3e4;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Detect the base URL based on environment
|
|
43
|
+
*/
|
|
44
|
+
detectBaseUrl() {
|
|
45
|
+
if (typeof window !== "undefined") {
|
|
46
|
+
return window.location.origin;
|
|
47
|
+
}
|
|
48
|
+
return "https://api.aicommerce.dev";
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Normalize URL (remove trailing slash)
|
|
52
|
+
*/
|
|
53
|
+
normalizeUrl(url) {
|
|
54
|
+
return url.replace(/\/$/, "");
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Make an API request
|
|
58
|
+
*/
|
|
59
|
+
async request(endpoint, options = {}) {
|
|
60
|
+
const url = `${this.baseUrl}${endpoint}`;
|
|
61
|
+
const controller = new AbortController();
|
|
62
|
+
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
63
|
+
try {
|
|
64
|
+
const response = await fetch(url, {
|
|
65
|
+
...options,
|
|
66
|
+
signal: controller.signal,
|
|
67
|
+
headers: {
|
|
68
|
+
"Content-Type": "application/json",
|
|
69
|
+
"X-API-Key": this.apiKey,
|
|
70
|
+
...this.sessionToken && { "X-Session-Token": this.sessionToken },
|
|
71
|
+
...options.headers
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
clearTimeout(timeoutId);
|
|
75
|
+
if (!response.ok) {
|
|
76
|
+
const errorData = await response.json().catch(() => ({}));
|
|
77
|
+
const error = {
|
|
78
|
+
code: errorData.code || "UNKNOWN_ERROR",
|
|
79
|
+
message: errorData.message || errorData.error || `HTTP ${response.status}`,
|
|
80
|
+
status: response.status
|
|
81
|
+
};
|
|
82
|
+
throw new AICommerceError(error.message, error.code, error.status);
|
|
83
|
+
}
|
|
84
|
+
return response.json();
|
|
85
|
+
} catch (error) {
|
|
86
|
+
clearTimeout(timeoutId);
|
|
87
|
+
if (error instanceof AICommerceError) {
|
|
88
|
+
throw error;
|
|
89
|
+
}
|
|
90
|
+
if (error instanceof Error && error.name === "AbortError") {
|
|
91
|
+
throw new AICommerceError("Request timeout", "TIMEOUT", 408);
|
|
92
|
+
}
|
|
93
|
+
throw new AICommerceError(
|
|
94
|
+
error instanceof Error ? error.message : "Unknown error",
|
|
95
|
+
"NETWORK_ERROR",
|
|
96
|
+
0
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Send a chat message and get product recommendations
|
|
102
|
+
*
|
|
103
|
+
* @param message - The user's message or full ChatRequest object
|
|
104
|
+
* @param context - Optional context for better recommendations
|
|
105
|
+
* @returns Chat response with AI reply and products
|
|
106
|
+
*
|
|
107
|
+
* @example
|
|
108
|
+
* ```typescript
|
|
109
|
+
* // Simple usage
|
|
110
|
+
* const response = await client.chat('I need running shoes');
|
|
111
|
+
*
|
|
112
|
+
* // With context
|
|
113
|
+
* const response = await client.chat('I need running shoes', {
|
|
114
|
+
* budget: { max: 150 },
|
|
115
|
+
* preferences: ['comfortable', 'lightweight']
|
|
116
|
+
* });
|
|
117
|
+
* ```
|
|
118
|
+
*/
|
|
119
|
+
async chat(message, context) {
|
|
120
|
+
const request = typeof message === "string" ? { message, context, sessionToken: this.sessionToken || void 0 } : { ...message, sessionToken: message.sessionToken || this.sessionToken || void 0 };
|
|
121
|
+
const response = await this.request("/api/v1/chat", {
|
|
122
|
+
method: "POST",
|
|
123
|
+
body: JSON.stringify(request)
|
|
124
|
+
});
|
|
125
|
+
if (response.sessionToken) {
|
|
126
|
+
this.sessionToken = response.sessionToken;
|
|
127
|
+
}
|
|
128
|
+
return response;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Create a new chat session
|
|
132
|
+
*
|
|
133
|
+
* @returns Session information with token
|
|
134
|
+
*/
|
|
135
|
+
async createSession() {
|
|
136
|
+
const response = await this.request("/api/v1/chat/session", {
|
|
137
|
+
method: "POST"
|
|
138
|
+
});
|
|
139
|
+
this.sessionToken = response.session.token;
|
|
140
|
+
return response.session;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Clear the current session
|
|
144
|
+
*/
|
|
145
|
+
clearSession() {
|
|
146
|
+
this.sessionToken = null;
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Get the current session token
|
|
150
|
+
*/
|
|
151
|
+
getSessionToken() {
|
|
152
|
+
return this.sessionToken;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Set a session token (for restoring sessions)
|
|
156
|
+
*/
|
|
157
|
+
setSessionToken(token) {
|
|
158
|
+
this.sessionToken = token;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Static method for one-off chat requests
|
|
162
|
+
*
|
|
163
|
+
* @example
|
|
164
|
+
* ```typescript
|
|
165
|
+
* const response = await AICommerce.quickChat({
|
|
166
|
+
* apiKey: 'your-api-key',
|
|
167
|
+
* message: 'I need a laptop'
|
|
168
|
+
* });
|
|
169
|
+
* ```
|
|
170
|
+
*/
|
|
171
|
+
static async quickChat(options) {
|
|
172
|
+
const client = new _AICommerce({
|
|
173
|
+
apiKey: options.apiKey,
|
|
174
|
+
baseUrl: options.baseUrl
|
|
175
|
+
});
|
|
176
|
+
return client.chat(options.message, options.context);
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
AICommerceError = class _AICommerceError extends Error {
|
|
180
|
+
constructor(message, code, status) {
|
|
181
|
+
super(message);
|
|
182
|
+
this.name = "AICommerceError";
|
|
183
|
+
this.code = code;
|
|
184
|
+
this.status = status;
|
|
185
|
+
Object.setPrototypeOf(this, _AICommerceError.prototype);
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
// src/index.ts
|
|
192
|
+
init_client();
|
|
193
|
+
var VERSION = "1.0.0";
|
|
194
|
+
if (typeof window !== "undefined") {
|
|
195
|
+
window.AICommerce = (init_client(), __toCommonJS(client_exports)).AICommerce;
|
|
196
|
+
window.AICommerceError = (init_client(), __toCommonJS(client_exports)).AICommerceError;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export { AICommerce, AICommerceError, VERSION };
|
|
200
|
+
//# sourceMappingURL=index.mjs.map
|
|
201
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client.ts","../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,IAAA,cAAA,GAAA,EAAA;AAAA,QAAA,CAAA,cAAA,EAAA;AAAA,EAAA,UAAA,EAAA,MAAA,UAAA;AAAA,EAAA,eAAA,EAAA,MAAA;AAAA,CAAA,CAAA;AAAA,IAqBa,UAAA,CAAA,CAkMA;AAvNb,IAAA,WAAA,GAAA,KAAA,CAAA;AAAA,EAAA,eAAA,GAAA;AAqBO,IAAM,UAAA,GAAN,MAAM,WAAA,CAAW;AAAA,MAMpB,YAAY,MAAA,EAA0B;AAFtC,QAAA,IAAA,CAAQ,YAAA,GAA8B,IAAA;AAGlC,QAAA,IAAI,CAAC,OAAO,MAAA,EAAQ;A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AA,CAAW;AAAA,UAC1B,QAAQ,OAAA,CAAQ,MAAA;AAAA,UAChB,SAAS,OAAA,CAAQ;AAAA,SACpB,CAAA;AACD,QAAA,OAAO,MAAA,CAAO,IAAA,CAAK,OAAA,CAAQ,OAAA,EAAS,QAAQ,OAAO,CAAA;AAAA,MACvD;AAAA,KACJ;AAKO,IAAM,eAAA,GAAN,MAAM,gBAAA,SAAwB,KAAA,CAAM;AAAA,MAIvC,WAAA,CAAY,OAAA,EAAiB,IAAA,EAAc,MAAA,EAAgB;AACvD,QAAA,KAAA,CAAM,OAAO,CAAA;AACb,QAAA,IAAA,CAAK,IAAA,GAAO,iBAAA;AACZ,QAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,QAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAGd,QAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,gBAAA,CAAgB,SAAS,CAAA;AAAA,MACzD;AAAA,KACJ;AAAA,EAAA;AAAA,CAAA,CAAA;;;ACpMA,WAAA,EAAA;AAgBO,IAAM,OAAA,GAAU;AAGvB,IAAI,OAAO,WAAW,WAAA,EAAa;AAE/B,EAAA,MAAA,CAAO,aAAa,CAAA,WAAA,EAAA,EAAA,YAAA,CAAA,cAAA,CAAA,EAAoB,UAAA;AAExC,EAAA,MAAA,CAAO,kBAAkB,CAAA,WAAA,EAAA,EAAA,YAAA,CAAA,cAAA,CAAA,EAAoB,eAAA;AACjD","file":"index.mjs","sourcesContent":["import type {\r\n AICommerceConfig,\r\n ChatRequest,\r\n ChatResponse,\r\n ChatContext,\r\n Session,\r\n APIError,\r\n} from './types';\r\n\r\n/**\r\n * AI Commerce SDK Client\r\n * \r\n * @example\r\n * ```typescript\r\n * import { AICommerce } from '@ai-commerce/sdk';\r\n * \r\n * const client = new AICommerce({ apiKey: 'your-api-key' });\r\n * const response = await client.chat('I need a laptop under $1000');\r\n * console.log(response.products);\r\n * ```\r\n */\r\nexport class AICommerce {\r\n private readonly apiKey: string;\r\n private readonly baseUrl: string;\r\n private readonly timeout: number;\r\n private sessionToken: string | null = null;\r\n\r\n constructor(config: AICommerceConfig) {\r\n if (!config.apiKey) {\r\n throw new Error('AICommerce: apiKey is required');\r\n }\r\n\r\n this.apiKey = config.apiKey;\r\n this.baseUrl = this.normalizeUrl(config.baseUrl || this.detectBaseUrl());\r\n this.timeout = config.timeout || 30000;\r\n }\r\n\r\n /**\r\n * Detect the base URL based on environment\r\n */\r\n private detectBaseUrl(): string {\r\n // Browser environment\r\n if (typeof window !== 'undefined') {\r\n return window.location.origin;\r\n }\r\n // Node.js or default\r\n return 'https://api.aicommerce.dev';\r\n }\r\n\r\n /**\r\n * Normalize URL (remove trailing slash)\r\n */\r\n private normalizeUrl(url: string): string {\r\n return url.replace(/\\/$/, '');\r\n }\r\n\r\n /**\r\n * Make an API request\r\n */\r\n private async request<T>(\r\n endpoint: string,\r\n options: RequestInit = {}\r\n ): Promise<T> {\r\n const url = `${this.baseUrl}${endpoint}`;\r\n\r\n const controller = new AbortController();\r\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\r\n\r\n try {\r\n const response = await fetch(url, {\r\n ...options,\r\n signal: controller.signal,\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n 'X-API-Key': this.apiKey,\r\n ...(this.sessionToken && { 'X-Session-Token': this.sessionToken }),\r\n ...options.headers,\r\n },\r\n });\r\n\r\n clearTimeout(timeoutId);\r\n\r\n if (!response.ok) {\r\n const errorData = await response.json().catch(() => ({}));\r\n const error: APIError = {\r\n code: errorData.code || 'UNKNOWN_ERROR',\r\n message: errorData.message || errorData.error || `HTTP ${response.status}`,\r\n status: response.status,\r\n };\r\n throw new AICommerceError(error.message, error.code, error.status);\r\n }\r\n\r\n return response.json();\r\n } catch (error) {\r\n clearTimeout(timeoutId);\r\n\r\n if (error instanceof AICommerceError) {\r\n throw error;\r\n }\r\n\r\n if (error instanceof Error && error.name === 'AbortError') {\r\n throw new AICommerceError('Request timeout', 'TIMEOUT', 408);\r\n }\r\n\r\n throw new AICommerceError(\r\n error instanceof Error ? error.message : 'Unknown error',\r\n 'NETWORK_ERROR',\r\n 0\r\n );\r\n }\r\n }\r\n\r\n /**\r\n * Send a chat message and get product recommendations\r\n * \r\n * @param message - The user's message or full ChatRequest object\r\n * @param context - Optional context for better recommendations\r\n * @returns Chat response with AI reply and products\r\n * \r\n * @example\r\n * ```typescript\r\n * // Simple usage\r\n * const response = await client.chat('I need running shoes');\r\n * \r\n * // With context\r\n * const response = await client.chat('I need running shoes', {\r\n * budget: { max: 150 },\r\n * preferences: ['comfortable', 'lightweight']\r\n * });\r\n * ```\r\n */\r\n async chat(\r\n message: string | ChatRequest,\r\n context?: ChatContext\r\n ): Promise<ChatResponse> {\r\n const request: ChatRequest = typeof message === 'string'\r\n ? { message, context, sessionToken: this.sessionToken || undefined }\r\n : { ...message, sessionToken: message.sessionToken || this.sessionToken || undefined };\r\n\r\n const response = await this.request<ChatResponse>('/api/v1/chat', {\r\n method: 'POST',\r\n body: JSON.stringify(request),\r\n });\r\n\r\n // Store session token for follow-up messages\r\n if (response.sessionToken) {\r\n this.sessionToken = response.sessionToken;\r\n }\r\n\r\n return response;\r\n }\r\n\r\n /**\r\n * Create a new chat session\r\n * \r\n * @returns Session information with token\r\n */\r\n async createSession(): Promise<Session> {\r\n const response = await this.request<{ session: Session }>('/api/v1/chat/session', {\r\n method: 'POST',\r\n });\r\n\r\n this.sessionToken = response.session.token;\r\n return response.session;\r\n }\r\n\r\n /**\r\n * Clear the current session\r\n */\r\n clearSession(): void {\r\n this.sessionToken = null;\r\n }\r\n\r\n /**\r\n * Get the current session token\r\n */\r\n getSessionToken(): string | null {\r\n return this.sessionToken;\r\n }\r\n\r\n /**\r\n * Set a session token (for restoring sessions)\r\n */\r\n setSessionToken(token: string): void {\r\n this.sessionToken = token;\r\n }\r\n\r\n /**\r\n * Static method for one-off chat requests\r\n * \r\n * @example\r\n * ```typescript\r\n * const response = await AICommerce.quickChat({\r\n * apiKey: 'your-api-key',\r\n * message: 'I need a laptop'\r\n * });\r\n * ```\r\n */\r\n static async quickChat(options: {\r\n apiKey: string;\r\n message: string;\r\n baseUrl?: string;\r\n context?: ChatContext;\r\n }): Promise<ChatResponse> {\r\n const client = new AICommerce({\r\n apiKey: options.apiKey,\r\n baseUrl: options.baseUrl,\r\n });\r\n return client.chat(options.message, options.context);\r\n }\r\n}\r\n\r\n/**\r\n * Custom error class for AI Commerce SDK\r\n */\r\nexport class AICommerceError extends Error {\r\n readonly code: string;\r\n readonly status: number;\r\n\r\n constructor(message: string, code: string, status: number) {\r\n super(message);\r\n this.name = 'AICommerceError';\r\n this.code = code;\r\n this.status = status;\r\n\r\n // Maintain proper prototype chain\r\n Object.setPrototypeOf(this, AICommerceError.prototype);\r\n }\r\n}\r\n","/**\r\n * AI Commerce SDK\r\n * \r\n * AI-powered product recommendations for e-commerce\r\n * \r\n * @packageDocumentation\r\n * @module @ai-commerce/sdk\r\n * \r\n * @example\r\n * ```typescript\r\n * // npm usage\r\n * import { AICommerce } from '@ai-commerce/sdk';\r\n * \r\n * const client = new AICommerce({ apiKey: 'your-api-key' });\r\n * const response = await client.chat('I need a laptop');\r\n * console.log(response.products);\r\n * ```\r\n * \r\n * @example\r\n * ```html\r\n * <!-- Script tag usage -->\r\n * <script src=\"https://cdn.aicommerce.dev/sdk.min.js\"></script>\r\n * <script>\r\n * const client = new AICommerce({ apiKey: 'your-api-key' });\r\n * client.chat('I need a laptop').then(response => {\r\n * console.log(response.products);\r\n * });\r\n * </script>\r\n * ```\r\n */\r\n\r\n// Export main client\r\nexport { AICommerce, AICommerceError } from './client';\r\n\r\n// Export all types\r\nexport type {\r\n AICommerceConfig,\r\n ChatRequest,\r\n ChatResponse,\r\n ChatContext,\r\n Product,\r\n Session,\r\n APIError,\r\n EventType,\r\n EventCallback,\r\n} from './types';\r\n\r\n// Version\r\nexport const VERSION = '1.0.0';\r\n\r\n// For UMD builds, attach to window\r\nif (typeof window !== 'undefined') {\r\n // @ts-expect-error - Attaching to window for UMD\r\n window.AICommerce = require('./client').AICommerce;\r\n // @ts-expect-error - Attaching to window for UMD\r\n window.AICommerceError = require('./client').AICommerceError;\r\n}\r\n"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@yassirbenmoussa/aicommerce-sdk",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "AI Commerce SDK - AI-powered product recommendations for e-commerce",
|
|
5
|
+
"author": "AI Commerce",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"main": "dist/index.cjs",
|
|
8
|
+
"module": "dist/index.mjs",
|
|
9
|
+
"browser": "dist/ai-commerce.min.js",
|
|
10
|
+
"types": "dist/index.d.ts",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"import": "./dist/index.mjs",
|
|
14
|
+
"require": "./dist/index.cjs",
|
|
15
|
+
"browser": "./dist/ai-commerce.min.js",
|
|
16
|
+
"types": "./dist/index.d.ts"
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"dist",
|
|
21
|
+
"README.md"
|
|
22
|
+
],
|
|
23
|
+
"scripts": {
|
|
24
|
+
"build": "tsup",
|
|
25
|
+
"dev": "tsup --watch",
|
|
26
|
+
"typecheck": "tsc --noEmit",
|
|
27
|
+
"clean": "rimraf dist"
|
|
28
|
+
},
|
|
29
|
+
"keywords": [
|
|
30
|
+
"ai",
|
|
31
|
+
"commerce",
|
|
32
|
+
"ecommerce",
|
|
33
|
+
"product-recommendations",
|
|
34
|
+
"chatbot",
|
|
35
|
+
"ai-assistant"
|
|
36
|
+
],
|
|
37
|
+
"repository": {
|
|
38
|
+
"type": "git",
|
|
39
|
+
"url": "https://github.com/your-org/ai-commerce"
|
|
40
|
+
},
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"tsup": "^8.0.0",
|
|
43
|
+
"typescript": "^5.3.0",
|
|
44
|
+
"rimraf": "^5.0.0"
|
|
45
|
+
},
|
|
46
|
+
"peerDependencies": {},
|
|
47
|
+
"engines": {
|
|
48
|
+
"node": ">=16"
|
|
49
|
+
}
|
|
50
|
+
}
|