@zorveus/sdk 0.1.9 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +85 -11
- package/dist/adapters/openai.d.mts +33 -0
- package/dist/adapters/openai.d.ts +33 -0
- package/dist/adapters/openai.js +384 -0
- package/dist/adapters/openai.js.map +1 -0
- package/dist/adapters/openai.mjs +95 -0
- package/dist/adapters/openai.mjs.map +1 -0
- package/dist/adapters/vercel.d.mts +24 -0
- package/dist/adapters/vercel.d.ts +24 -0
- package/dist/adapters/vercel.js +336 -0
- package/dist/adapters/vercel.js.map +1 -0
- package/dist/adapters/vercel.mjs +57 -0
- package/dist/adapters/vercel.mjs.map +1 -0
- package/dist/chunk-6SPZ5W5D.mjs +285 -0
- package/dist/chunk-6SPZ5W5D.mjs.map +1 -0
- package/dist/index.d.mts +101 -285
- package/dist/index.d.ts +101 -285
- package/dist/index.js +212 -25
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +115 -178
- package/dist/index.mjs.map +1 -1
- package/dist/zorveus-error-DbltWNhC.d.mts +347 -0
- package/dist/zorveus-error-DbltWNhC.d.ts +347 -0
- package/package.json +57 -1
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import {
|
|
2
|
+
parseZorveusGatewayError
|
|
3
|
+
} from "../chunk-6SPZ5W5D.mjs";
|
|
4
|
+
|
|
5
|
+
// src/adapters/openai.ts
|
|
6
|
+
import OpenAI from "openai";
|
|
7
|
+
var ZorveusOpenAI = class extends OpenAI {
|
|
8
|
+
defaultExternalUserId;
|
|
9
|
+
defaultProductEndUserId;
|
|
10
|
+
defaultDisplayName;
|
|
11
|
+
defaultUserEmail;
|
|
12
|
+
defaultUserMetadata;
|
|
13
|
+
defaultAppId;
|
|
14
|
+
defaultMetadata;
|
|
15
|
+
constructor(options = {}) {
|
|
16
|
+
const apiKey = options.apiKey ?? process.env.ZORVEUS_INFERENCE_KEY;
|
|
17
|
+
if (!apiKey) {
|
|
18
|
+
throw new Error("Zorveus API key is required. Set ZORVEUS_INFERENCE_KEY or pass apiKey.");
|
|
19
|
+
}
|
|
20
|
+
const {
|
|
21
|
+
externalUserId,
|
|
22
|
+
productEndUserId,
|
|
23
|
+
displayName,
|
|
24
|
+
userEmail,
|
|
25
|
+
email,
|
|
26
|
+
userMetadata,
|
|
27
|
+
appId,
|
|
28
|
+
metadata,
|
|
29
|
+
baseURL,
|
|
30
|
+
defaultHeaders,
|
|
31
|
+
...restOptions
|
|
32
|
+
} = options;
|
|
33
|
+
super({
|
|
34
|
+
apiKey,
|
|
35
|
+
baseURL: baseURL ?? process.env.ZORVEUS_GATEWAY_URL ?? "https://api.zorveus.com/v1",
|
|
36
|
+
defaultHeaders,
|
|
37
|
+
...restOptions
|
|
38
|
+
});
|
|
39
|
+
this.defaultExternalUserId = externalUserId;
|
|
40
|
+
this.defaultProductEndUserId = productEndUserId;
|
|
41
|
+
this.defaultDisplayName = displayName;
|
|
42
|
+
this.defaultUserEmail = userEmail || email;
|
|
43
|
+
this.defaultUserMetadata = userMetadata;
|
|
44
|
+
this.defaultAppId = appId;
|
|
45
|
+
this.defaultMetadata = metadata;
|
|
46
|
+
const buildMetadata = (body) => {
|
|
47
|
+
const extId = body?.user ?? body?.external_user_id ?? this.defaultExternalUserId;
|
|
48
|
+
const prodUserId = body?.product_end_user_id ?? body?.metadata?.product_end_user_id ?? this.defaultProductEndUserId;
|
|
49
|
+
const dName = body?.display_name ?? this.defaultDisplayName;
|
|
50
|
+
const uEmail = body?.user_email ?? body?.email ?? this.defaultUserEmail;
|
|
51
|
+
const uMeta = body?.user_metadata ?? this.defaultUserMetadata;
|
|
52
|
+
const aId = body?.app_id ?? this.defaultAppId;
|
|
53
|
+
const productUser = {
|
|
54
|
+
...dName ? { display_name: dName } : {},
|
|
55
|
+
...uEmail ? { email: uEmail } : {},
|
|
56
|
+
...uMeta ? { metadata: uMeta } : {},
|
|
57
|
+
...body?.metadata?.product_user
|
|
58
|
+
};
|
|
59
|
+
const merged = {
|
|
60
|
+
...extId ? { external_user_id: extId } : {},
|
|
61
|
+
...prodUserId ? { product_end_user_id: prodUserId } : {},
|
|
62
|
+
...aId ? { app_id: aId } : {},
|
|
63
|
+
...Object.keys(productUser).length > 0 ? { product_user: productUser } : {},
|
|
64
|
+
...this.defaultMetadata,
|
|
65
|
+
...body?.metadata
|
|
66
|
+
};
|
|
67
|
+
return Object.keys(merged).length > 0 ? merged : void 0;
|
|
68
|
+
};
|
|
69
|
+
const originalCreate = this.chat.completions.create.bind(this.chat.completions);
|
|
70
|
+
this.chat.completions.create = ((body, requestOptions) => {
|
|
71
|
+
const mergedMetadata = buildMetadata(body);
|
|
72
|
+
const updatedBody = {
|
|
73
|
+
...body,
|
|
74
|
+
...mergedMetadata ? { metadata: mergedMetadata } : {}
|
|
75
|
+
};
|
|
76
|
+
return originalCreate(updatedBody, requestOptions);
|
|
77
|
+
});
|
|
78
|
+
if (this.responses && typeof this.responses.create === "function") {
|
|
79
|
+
const originalResponsesCreate = this.responses.create.bind(this.responses);
|
|
80
|
+
this.responses.create = ((body, requestOptions) => {
|
|
81
|
+
const mergedMetadata = buildMetadata(body);
|
|
82
|
+
const updatedBody = {
|
|
83
|
+
...body,
|
|
84
|
+
...mergedMetadata ? { metadata: mergedMetadata } : {}
|
|
85
|
+
};
|
|
86
|
+
return originalResponsesCreate(updatedBody, requestOptions);
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
export {
|
|
92
|
+
ZorveusOpenAI,
|
|
93
|
+
parseZorveusGatewayError
|
|
94
|
+
};
|
|
95
|
+
//# sourceMappingURL=openai.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/openai.ts"],"sourcesContent":["import OpenAI from \"openai\";\nexport { parseZorveusGatewayError } from \"../errors/zorveus-error\";\n\nexport interface ZorveusOpenAIOptions {\n apiKey?: string;\n baseURL?: string;\n externalUserId?: string;\n productEndUserId?: string;\n displayName?: string;\n userEmail?: string;\n email?: string;\n userMetadata?: Record<string, unknown>;\n appId?: string;\n metadata?: Record<string, unknown>;\n defaultHeaders?: Record<string, string>;\n [key: string]: unknown;\n}\n\n/**\n * ZorveusOpenAI wraps the official OpenAI SDK client, automatically injecting\n * metadata (external_user_id, product_end_user_id, and product_user attribution) into request payloads.\n */\nexport class ZorveusOpenAI extends OpenAI {\n private readonly defaultExternalUserId?: string;\n private readonly defaultProductEndUserId?: string;\n private readonly defaultDisplayName?: string;\n private readonly defaultUserEmail?: string;\n private readonly defaultUserMetadata?: Record<string, unknown>;\n private readonly defaultAppId?: string;\n private readonly defaultMetadata?: Record<string, unknown>;\n\n constructor(options: ZorveusOpenAIOptions = {}) {\n const apiKey = options.apiKey ?? process.env.ZORVEUS_INFERENCE_KEY;\n if (!apiKey) {\n throw new Error(\"Zorveus API key is required. Set ZORVEUS_INFERENCE_KEY or pass apiKey.\");\n }\n\n const {\n externalUserId,\n productEndUserId,\n displayName,\n userEmail,\n email,\n userMetadata,\n appId,\n metadata,\n baseURL,\n defaultHeaders,\n ...restOptions\n } = options;\n\n super({\n apiKey,\n baseURL: baseURL ?? process.env.ZORVEUS_GATEWAY_URL ?? \"https://api.zorveus.com/v1\",\n defaultHeaders,\n ...restOptions\n });\n\n this.defaultExternalUserId = externalUserId;\n this.defaultProductEndUserId = productEndUserId;\n this.defaultDisplayName = displayName;\n this.defaultUserEmail = userEmail || email;\n this.defaultUserMetadata = userMetadata;\n this.defaultAppId = appId;\n this.defaultMetadata = metadata;\n\n const buildMetadata = (body: any) => {\n const extId = body?.user ?? body?.external_user_id ?? this.defaultExternalUserId;\n const prodUserId =\n body?.product_end_user_id ??\n body?.metadata?.product_end_user_id ??\n this.defaultProductEndUserId;\n const dName = body?.display_name ?? this.defaultDisplayName;\n const uEmail = body?.user_email ?? body?.email ?? this.defaultUserEmail;\n const uMeta = body?.user_metadata ?? this.defaultUserMetadata;\n const aId = body?.app_id ?? this.defaultAppId;\n\n const productUser = {\n ...(dName ? { display_name: dName } : {}),\n ...(uEmail ? { email: uEmail } : {}),\n ...(uMeta ? { metadata: uMeta } : {}),\n ...body?.metadata?.product_user\n };\n\n const merged = {\n ...(extId ? { external_user_id: extId } : {}),\n ...(prodUserId ? { product_end_user_id: prodUserId } : {}),\n ...(aId ? { app_id: aId } : {}),\n ...(Object.keys(productUser).length > 0 ? { product_user: productUser } : {}),\n ...this.defaultMetadata,\n ...body?.metadata\n };\n\n return Object.keys(merged).length > 0 ? merged : undefined;\n };\n\n const originalCreate = this.chat.completions.create.bind(this.chat.completions);\n\n this.chat.completions.create = ((body: any, requestOptions?: any) => {\n const mergedMetadata = buildMetadata(body);\n const updatedBody = {\n ...body,\n ...(mergedMetadata ? { metadata: mergedMetadata } : {})\n };\n\n return originalCreate(updatedBody, requestOptions);\n }) as any;\n\n if (this.responses && typeof (this.responses as any).create === \"function\") {\n const originalResponsesCreate = (this.responses as any).create.bind(this.responses);\n\n (this.responses as any).create = ((body: any, requestOptions?: any) => {\n const mergedMetadata = buildMetadata(body);\n const updatedBody = {\n ...body,\n ...(mergedMetadata ? { metadata: mergedMetadata } : {})\n };\n\n return originalResponsesCreate(updatedBody, requestOptions);\n }) as any;\n }\n }\n}\n"],"mappings":";;;;;AAAA,OAAO,YAAY;AAsBZ,IAAM,gBAAN,cAA4B,OAAO;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEjB,YAAY,UAAgC,CAAC,GAAG;AAC9C,UAAM,SAAS,QAAQ,UAAU,QAAQ,IAAI;AAC7C,QAAI,CAAC,QAAQ;AACX,YAAM,IAAI,MAAM,wEAAwE;AAAA,IAC1F;AAEA,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,GAAG;AAAA,IACL,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AK,YAAY,OAAO,KAAK,KAAK,KAAK,WAAW;AAE9E,SAAK,KAAK,YAAY,UAAU,CAAC,MAAW,mBAAyB;AACnE,YAAM,iBAAiB,cAAc,IAAI;AACzC,YAAM,cAAc;AAAA,QAClB,GAAG;AAAA,QACH,GAAI,iBAAiB,EAAE,UAAU,eAAe,IAAI,CAAC;AAAA,MACvD;AAEA,aAAO,eAAe,aAAa,cAAc;AAAA,IACnD;AAEA,QAAI,KAAK,aAAa,OAAQ,KAAK,UAAkB,WAAW,YAAY;AAC1E,YAAM,0BAA2B,KAAK,UAAkB,OAAO,KAAK,KAAK,SAAS;AAElF,MAAC,KAAK,UAAkB,UAAU,CAAC,MAAW,mBAAyB;AACrE,cAAM,iBAAiB,cAAc,IAAI;AACzC,cAAM,cAAc;AAAA,UAClB,GAAG;AAAA,UACH,GAAI,iBAAiB,EAAE,UAAU,eAAe,IAAI,CAAC;AAAA,QACvD;AAEA,eAAO,wBAAwB,aAAa,cAAc;AAAA,MAC5D;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { OpenAIProvider } from '@ai-sdk/openai';
|
|
2
|
+
export { p as parseZorveusGatewayError } from '../zorveus-error-DbltWNhC.mjs';
|
|
3
|
+
|
|
4
|
+
interface ZorveusVercelOptions {
|
|
5
|
+
apiKey?: string;
|
|
6
|
+
baseURL?: string;
|
|
7
|
+
externalUserId?: string;
|
|
8
|
+
productEndUserId?: string;
|
|
9
|
+
displayName?: string;
|
|
10
|
+
userEmail?: string;
|
|
11
|
+
email?: string;
|
|
12
|
+
userMetadata?: Record<string, unknown>;
|
|
13
|
+
appId?: string;
|
|
14
|
+
metadata?: Record<string, unknown>;
|
|
15
|
+
headers?: Record<string, string>;
|
|
16
|
+
fetch?: typeof globalThis.fetch;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Creates a Vercel AI SDK provider instance configured for Zorveus AI Gateway,
|
|
20
|
+
* automatically injecting metadata (external_user_id, product_end_user_id, and product_user attribution) into request payloads.
|
|
21
|
+
*/
|
|
22
|
+
declare function createZorveus(options?: ZorveusVercelOptions): OpenAIProvider;
|
|
23
|
+
|
|
24
|
+
export { type ZorveusVercelOptions, createZorveus };
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { OpenAIProvider } from '@ai-sdk/openai';
|
|
2
|
+
export { p as parseZorveusGatewayError } from '../zorveus-error-DbltWNhC.js';
|
|
3
|
+
|
|
4
|
+
interface ZorveusVercelOptions {
|
|
5
|
+
apiKey?: string;
|
|
6
|
+
baseURL?: string;
|
|
7
|
+
externalUserId?: string;
|
|
8
|
+
productEndUserId?: string;
|
|
9
|
+
displayName?: string;
|
|
10
|
+
userEmail?: string;
|
|
11
|
+
email?: string;
|
|
12
|
+
userMetadata?: Record<string, unknown>;
|
|
13
|
+
appId?: string;
|
|
14
|
+
metadata?: Record<string, unknown>;
|
|
15
|
+
headers?: Record<string, string>;
|
|
16
|
+
fetch?: typeof globalThis.fetch;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Creates a Vercel AI SDK provider instance configured for Zorveus AI Gateway,
|
|
20
|
+
* automatically injecting metadata (external_user_id, product_end_user_id, and product_user attribution) into request payloads.
|
|
21
|
+
*/
|
|
22
|
+
declare function createZorveus(options?: ZorveusVercelOptions): OpenAIProvider;
|
|
23
|
+
|
|
24
|
+
export { type ZorveusVercelOptions, createZorveus };
|
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/adapters/vercel.ts
|
|
21
|
+
var vercel_exports = {};
|
|
22
|
+
__export(vercel_exports, {
|
|
23
|
+
createZorveus: () => createZorveus,
|
|
24
|
+
parseZorveusGatewayError: () => parseZorveusGatewayError
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(vercel_exports);
|
|
27
|
+
var import_openai = require("@ai-sdk/openai");
|
|
28
|
+
|
|
29
|
+
// src/errors/zorveus-error.ts
|
|
30
|
+
var ZorveusError = class extends Error {
|
|
31
|
+
status;
|
|
32
|
+
code;
|
|
33
|
+
param;
|
|
34
|
+
type;
|
|
35
|
+
params;
|
|
36
|
+
headers;
|
|
37
|
+
rawBody;
|
|
38
|
+
constructor(message, options = {}) {
|
|
39
|
+
super(message);
|
|
40
|
+
this.name = "ZorveusError";
|
|
41
|
+
this.status = options.status;
|
|
42
|
+
this.code = options.code;
|
|
43
|
+
this.param = options.param;
|
|
44
|
+
this.type = options.type;
|
|
45
|
+
this.params = options.params;
|
|
46
|
+
this.headers = options.headers;
|
|
47
|
+
this.rawBody = options.rawBody;
|
|
48
|
+
if (options.cause) {
|
|
49
|
+
this.cause = options.cause;
|
|
50
|
+
}
|
|
51
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
var APIStatusError = class extends ZorveusError {
|
|
55
|
+
constructor(message, options) {
|
|
56
|
+
super(message, options);
|
|
57
|
+
this.name = "APIStatusError";
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
var AuthenticationError = class extends APIStatusError {
|
|
61
|
+
constructor(message = "Invalid or expired Zorveus credentials", options = {}) {
|
|
62
|
+
super(message, { ...options, status: options.status ?? 401 });
|
|
63
|
+
this.name = "AuthenticationError";
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
var PermissionDeniedError = class extends APIStatusError {
|
|
67
|
+
constructor(message = "Permission denied for this operation or model", options = {}) {
|
|
68
|
+
super(message, { ...options, status: options.status ?? 403 });
|
|
69
|
+
this.name = "PermissionDeniedError";
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
var NotFoundError = class extends APIStatusError {
|
|
73
|
+
constructor(message = "Resource not found", options = {}) {
|
|
74
|
+
super(message, { ...options, status: options.status ?? 404 });
|
|
75
|
+
this.name = "NotFoundError";
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
var UnprocessableEntityError = class extends APIStatusError {
|
|
79
|
+
constructor(message = "Request validation failed", options = {}) {
|
|
80
|
+
super(message, { ...options, status: options.status ?? 422 });
|
|
81
|
+
this.name = "UnprocessableEntityError";
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
var RateLimitError = class extends APIStatusError {
|
|
85
|
+
constructor(message = "Rate limit exceeded. Please retry after some time.", options = {}) {
|
|
86
|
+
super(message, { ...options, status: options.status ?? 429 });
|
|
87
|
+
this.name = "RateLimitError";
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
var InternalServerError = class extends APIStatusError {
|
|
91
|
+
constructor(message = "Zorveus internal server error", options = {}) {
|
|
92
|
+
super(message, { ...options, status: options.status ?? 500 });
|
|
93
|
+
this.name = "InternalServerError";
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
var ZorveusBusinessError = class extends APIStatusError {
|
|
97
|
+
constructor(message, options) {
|
|
98
|
+
super(message, options);
|
|
99
|
+
this.name = "ZorveusBusinessError";
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
var InsufficientFundsError = class extends ZorveusBusinessError {
|
|
103
|
+
constructor(message = "Wallet balance exhausted. Top up required.", options = {}) {
|
|
104
|
+
super(message, {
|
|
105
|
+
...options,
|
|
106
|
+
status: options.status ?? 402,
|
|
107
|
+
code: options.code ?? "zorveus_reservation_insufficient_balance"
|
|
108
|
+
});
|
|
109
|
+
this.name = "InsufficientFundsError";
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
var CapExceededError = class extends ZorveusBusinessError {
|
|
113
|
+
constructor(message = "Spending cap limit reached", options = {}) {
|
|
114
|
+
super(message, {
|
|
115
|
+
...options,
|
|
116
|
+
status: options.status ?? 403,
|
|
117
|
+
code: options.code ?? "zorveus_cap_exceeded"
|
|
118
|
+
});
|
|
119
|
+
this.name = "CapExceededError";
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
var ProductUserAllowanceInsufficientError = class extends ZorveusBusinessError {
|
|
123
|
+
constructor(message = "Product user AI allowance is insufficient for this request.", options = {}) {
|
|
124
|
+
super(message, {
|
|
125
|
+
...options,
|
|
126
|
+
status: options.status ?? 403,
|
|
127
|
+
code: options.code ?? "zorveus_product_user_allowance_insufficient",
|
|
128
|
+
params: options.params
|
|
129
|
+
});
|
|
130
|
+
this.name = "ProductUserAllowanceInsufficientError";
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
var CreditGrantExpiredError = class extends ZorveusBusinessError {
|
|
134
|
+
constructor(message = "Product user credit grant has expired", options = {}) {
|
|
135
|
+
super(message, {
|
|
136
|
+
...options,
|
|
137
|
+
status: options.status ?? 403,
|
|
138
|
+
code: options.code ?? "credit_grant_expired"
|
|
139
|
+
});
|
|
140
|
+
this.name = "CreditGrantExpiredError";
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
var AppConnectionNotFoundError = class extends ZorveusBusinessError {
|
|
144
|
+
constructor(message = "Inference key or app connection not found or revoked", options = {}) {
|
|
145
|
+
super(message, {
|
|
146
|
+
...options,
|
|
147
|
+
status: options.status ?? 403,
|
|
148
|
+
code: options.code ?? "zorveus_app_connection_not_found"
|
|
149
|
+
});
|
|
150
|
+
this.name = "AppConnectionNotFoundError";
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
var ReservationConflictError = class extends ZorveusBusinessError {
|
|
154
|
+
constructor(message = "Idempotency key reused with conflicting request parameters", options = {}) {
|
|
155
|
+
super(message, {
|
|
156
|
+
...options,
|
|
157
|
+
status: options.status ?? 409,
|
|
158
|
+
code: options.code ?? "zorveus_reservation_conflict"
|
|
159
|
+
});
|
|
160
|
+
this.name = "ReservationConflictError";
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
function createAPIError(status, body, headers) {
|
|
164
|
+
let message = `Request failed with status ${status}`;
|
|
165
|
+
let code;
|
|
166
|
+
let param;
|
|
167
|
+
let type;
|
|
168
|
+
let params;
|
|
169
|
+
let parsedBody = body;
|
|
170
|
+
if (typeof body === "string") {
|
|
171
|
+
try {
|
|
172
|
+
parsedBody = JSON.parse(body);
|
|
173
|
+
} catch {
|
|
174
|
+
try {
|
|
175
|
+
parsedBody = JSON.parse(body.replace(/'/g, '"'));
|
|
176
|
+
} catch {
|
|
177
|
+
const codeMatch = body.match(/['"]code['"]\s*:\s*['"]([^'"]+)['"]/);
|
|
178
|
+
const msgMatch = body.match(/['"]message['"]\s*:\s*['"]([^'"]+)['"]/);
|
|
179
|
+
if (msgMatch?.[1]) message = msgMatch[1];
|
|
180
|
+
if (codeMatch?.[1]) code = codeMatch[1];
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
if (parsedBody && typeof parsedBody === "object") {
|
|
185
|
+
const obj = parsedBody;
|
|
186
|
+
const providerFields = obj.provider_specific_fields ?? obj.error?.provider_specific_fields;
|
|
187
|
+
const nestedGatewayError = providerFields?.error ?? providerFields;
|
|
188
|
+
if (nestedGatewayError && typeof nestedGatewayError === "object") {
|
|
189
|
+
if (typeof nestedGatewayError.message === "string") message = nestedGatewayError.message;
|
|
190
|
+
if (typeof nestedGatewayError.code === "string") code = nestedGatewayError.code;
|
|
191
|
+
if (typeof nestedGatewayError.param === "string") param = nestedGatewayError.param;
|
|
192
|
+
if (typeof nestedGatewayError.type === "string") type = nestedGatewayError.type;
|
|
193
|
+
if (nestedGatewayError.params && typeof nestedGatewayError.params === "object") {
|
|
194
|
+
params = nestedGatewayError.params;
|
|
195
|
+
}
|
|
196
|
+
} else if (obj.error && typeof obj.error === "object") {
|
|
197
|
+
const err = obj.error;
|
|
198
|
+
if (typeof err.message === "string") message = err.message;
|
|
199
|
+
if (typeof err.code === "string") code = err.code;
|
|
200
|
+
if (typeof err.param === "string") param = err.param;
|
|
201
|
+
if (typeof err.type === "string") type = err.type;
|
|
202
|
+
if (err.params && typeof err.params === "object") {
|
|
203
|
+
params = err.params;
|
|
204
|
+
}
|
|
205
|
+
} else {
|
|
206
|
+
if (typeof obj.message === "string") message = obj.message;
|
|
207
|
+
if (typeof obj.code === "string") code = obj.code;
|
|
208
|
+
if (typeof obj.param === "string") param = obj.param;
|
|
209
|
+
if (typeof obj.type === "string") type = obj.type;
|
|
210
|
+
if (obj.params && typeof obj.params === "object") {
|
|
211
|
+
params = obj.params;
|
|
212
|
+
}
|
|
213
|
+
if (typeof obj.detail === "string") {
|
|
214
|
+
message = obj.detail;
|
|
215
|
+
} else if (Array.isArray(obj.detail) && obj.detail.length > 0) {
|
|
216
|
+
const first = obj.detail[0];
|
|
217
|
+
if (first && typeof first.msg === "string") {
|
|
218
|
+
message = first.msg;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
const options = { status, code, param, type, params, headers, rawBody: body };
|
|
224
|
+
const normalizedCode = (code || "").toLowerCase();
|
|
225
|
+
if (normalizedCode === "zorveus_product_user_allowance_insufficient" || normalizedCode === "zorveus_product_user_credits_insufficient" || normalizedCode.includes("allowance_insufficient") || normalizedCode.includes("credits_insufficient") || message.toLowerCase().includes("allowance remaining")) {
|
|
226
|
+
return new ProductUserAllowanceInsufficientError(message, {
|
|
227
|
+
...options,
|
|
228
|
+
status: status === 200 ? 403 : status,
|
|
229
|
+
params
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
if (normalizedCode === "zorveus_cap_exceeded" || normalizedCode.includes("cap_exceed") || normalizedCode.includes("spend_cap") || message.toLowerCase().includes("spending cap")) {
|
|
233
|
+
return new CapExceededError(message, options);
|
|
234
|
+
}
|
|
235
|
+
if (normalizedCode === "zorveus_app_connection_not_found" || normalizedCode.includes("app_connection_not_found")) {
|
|
236
|
+
return new AppConnectionNotFoundError(message, options);
|
|
237
|
+
}
|
|
238
|
+
if (status === 409 || normalizedCode === "zorveus_reservation_conflict" || normalizedCode.includes("reservation_conflict")) {
|
|
239
|
+
return new ReservationConflictError(message, options);
|
|
240
|
+
}
|
|
241
|
+
if (status === 402 || normalizedCode === "zorveus_reservation_insufficient_balance" || normalizedCode.includes("insufficient_funds") || normalizedCode.includes("balance_exhausted") || normalizedCode.includes("insufficient_balance") || normalizedCode.includes("wallet_empty") || message.toLowerCase().includes("insufficient funds") || message.toLowerCase().includes("balance exhausted") || message.toLowerCase().includes("wallet is empty")) {
|
|
242
|
+
return new InsufficientFundsError(message, options);
|
|
243
|
+
}
|
|
244
|
+
if (normalizedCode.includes("grant_expired")) {
|
|
245
|
+
return new CreditGrantExpiredError(message, options);
|
|
246
|
+
}
|
|
247
|
+
if (status === 401) {
|
|
248
|
+
return new AuthenticationError(message, options);
|
|
249
|
+
}
|
|
250
|
+
if (status === 403) {
|
|
251
|
+
return new PermissionDeniedError(message, options);
|
|
252
|
+
}
|
|
253
|
+
if (status === 404) {
|
|
254
|
+
return new NotFoundError(message, options);
|
|
255
|
+
}
|
|
256
|
+
if (status === 422) {
|
|
257
|
+
return new UnprocessableEntityError(message, options);
|
|
258
|
+
}
|
|
259
|
+
if (status === 429) {
|
|
260
|
+
return new RateLimitError(message, options);
|
|
261
|
+
}
|
|
262
|
+
if (status >= 500) {
|
|
263
|
+
return new InternalServerError(message, options);
|
|
264
|
+
}
|
|
265
|
+
return new APIStatusError(message, options);
|
|
266
|
+
}
|
|
267
|
+
function parseZorveusGatewayError(error) {
|
|
268
|
+
if (error instanceof ZorveusError) {
|
|
269
|
+
return error;
|
|
270
|
+
}
|
|
271
|
+
if (!error || typeof error !== "object") {
|
|
272
|
+
return error;
|
|
273
|
+
}
|
|
274
|
+
const errObj = error;
|
|
275
|
+
const status = typeof errObj.status === "number" ? errObj.status : typeof errObj.statusCode === "number" ? errObj.statusCode : void 0;
|
|
276
|
+
const rawBody = errObj.error ?? errObj.body ?? errObj.rawBody;
|
|
277
|
+
if (status !== void 0 && rawBody !== void 0) {
|
|
278
|
+
const headers = errObj.headers && typeof errObj.headers === "object" ? errObj.headers : void 0;
|
|
279
|
+
return createAPIError(status, rawBody, headers);
|
|
280
|
+
}
|
|
281
|
+
return error;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// src/adapters/vercel.ts
|
|
285
|
+
function createZorveus(options = {}) {
|
|
286
|
+
const apiKey = options.apiKey ?? process.env.ZORVEUS_INFERENCE_KEY;
|
|
287
|
+
if (!apiKey) {
|
|
288
|
+
throw new Error("Zorveus API key is required. Set ZORVEUS_INFERENCE_KEY or pass apiKey.");
|
|
289
|
+
}
|
|
290
|
+
const baseFetch = options.fetch ?? globalThis.fetch;
|
|
291
|
+
const customFetch = async (url, init) => {
|
|
292
|
+
if (init?.body && typeof init.body === "string") {
|
|
293
|
+
try {
|
|
294
|
+
const bodyObj = JSON.parse(init.body);
|
|
295
|
+
const extId = bodyObj.user ?? bodyObj.external_user_id ?? options.externalUserId;
|
|
296
|
+
const prodUserId = bodyObj.product_end_user_id ?? bodyObj.metadata?.product_end_user_id ?? options.productEndUserId;
|
|
297
|
+
const dName = bodyObj.display_name ?? options.displayName;
|
|
298
|
+
const uEmail = bodyObj.user_email ?? bodyObj.email ?? options.userEmail ?? options.email;
|
|
299
|
+
const uMeta = bodyObj.user_metadata ?? options.userMetadata;
|
|
300
|
+
const aId = bodyObj.app_id ?? options.appId;
|
|
301
|
+
const productUser = {
|
|
302
|
+
...dName ? { display_name: dName } : {},
|
|
303
|
+
...uEmail ? { email: uEmail } : {},
|
|
304
|
+
...uMeta ? { metadata: uMeta } : {},
|
|
305
|
+
...bodyObj.metadata?.product_user
|
|
306
|
+
};
|
|
307
|
+
const merged = {
|
|
308
|
+
...extId ? { external_user_id: extId } : {},
|
|
309
|
+
...prodUserId ? { product_end_user_id: prodUserId } : {},
|
|
310
|
+
...aId ? { app_id: aId } : {},
|
|
311
|
+
...Object.keys(productUser).length > 0 ? { product_user: productUser } : {},
|
|
312
|
+
...options.metadata,
|
|
313
|
+
...bodyObj.metadata
|
|
314
|
+
};
|
|
315
|
+
if (Object.keys(merged).length > 0) {
|
|
316
|
+
bodyObj.metadata = merged;
|
|
317
|
+
init = { ...init, body: JSON.stringify(bodyObj) };
|
|
318
|
+
}
|
|
319
|
+
} catch {
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
return baseFetch(url, init);
|
|
323
|
+
};
|
|
324
|
+
return (0, import_openai.createOpenAI)({
|
|
325
|
+
apiKey,
|
|
326
|
+
baseURL: options.baseURL ?? process.env.ZORVEUS_GATEWAY_URL ?? "https://api.zorveus.com/v1",
|
|
327
|
+
headers: options.headers,
|
|
328
|
+
fetch: customFetch
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
332
|
+
0 && (module.exports = {
|
|
333
|
+
createZorveus,
|
|
334
|
+
parseZorveusGatewayError
|
|
335
|
+
});
|
|
336
|
+
//# sourceMappingURL=vercel.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/vercel.ts","../../src/errors/zorveus-error.ts"],"sourcesContent":["import { createOpenAI, type OpenAIProvider } from \"@ai-sdk/openai\";\nexport { parseZorveusGatewayError } from \"../errors/zorveus-error\";\n\nexport interface ZorveusVercelOptions {\n apiKey?: string;\n baseURL?: string;\n externalUserId?: string;\n productEndUserId?: string;\n displayName?: string;\n userEmail?: string;\n email?: string;\n userMetadata?: Record<string, unknown>;\n appId?: string;\n metadata?: Record<string, unknown>;\n headers?: Record<string, string>;\n fetch?: typeof globalThis.fetch;\n}\n\n/**\n * Creates a Vercel AI SDK provider instance configured for Zorveus AI Gateway,\n * automatically injecting metadata (external_user_id, product_end_user_id, and product_user attribution) into request payloads.\n */\nexport function createZorveus(options: ZorveusVercelOptions = {}): OpenAIProvider {\n const apiKey = options.apiKey ?? process.env.ZORVEUS_INFERENCE_KEY;\n if (!apiKey) {\n throw new Error(\"Zorveus API key is required. Set ZORVEUS_INFERENCE_KEY or pass apiKey.\");\n }\n\n const baseFetch = options.fetch ?? globalThis.fetch;\n\n const customFetch: typeof globalThis.fetch = async (url, init) => {\n if (init?.body && typeof init.body === \"string\") {\n try {\n const bodyObj = JSON.parse(init.body);\n\n const extId = bodyObj.user ?? bodyObj.external_user_id ?? options.externalUserId;\n const prodUserId =\n bodyObj.product_end_user_id ??\n bodyObj.metadata?.product_end_user_id ??\n options.productEndUserId;\n const dName = bodyObj.display_name ?? options.displayName;\n const uEmail = bodyObj.user_email ?? bodyObj.email ?? options.userEmail ?? options.email;\n const uMeta = bodyObj.user_metadata ?? options.userMetadata;\n const aId = bodyObj.app_id ?? options.appId;\n\n const productUser = {\n ...(dName ? { display_name: dName } : {}),\n ...(uEmail ? { email: uEmail } : {}),\n ...(uMeta ? { metadata: uMeta } : {}),\n ...bodyObj.metadata?.product_user\n };\n\n const merged = {\n ...(extId ? { external_user_id: extId } : {}),\n ...(prodUserId ? { product_end_user_id: prodUserId } : {}),\n ...(aId ? { app_id: aId } : {}),\n ...(Object.keys(productUser).length > 0 ? { product_user: productUser } : {}),\n ...options.metadata,\n ...bodyObj.metadata\n };\n\n if (Object.keys(merged).length > 0) {\n bodyObj.metadata = merged;\n init = { ...init, body: JSON.stringify(bodyObj) };\n }\n } catch {\n // Ignore non-JSON request body\n }\n }\n return baseFetch(url, init);\n };\n\n return createOpenAI({\n apiKey,\n baseURL: options.baseURL ?? process.env.ZORVEUS_GATEWAY_URL ?? \"https://api.zorveus.com/v1\",\n headers: options.headers,\n fetch: customFetch\n });\n}\n","import type { ProductUserAllowanceInsufficientParams } from \"../types/product-users\";\n\n/**\n * Base class for all Zorveus SDK errors.\n */\nexport class ZorveusError extends Error {\n readonly status?: number;\n readonly code?: string;\n readonly param?: string;\n readonly type?: string;\n readonly params?: Record<string, unknown>;\n readonly headers?: Record<string, string>;\n readonly rawBody?: unknown;\n\n constructor(\n message: string,\n options: {\n status?: number;\n code?: string;\n param?: string;\n type?: string;\n params?: Record<string, unknown>;\n headers?: Record<string, string>;\n rawBody?: unknown;\n cause?: unknown;\n } = {}\n ) {\n super(message);\n this.name = \"ZorveusError\";\n this.status = options.status;\n this.code = options.code;\n this.param = options.param;\n this.type = options.type;\n this.params = options.params;\n this.headers = options.headers;\n this.rawBody = options.rawBody;\n if (options.cause) {\n this.cause = options.cause;\n }\n\n // Restore prototype chain\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when an HTTP request fails before receiving a response (network drops, DNS failures, aborts/timeouts).\n */\nexport class APIConnectionError extends ZorveusError {\n constructor(message = \"Connection to Zorveus API failed\", options: { cause?: unknown } = {}) {\n super(message, options);\n this.name = \"APIConnectionError\";\n if (options.cause) {\n this.cause = options.cause;\n }\n }\n}\n\n/**\n * Base class for all HTTP 4xx and 5xx responses from the Zorveus API.\n */\nexport class APIStatusError extends ZorveusError {\n constructor(\n message: string,\n options: {\n status: number;\n code?: string;\n param?: string;\n type?: string;\n params?: Record<string, unknown>;\n headers?: Record<string, string>;\n rawBody?: unknown;\n }\n ) {\n super(message, options);\n this.name = \"APIStatusError\";\n }\n}\n\n/**\n * HTTP 401: Invalid or expired API key, Service key, or OAuth access token.\n */\nexport class AuthenticationError extends APIStatusError {\n constructor(message = \"Invalid or expired Zorveus credentials\", options: Omit<ConstructorParameters<typeof APIStatusError>[1], \"status\"> & { status?: number } = {}) {\n super(message, { ...options, status: options.status ?? 401 });\n this.name = \"AuthenticationError\";\n }\n}\n\n/**\n * HTTP 403: Forbidden access, insufficient scope, or model not permitted.\n */\nexport class PermissionDeniedError extends APIStatusError {\n constructor(message = \"Permission denied for this operation or model\", options: Omit<ConstructorParameters<typeof APIStatusError>[1], \"status\"> & { status?: number } = {}) {\n super(message, { ...options, status: options.status ?? 403 });\n this.name = \"PermissionDeniedError\";\n }\n}\n\n/**\n * HTTP 404: Requested resource (app, user, credential, model) was not found.\n */\nexport class NotFoundError extends APIStatusError {\n constructor(message = \"Resource not found\", options: Omit<ConstructorParameters<typeof APIStatusError>[1], \"status\"> & { status?: number } = {}) {\n super(message, { ...options, status: options.status ?? 404 });\n this.name = \"NotFoundError\";\n }\n}\n\n/**\n * HTTP 422: Request schema validation failure.\n */\nexport class UnprocessableEntityError extends APIStatusError {\n constructor(message = \"Request validation failed\", options: Omit<ConstructorParameters<typeof APIStatusError>[1], \"status\"> & { status?: number } = {}) {\n super(message, { ...options, status: options.status ?? 422 });\n this.name = \"UnprocessableEntityError\";\n }\n}\n\n/**\n * HTTP 429: Rate limit exceeded or quota exhausted.\n */\nexport class RateLimitError extends APIStatusError {\n constructor(message = \"Rate limit exceeded. Please retry after some time.\", options: Omit<ConstructorParameters<typeof APIStatusError>[1], \"status\"> & { status?: number } = {}) {\n super(message, { ...options, status: options.status ?? 429 });\n this.name = \"RateLimitError\";\n }\n}\n\n/**\n * HTTP 500, 502, 503, 504: Zorveus internal server or upstream gateway error.\n */\nexport class InternalServerError extends APIStatusError {\n constructor(message = \"Zorveus internal server error\", options: Omit<ConstructorParameters<typeof APIStatusError>[1], \"status\"> & { status?: number } = {}) {\n super(message, { ...options, status: options.status ?? 500 });\n this.name = \"InternalServerError\";\n }\n}\n\n/**\n * Base class for Zorveus financial and business constraint errors.\n */\nexport class ZorveusBusinessError extends APIStatusError {\n constructor(\n message: string,\n options: {\n status: number;\n code?: string;\n param?: string;\n type?: string;\n params?: Record<string, unknown>;\n headers?: Record<string, string>;\n rawBody?: unknown;\n }\n ) {\n super(message, options);\n this.name = \"ZorveusBusinessError\";\n }\n}\n\n/**\n * HTTP 402: Organization wallet balance is exhausted or insufficient for estimated charge/fee.\n */\nexport class InsufficientFundsError extends ZorveusBusinessError {\n constructor(\n message = \"Wallet balance exhausted. Top up required.\",\n options: Omit<ConstructorParameters<typeof ZorveusBusinessError>[1], \"status\"> & { status?: number } = {}\n ) {\n super(message, {\n ...options,\n status: options.status ?? 402,\n code: options.code ?? \"zorveus_reservation_insufficient_balance\"\n });\n this.name = \"InsufficientFundsError\";\n }\n}\n\n/**\n * HTTP 403: Spending cap limit reached for inference key or member.\n */\nexport class CapExceededError extends ZorveusBusinessError {\n constructor(\n message = \"Spending cap limit reached\",\n options: Omit<ConstructorParameters<typeof ZorveusBusinessError>[1], \"status\"> & { status?: number } = {}\n ) {\n super(message, {\n ...options,\n status: options.status ?? 403,\n code: options.code ?? \"zorveus_cap_exceeded\"\n });\n this.name = \"CapExceededError\";\n }\n}\n\n/**\n * HTTP 403: Enforced AI allowance exhausted for a product user on an inference key.\n * Contains shortfall and breakdown between base cap and promotional credits.\n */\nexport class ProductUserAllowanceInsufficientError extends ZorveusBusinessError {\n declare readonly params?: ProductUserAllowanceInsufficientParams;\n\n constructor(\n message = \"Product user AI allowance is insufficient for this request.\",\n options: Omit<ConstructorParameters<typeof ZorveusBusinessError>[1], \"status\"> & {\n status?: number;\n params?: ProductUserAllowanceInsufficientParams;\n } = {}\n ) {\n super(message, {\n ...options,\n status: options.status ?? 403,\n code: options.code ?? \"zorveus_product_user_allowance_insufficient\",\n params: options.params\n });\n this.name = \"ProductUserAllowanceInsufficientError\";\n }\n}\n\n/**\n * HTTP 403: Product user credit grant has expired.\n */\nexport class CreditGrantExpiredError extends ZorveusBusinessError {\n constructor(\n message = \"Product user credit grant has expired\",\n options: Omit<ConstructorParameters<typeof ZorveusBusinessError>[1], \"status\"> & { status?: number } = {}\n ) {\n super(message, {\n ...options,\n status: options.status ?? 403,\n code: options.code ?? \"credit_grant_expired\"\n });\n this.name = \"CreditGrantExpiredError\";\n }\n}\n\n/**\n * HTTP 403: Supplied inference key or connected app is invalid or revoked.\n */\nexport class AppConnectionNotFoundError extends ZorveusBusinessError {\n constructor(\n message = \"Inference key or app connection not found or revoked\",\n options: Omit<ConstructorParameters<typeof ZorveusBusinessError>[1], \"status\"> & { status?: number } = {}\n ) {\n super(message, {\n ...options,\n status: options.status ?? 403,\n code: options.code ?? \"zorveus_app_connection_not_found\"\n });\n this.name = \"AppConnectionNotFoundError\";\n }\n}\n\n/**\n * HTTP 409: Idempotency key reused with mismatched request parameters.\n */\nexport class ReservationConflictError extends ZorveusBusinessError {\n constructor(\n message = \"Idempotency key reused with conflicting request parameters\",\n options: Omit<ConstructorParameters<typeof ZorveusBusinessError>[1], \"status\"> & { status?: number } = {}\n ) {\n super(message, {\n ...options,\n status: options.status ?? 409,\n code: options.code ?? \"zorveus_reservation_conflict\"\n });\n this.name = \"ReservationConflictError\";\n }\n}\n\n/**\n * Factory that parses HTTP status code and response payload into the most specific ZorveusError subclass.\n */\nexport function createAPIError(\n status: number,\n body: unknown,\n headers?: Record<string, string>\n): APIStatusError {\n let message = `Request failed with status ${status}`;\n let code: string | undefined;\n let param: string | undefined;\n let type: string | undefined;\n let params: Record<string, unknown> | undefined;\n\n // Normalize string error bodies (including single-quoted Python dict strings)\n let parsedBody: unknown = body;\n if (typeof body === \"string\") {\n try {\n parsedBody = JSON.parse(body);\n } catch {\n try {\n parsedBody = JSON.parse(body.replace(/'/g, '\"'));\n } catch {\n const codeMatch = body.match(/['\"]code['\"]\\s*:\\s*['\"]([^'\"]+)['\"]/);\n const msgMatch = body.match(/['\"]message['\"]\\s*:\\s*['\"]([^'\"]+)['\"]/);\n if (msgMatch?.[1]) message = msgMatch[1];\n if (codeMatch?.[1]) code = codeMatch[1];\n }\n }\n }\n\n // Extract structured error details if available\n if (parsedBody && typeof parsedBody === \"object\") {\n const obj = parsedBody as Record<string, unknown>;\n\n // Check OpenAI-compatible gateway wrapper: provider_specific_fields.error or error.provider_specific_fields.error\n const providerFields = (\n obj.provider_specific_fields ??\n (obj.error as Record<string, unknown> | undefined)?.provider_specific_fields\n ) as Record<string, unknown> | undefined;\n const nestedGatewayError = (providerFields?.error ?? providerFields) as Record<string, unknown> | undefined;\n\n if (nestedGatewayError && typeof nestedGatewayError === \"object\") {\n if (typeof nestedGatewayError.message === \"string\") message = nestedGatewayError.message;\n if (typeof nestedGatewayError.code === \"string\") code = nestedGatewayError.code;\n if (typeof nestedGatewayError.param === \"string\") param = nestedGatewayError.param;\n if (typeof nestedGatewayError.type === \"string\") type = nestedGatewayError.type;\n if (nestedGatewayError.params && typeof nestedGatewayError.params === \"object\") {\n params = nestedGatewayError.params as Record<string, unknown>;\n }\n } else if (obj.error && typeof obj.error === \"object\") {\n const err = obj.error as Record<string, unknown>;\n if (typeof err.message === \"string\") message = err.message;\n if (typeof err.code === \"string\") code = err.code;\n if (typeof err.param === \"string\") param = err.param;\n if (typeof err.type === \"string\") type = err.type;\n if (err.params && typeof err.params === \"object\") {\n params = err.params as Record<string, unknown>;\n }\n } else {\n if (typeof obj.message === \"string\") message = obj.message;\n if (typeof obj.code === \"string\") code = obj.code;\n if (typeof obj.param === \"string\") param = obj.param;\n if (typeof obj.type === \"string\") type = obj.type;\n if (obj.params && typeof obj.params === \"object\") {\n params = obj.params as Record<string, unknown>;\n }\n if (typeof obj.detail === \"string\") {\n message = obj.detail;\n } else if (Array.isArray(obj.detail) && obj.detail.length > 0) {\n const first = obj.detail[0];\n if (first && typeof first.msg === \"string\") {\n message = first.msg;\n }\n }\n }\n }\n\n const options = { status, code, param, type, params, headers, rawBody: body };\n const normalizedCode = (code || \"\").toLowerCase();\n\n // 1. Enforced product-user allowance denial (HTTP 403)\n if (\n normalizedCode === \"zorveus_product_user_allowance_insufficient\" ||\n normalizedCode === \"zorveus_product_user_credits_insufficient\" ||\n normalizedCode.includes(\"allowance_insufficient\") ||\n normalizedCode.includes(\"credits_insufficient\") ||\n message.toLowerCase().includes(\"allowance remaining\")\n ) {\n return new ProductUserAllowanceInsufficientError(message, {\n ...options,\n status: status === 200 ? 403 : status,\n params: params as ProductUserAllowanceInsufficientParams | undefined\n });\n }\n\n // 2. Spending cap exceeded (HTTP 403)\n if (\n normalizedCode === \"zorveus_cap_exceeded\" ||\n normalizedCode.includes(\"cap_exceed\") ||\n normalizedCode.includes(\"spend_cap\") ||\n message.toLowerCase().includes(\"spending cap\")\n ) {\n return new CapExceededError(message, options);\n }\n\n // 3. App connection not found / revoked (HTTP 403)\n if (\n normalizedCode === \"zorveus_app_connection_not_found\" ||\n normalizedCode.includes(\"app_connection_not_found\")\n ) {\n return new AppConnectionNotFoundError(message, options);\n }\n\n // 4. Idempotency reservation conflict (HTTP 409)\n if (\n status === 409 ||\n normalizedCode === \"zorveus_reservation_conflict\" ||\n normalizedCode.includes(\"reservation_conflict\")\n ) {\n return new ReservationConflictError(message, options);\n }\n\n // 5. Wallet insufficient balance (HTTP 402)\n if (\n status === 402 ||\n normalizedCode === \"zorveus_reservation_insufficient_balance\" ||\n normalizedCode.includes(\"insufficient_funds\") ||\n normalizedCode.includes(\"balance_exhausted\") ||\n normalizedCode.includes(\"insufficient_balance\") ||\n normalizedCode.includes(\"wallet_empty\") ||\n message.toLowerCase().includes(\"insufficient funds\") ||\n message.toLowerCase().includes(\"balance exhausted\") ||\n message.toLowerCase().includes(\"wallet is empty\")\n ) {\n return new InsufficientFundsError(message, options);\n }\n\n // 6. Expired credit grant (HTTP 403)\n if (normalizedCode.includes(\"grant_expired\")) {\n return new CreditGrantExpiredError(message, options);\n }\n\n // Status code based fallback mapping\n if (status === 401) {\n return new AuthenticationError(message, options);\n }\n\n if (status === 403) {\n return new PermissionDeniedError(message, options);\n }\n\n if (status === 404) {\n return new NotFoundError(message, options);\n }\n\n if (status === 422) {\n return new UnprocessableEntityError(message, options);\n }\n\n if (status === 429) {\n return new RateLimitError(message, options);\n }\n\n if (status >= 500) {\n return new InternalServerError(message, options);\n }\n\n return new APIStatusError(message, options);\n}\n\n/**\n * Parses errors thrown by OpenAI SDK or Vercel AI SDK into typed Zorveus errors.\n */\nexport function parseZorveusGatewayError(error: unknown): ZorveusError | unknown {\n if (error instanceof ZorveusError) {\n return error;\n }\n\n if (!error || typeof error !== \"object\") {\n return error;\n }\n\n const errObj = error as Record<string, unknown>;\n const status =\n typeof errObj.status === \"number\"\n ? errObj.status\n : typeof errObj.statusCode === \"number\"\n ? errObj.statusCode\n : undefined;\n\n const rawBody = errObj.error ?? errObj.body ?? errObj.rawBody;\n if (status !== undefined && rawBody !== undefined) {\n const headers =\n errObj.headers && typeof errObj.headers === \"object\"\n ? (errObj.headers as Record<string, string>)\n : undefined;\n return createAPIError(status, rawBody, headers);\n }\n\n return error;\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAkD;;;ACK3C,IAAM,eAAN,cAA2B,MAAM;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,YACE,SACA,UASI,CAAC,GACL;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS,QAAQ;AACtB,SAAK,OAAO,QAAQ;AACpB,SAAK,QAAQ,QAAQ;AACrB,SAAK,OAAO,QAAQ;AACpB,SAAK,SAAS,QAAQ;AACtB,SAAK,UAAU,QAAQ;AACvB,SAAK,UAAU,QAAQ;AACvB,QAAI,QAAQ,OAAO;AACjB,WAAK,QAAQ,QAAQ;AAAA,IACvB;AAGA,WAAO,eAAe,MAAM,WAAW,SAAS;AAAA,EAClD;AACF;AAkBO,IAAM,iBAAN,cAA6B,aAAa;AAAA,EAC/C,YACE,SACA,SASA;AACA,UAAM,SAAS,OAAO;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AAc;AAAA,UAClB,GAAI,QAAQ,EAAE,cAAc,MAAM,IAAI,CAAC;AAAA,UACvC,GAAI,SAAS,EAAE,OAAO,OAAO,IAAI,CAAC;AAAA,UAClC,GAAI,QAAQ,EAAE,UAAU,MAAM,IAAI,CAAC;AAAA,UACnC,GAAG,QAAQ,UAAU;AAAA,QACvB;AAEA,cAAM,SAAS;AAAA,UACb,GAAI,QAAQ,EAAE,kBAAkB,MAAM,IAAI,CAAC;AAAA,UAC3C,GAAI,aAAa,EAAE,qBAAqB,WAAW,IAAI,CAAC;AAAA,UACxD,GAAI,MAAM,EAAE,QAAQ,IAAI,IAAI,CAAC;AAAA,UAC7B,GAAI,OAAO,KAAK,WAAW,EAAE,SAAS,IAAI,EAAE,cAAc,YAAY,IAAI,CAAC;AAAA,UAC3E,GAAG,QAAQ;AAAA,UACX,GAAG,QAAQ;AAAA,QACb;AAEA,YAAI,OAAO,KAAK,MAAM,EAAE,SAAS,GAAG;AAClC,kBAAQ,WAAW;AACnB,iBAAO,EAAE,GAAG,MAAM,MAAM,KAAK,UAAU,OAAO,EAAE;AAAA,QAClD;AAAA,MACF,QAAQ;AAAA,MAER;AAAA,IACF;AACA,WAAO,UAAU,KAAK,IAAI;AAAA,EAC5B;AAEA,aAAO,4BAAa;AAAA,IAClB;AAAA,IACA,SAAS,QAAQ,WAAW,QAAQ,IAAI,uBAAuB;AAAA,IAC/D,SAAS,QAAQ;AAAA,IACjB,OAAO;AAAA,EACT,CAAC;AACH;","names":[]}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import {
|
|
2
|
+
parseZorveusGatewayError
|
|
3
|
+
} from "../chunk-6SPZ5W5D.mjs";
|
|
4
|
+
|
|
5
|
+
// src/adapters/vercel.ts
|
|
6
|
+
import { createOpenAI } from "@ai-sdk/openai";
|
|
7
|
+
function createZorveus(options = {}) {
|
|
8
|
+
const apiKey = options.apiKey ?? process.env.ZORVEUS_INFERENCE_KEY;
|
|
9
|
+
if (!apiKey) {
|
|
10
|
+
throw new Error("Zorveus API key is required. Set ZORVEUS_INFERENCE_KEY or pass apiKey.");
|
|
11
|
+
}
|
|
12
|
+
const baseFetch = options.fetch ?? globalThis.fetch;
|
|
13
|
+
const customFetch = async (url, init) => {
|
|
14
|
+
if (init?.body && typeof init.body === "string") {
|
|
15
|
+
try {
|
|
16
|
+
const bodyObj = JSON.parse(init.body);
|
|
17
|
+
const extId = bodyObj.user ?? bodyObj.external_user_id ?? options.externalUserId;
|
|
18
|
+
const prodUserId = bodyObj.product_end_user_id ?? bodyObj.metadata?.product_end_user_id ?? options.productEndUserId;
|
|
19
|
+
const dName = bodyObj.display_name ?? options.displayName;
|
|
20
|
+
const uEmail = bodyObj.user_email ?? bodyObj.email ?? options.userEmail ?? options.email;
|
|
21
|
+
const uMeta = bodyObj.user_metadata ?? options.userMetadata;
|
|
22
|
+
const aId = bodyObj.app_id ?? options.appId;
|
|
23
|
+
const productUser = {
|
|
24
|
+
...dName ? { display_name: dName } : {},
|
|
25
|
+
...uEmail ? { email: uEmail } : {},
|
|
26
|
+
...uMeta ? { metadata: uMeta } : {},
|
|
27
|
+
...bodyObj.metadata?.product_user
|
|
28
|
+
};
|
|
29
|
+
const merged = {
|
|
30
|
+
...extId ? { external_user_id: extId } : {},
|
|
31
|
+
...prodUserId ? { product_end_user_id: prodUserId } : {},
|
|
32
|
+
...aId ? { app_id: aId } : {},
|
|
33
|
+
...Object.keys(productUser).length > 0 ? { product_user: productUser } : {},
|
|
34
|
+
...options.metadata,
|
|
35
|
+
...bodyObj.metadata
|
|
36
|
+
};
|
|
37
|
+
if (Object.keys(merged).length > 0) {
|
|
38
|
+
bodyObj.metadata = merged;
|
|
39
|
+
init = { ...init, body: JSON.stringify(bodyObj) };
|
|
40
|
+
}
|
|
41
|
+
} catch {
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return baseFetch(url, init);
|
|
45
|
+
};
|
|
46
|
+
return createOpenAI({
|
|
47
|
+
apiKey,
|
|
48
|
+
baseURL: options.baseURL ?? process.env.ZORVEUS_GATEWAY_URL ?? "https://api.zorveus.com/v1",
|
|
49
|
+
headers: options.headers,
|
|
50
|
+
fetch: customFetch
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
export {
|
|
54
|
+
createZorveus,
|
|
55
|
+
parseZorveusGatewayError
|
|
56
|
+
};
|
|
57
|
+
//# sourceMappingURL=vercel.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/vercel.ts"],"sourcesContent":["import { createOpenAI, type OpenAIProvider } from \"@ai-sdk/openai\";\nexport { parseZorveusGatewayError } from \"../errors/zorveus-error\";\n\nexport interface ZorveusVercelOptions {\n apiKey?: string;\n baseURL?: string;\n externalUserId?: string;\n productEndUserId?: string;\n displayName?: string;\n userEmail?: string;\n email?: string;\n userMetadata?: Record<string, unknown>;\n appId?: string;\n metadata?: Record<string, unknown>;\n headers?: Record<string, string>;\n fetch?: typeof globalThis.fetch;\n}\n\n/**\n * Creates a Vercel AI SDK provider instance configured for Zorveus AI Gateway,\n * automatically injecting metadata (external_user_id, product_end_user_id, and product_user attribution) into request payloads.\n */\nexport function createZorveus(options: ZorveusVercelOptions = {}): OpenAIProvider {\n const apiKey = options.apiKey ?? process.env.ZORVEUS_INFERENCE_KEY;\n if (!apiKey) {\n throw new Error(\"Zorveus API key is required. Set ZORVEUS_INFERENCE_KEY or pass apiKey.\");\n }\n\n const baseFetch = options.fetch ?? globalThis.fetch;\n\n const customFetch: typeof globalThis.fetch = async (url, init) => {\n if (init?.body && typeof init.body === \"string\") {\n try {\n const bodyObj = JSON.parse(init.body);\n\n const extId = bodyObj.user ?? bodyObj.external_user_id ?? options.externalUserId;\n const prodUserId =\n bodyObj.product_end_user_id ??\n bodyObj.metadata?.product_end_user_id ??\n options.productEndUserId;\n const dName = bodyObj.display_name ?? options.displayName;\n const uEmail = bodyObj.user_email ?? bodyObj.email ?? options.userEmail ?? options.email;\n const uMeta = bodyObj.user_metadata ?? options.userMetadata;\n const aId = bodyObj.app_id ?? options.appId;\n\n const productUser = {\n ...(dName ? { display_name: dName } : {}),\n ...(uEmail ? { email: uEmail } : {}),\n ...(uMeta ? { metadata: uMeta } : {}),\n ...bodyObj.metadata?.product_user\n };\n\n const merged = {\n ...(extId ? { external_user_id: extId } : {}),\n ...(prodUserId ? { product_end_user_id: prodUserId } : {}),\n ...(aId ? { app_id: aId } : {}),\n ...(Object.keys(productUser).length > 0 ? { product_user: productUser } : {}),\n ...options.metadata,\n ...bodyObj.metadata\n };\n\n if (Object.keys(merged).length > 0) {\n bodyObj.metadata = merged;\n init = { ...init, body: JSON.stringify(bodyObj) };\n }\n } catch {\n // Ignore non-JSON request body\n }\n }\n return baseFetch(url, init);\n };\n\n return createOpenAI({\n apiKey,\n baseURL: options.baseURL ?? process.env.ZORVEUS_GATEWAY_URL ?? \"https://api.zorveus.com/v1\",\n headers: options.headers,\n fetch: customFetch\n });\n}\n"],"mappings":";;;;;AAAA,SAAS,oBAAyC;AAsB3C,SAAS,cAAc,UAAgC,CAAC,GAAmB;AAChF,QAAM,SAAS,QAAQ,UAAU,QAAQ,IAAI;AAC7C,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI,MAAM,wEAAwE;AAAA,EAC1F;AAEA,QAAM,YAAY,QAAQ,SAAS,WAAW;AAE9C,QAAM,cAAuC,OAAO,KAAK,SAAS;AAChE,QAAI,MAAM,QAAQ,OAAO,KAAK,SAAS,UAAU;AAC/C,UAAI;AACF,cAAM,UAAU,KAAK,MAAM,KAAK,IAAI;AAEpC,cAAM,QAAQ,QAAQ,QAAQ,QAAQ,oBAAoB,QAAQ;AAClE,cAAM,aACJ,QAAQ,uBACR,QAAQ,UAAU,uBAClB,QAAQ;AACV,cAAM,QAAQ,QAAQ,gBAAgB,QAAQ;AAC9C,cAAM,SAAS,QAAQ,cAAc,QAAQ,SAAS,QAAQ,aAAa,QAAQ;AACnF,cAAM,QAAQ,QAAQ,iBAAiB,QAAQ;AA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