@enlitt/sdk 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/LICENSE +21 -0
- package/README.md +61 -2
- package/dist/browser/auth.d.cts +44 -0
- package/dist/browser/auth.d.ts +45 -0
- package/dist/browser/auth.d.ts.map +1 -0
- package/dist/browser.cjs +35 -0
- package/dist/browser.cjs.map +1 -0
- package/dist/browser.d.cts +12 -0
- package/dist/browser.d.ts +13 -0
- package/dist/browser.d.ts.map +1 -0
- package/dist/browser.js +32 -0
- package/dist/browser.js.map +1 -0
- package/dist/chunk-26SW63P5.cjs +883 -0
- package/dist/chunk-26SW63P5.cjs.map +1 -0
- package/dist/chunk-6DPBYLA5.js +855 -0
- package/dist/chunk-6DPBYLA5.js.map +1 -0
- package/dist/chunk-6OWXYBBT.cjs +146 -0
- package/dist/chunk-6OWXYBBT.cjs.map +1 -0
- package/dist/chunk-C76K6HLL.cjs +906 -0
- package/dist/chunk-C76K6HLL.cjs.map +1 -0
- package/dist/chunk-G4DTTV5E.cjs +35 -0
- package/dist/chunk-G4DTTV5E.cjs.map +1 -0
- package/dist/chunk-SFI4RLNN.js +900 -0
- package/dist/chunk-SFI4RLNN.js.map +1 -0
- package/dist/chunk-V5TCSQ7C.js +143 -0
- package/dist/chunk-V5TCSQ7C.js.map +1 -0
- package/dist/chunk-VNVMEU34.js +33 -0
- package/dist/chunk-VNVMEU34.js.map +1 -0
- package/dist/core/errors.d.cts +254 -0
- package/dist/core/errors.d.ts +255 -0
- package/dist/core/errors.d.ts.map +1 -0
- package/dist/core/index.d.cts +24 -0
- package/dist/core/index.d.ts +25 -0
- package/dist/core/index.d.ts.map +1 -0
- package/dist/core/premium.d.cts +230 -0
- package/dist/core/premium.d.ts +231 -0
- package/dist/core/premium.d.ts.map +1 -0
- package/dist/core/session.d.cts +107 -0
- package/dist/core/session.d.ts +108 -0
- package/dist/core/session.d.ts.map +1 -0
- package/dist/core/sse.d.cts +79 -0
- package/dist/core/sse.d.ts +80 -0
- package/dist/core/sse.d.ts.map +1 -0
- package/dist/core/transport.d.cts +223 -0
- package/dist/core/transport.d.ts +224 -0
- package/dist/core/transport.d.ts.map +1 -0
- package/dist/core/usage.d.cts +35 -0
- package/dist/core/usage.d.ts +36 -0
- package/dist/core/usage.d.ts.map +1 -0
- package/dist/core.cjs +73 -0
- package/dist/core.cjs.map +1 -0
- package/dist/core.js +4 -0
- package/dist/core.js.map +1 -0
- package/dist/index.cjs +4 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +16 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/openai/client.d.cts +48 -0
- package/dist/openai/client.d.ts +49 -0
- package/dist/openai/client.d.ts.map +1 -0
- package/dist/openai/index.d.cts +1 -0
- package/dist/openai/index.d.ts +2 -0
- package/dist/openai/index.d.ts.map +1 -0
- package/dist/openai.cjs +479 -0
- package/dist/openai.cjs.map +1 -0
- package/dist/openai.js +473 -0
- package/dist/openai.js.map +1 -0
- package/dist/server/callback.d.cts +106 -0
- package/dist/server/callback.d.ts +107 -0
- package/dist/server/callback.d.ts.map +1 -0
- package/dist/server/index.d.cts +19 -0
- package/dist/server/index.d.ts +20 -0
- package/dist/server/index.d.ts.map +1 -0
- package/dist/server/secrets.d.cts +46 -0
- package/dist/server/secrets.d.ts +47 -0
- package/dist/server/secrets.d.ts.map +1 -0
- package/dist/server-unavailable.cjs +8 -0
- package/dist/server-unavailable.cjs.map +1 -0
- package/dist/server-unavailable.d.cts +10 -0
- package/dist/server-unavailable.d.ts +11 -0
- package/dist/server-unavailable.d.ts.map +1 -0
- package/dist/server-unavailable.js +6 -0
- package/dist/server-unavailable.js.map +1 -0
- package/dist/server.cjs +354 -0
- package/dist/server.cjs.map +1 -0
- package/dist/server.js +275 -0
- package/dist/server.js.map +1 -0
- package/dist/vercel/index.d.cts +15 -0
- package/dist/vercel/index.d.ts +16 -0
- package/dist/vercel/index.d.ts.map +1 -0
- package/dist/vercel/language-model.d.cts +131 -0
- package/dist/vercel/language-model.d.ts +132 -0
- package/dist/vercel/language-model.d.ts.map +1 -0
- package/dist/vercel/premium-language-model.d.cts +98 -0
- package/dist/vercel/premium-language-model.d.ts +99 -0
- package/dist/vercel/premium-language-model.d.ts.map +1 -0
- package/dist/vercel/standard-language-model.d.cts +104 -0
- package/dist/vercel/standard-language-model.d.ts +105 -0
- package/dist/vercel/standard-language-model.d.ts.map +1 -0
- package/dist/vercel.cjs +22 -0
- package/dist/vercel.cjs.map +1 -0
- package/dist/vercel.js +5 -0
- package/dist/vercel.js.map +1 -0
- package/package.json +129 -3
|
@@ -0,0 +1,883 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var protocol = require('@enlitt/protocol');
|
|
4
|
+
var async_hooks = require('async_hooks');
|
|
5
|
+
|
|
6
|
+
// src/core/errors.ts
|
|
7
|
+
var EnlittError = class extends Error {
|
|
8
|
+
name = "EnlittError";
|
|
9
|
+
code;
|
|
10
|
+
/**
|
|
11
|
+
* Always `false`. Enlitt refuses before a provider is ever reached, so no
|
|
12
|
+
* instance of this hierarchy can report otherwise — that is the one
|
|
13
|
+
* question a business needs answered before it retries or bills anything.
|
|
14
|
+
* A provider's own error is never wrapped in this class in the first
|
|
15
|
+
* place; see `normalizeEnlittModelError`.
|
|
16
|
+
*/
|
|
17
|
+
providerInvoked = false;
|
|
18
|
+
/**
|
|
19
|
+
* Read from the frozen record for a wire code, and always `false` for a
|
|
20
|
+
* local code, which has no record entry. Never decided per instance: a
|
|
21
|
+
* refusal carries the non-retryable marker the pinned Vercel AI SDK reads,
|
|
22
|
+
* so a configured `maxRetries` cannot turn one refusal into several.
|
|
23
|
+
*/
|
|
24
|
+
retryable;
|
|
25
|
+
retryAfterMs;
|
|
26
|
+
requestId;
|
|
27
|
+
/**
|
|
28
|
+
* Present only when the record's `authorizeUrl` field for this instance's
|
|
29
|
+
* code is `"allowed"` and a caller supplied one. It is a navigation
|
|
30
|
+
* target, never a disclosure: the actual figures live only on Enlitt's own
|
|
31
|
+
* dashboard behind it.
|
|
32
|
+
*
|
|
33
|
+
* The record allows this on the four `insufficient_credits_error` codes and
|
|
34
|
+
* no others, which is what this module's spec text says. `authorizeUrl` is
|
|
35
|
+
* still read from the record rather than decided here, per this module's own
|
|
36
|
+
* rule; the record simply now agrees with the spec.
|
|
37
|
+
*/
|
|
38
|
+
authorizeUrl;
|
|
39
|
+
constructor(code, message, facts = {}) {
|
|
40
|
+
super(message);
|
|
41
|
+
this.code = code;
|
|
42
|
+
const definition = protocol.isEnlittErrorCode(code) ? protocol.ENLITT_ERROR_CODES[code] : void 0;
|
|
43
|
+
this.retryable = definition?.retryable ?? (isLocalCode(code) ? false : facts.retryable ?? false);
|
|
44
|
+
if (facts.retryAfterMs !== void 0) {
|
|
45
|
+
this.retryAfterMs = facts.retryAfterMs;
|
|
46
|
+
}
|
|
47
|
+
if (facts.requestId !== void 0) {
|
|
48
|
+
this.requestId = facts.requestId;
|
|
49
|
+
}
|
|
50
|
+
if (facts.authorizeUrl !== void 0 && (definition?.authorizeUrl === "allowed" || definition === void 0 && !isLocalCode(code))) {
|
|
51
|
+
this.authorizeUrl = facts.authorizeUrl;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
var LOCAL_CODES = /* @__PURE__ */ new Set([
|
|
56
|
+
"configuration_invalid",
|
|
57
|
+
"transport_failed",
|
|
58
|
+
"malformed_response",
|
|
59
|
+
"request_canceled"
|
|
60
|
+
]);
|
|
61
|
+
function isLocalCode(code) {
|
|
62
|
+
return LOCAL_CODES.has(code);
|
|
63
|
+
}
|
|
64
|
+
var EnlittConfigurationError = class extends EnlittError {
|
|
65
|
+
name = "EnlittConfigurationError";
|
|
66
|
+
constructor(message) {
|
|
67
|
+
super("configuration_invalid", message);
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
var EnlittLoginRequiredError = class extends EnlittError {
|
|
71
|
+
name = "EnlittLoginRequiredError";
|
|
72
|
+
constructor(message, facts = {}) {
|
|
73
|
+
super(protocol.ENLITT_ERROR_CODE.personal_login_required, message, facts);
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
var EnlittLimitExceededError = class extends EnlittError {
|
|
77
|
+
name = "EnlittLimitExceededError";
|
|
78
|
+
limitRule;
|
|
79
|
+
constructor(message, limitRule, facts = {}) {
|
|
80
|
+
super(protocol.ENLITT_ERROR_CODE.spending_limit_exceeded, message, facts);
|
|
81
|
+
this.limitRule = limitRule;
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
var EnlittInsufficientCreditsError = class extends EnlittError {
|
|
85
|
+
name = "EnlittInsufficientCreditsError";
|
|
86
|
+
admissibleMaxChargeNanoUsd;
|
|
87
|
+
constructor(code, message, facts = {}) {
|
|
88
|
+
super(code, message, facts);
|
|
89
|
+
if (facts.admissibleMaxChargeNanoUsd !== void 0) {
|
|
90
|
+
this.admissibleMaxChargeNanoUsd = facts.admissibleMaxChargeNanoUsd;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
var EnlittSubscriptionInactiveError = class extends EnlittError {
|
|
95
|
+
name = "EnlittSubscriptionInactiveError";
|
|
96
|
+
constructor(message, facts = {}) {
|
|
97
|
+
super(protocol.ENLITT_ERROR_CODE.subscription_inactive, message, facts);
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
var EnlittRateLimitError = class extends EnlittError {
|
|
101
|
+
name = "EnlittRateLimitError";
|
|
102
|
+
constructor(message, facts = {}) {
|
|
103
|
+
super(protocol.ENLITT_ERROR_CODE.rate_limit_exceeded, message, facts);
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
var EnlittAuthenticationError = class extends EnlittError {
|
|
107
|
+
name = "EnlittAuthenticationError";
|
|
108
|
+
constructor(message, facts = {}) {
|
|
109
|
+
super(protocol.ENLITT_ERROR_CODE.invalid_api_key, message, facts);
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
var EnlittAuthorizationError = class extends EnlittError {
|
|
113
|
+
name = "EnlittAuthorizationError";
|
|
114
|
+
constructor(message, facts = {}) {
|
|
115
|
+
super(protocol.ENLITT_ERROR_CODE.insufficient_permissions, message, facts);
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
var WIRE_CODE_FACTORY = {
|
|
119
|
+
personal_login_required: (message, facts) => new EnlittLoginRequiredError(message, facts),
|
|
120
|
+
spending_limit_exceeded: (message, facts, extras) => new EnlittLimitExceededError(message, extras.limitRule ?? "unrecognized", facts),
|
|
121
|
+
premium_balance_exhausted: (message, facts, extras) => new EnlittInsufficientCreditsError(protocol.ENLITT_ERROR_CODE.premium_balance_exhausted, message, {
|
|
122
|
+
...facts,
|
|
123
|
+
...extras.admissibleMaxChargeNanoUsd !== void 0 ? { admissibleMaxChargeNanoUsd: extras.admissibleMaxChargeNanoUsd } : {}
|
|
124
|
+
}),
|
|
125
|
+
standard_balance_exhausted: (message, facts) => new EnlittInsufficientCreditsError(protocol.ENLITT_ERROR_CODE.standard_balance_exhausted, message, facts),
|
|
126
|
+
subscription_inactive: (message, facts) => new EnlittSubscriptionInactiveError(message, facts),
|
|
127
|
+
rate_limit_exceeded: (message, facts) => new EnlittRateLimitError(message, facts),
|
|
128
|
+
invalid_api_key: (message, facts) => new EnlittAuthenticationError(message, facts),
|
|
129
|
+
insufficient_permissions: (message, facts) => new EnlittAuthorizationError(message, facts),
|
|
130
|
+
dashboard_login_required: (message, facts) => new EnlittError(protocol.ENLITT_ERROR_CODE.dashboard_login_required, message, facts),
|
|
131
|
+
admin_authentication_required: (message, facts) => new EnlittError(protocol.ENLITT_ERROR_CODE.admin_authentication_required, message, facts),
|
|
132
|
+
conflict_error: (message, facts) => new EnlittError(protocol.ENLITT_ERROR_CODE.conflict_error, message, facts),
|
|
133
|
+
operation_in_progress: (message, facts) => new EnlittError(protocol.ENLITT_ERROR_CODE.operation_in_progress, message, facts),
|
|
134
|
+
idempotency_replay_unavailable: (message, facts) => new EnlittError(protocol.ENLITT_ERROR_CODE.idempotency_replay_unavailable, message, facts),
|
|
135
|
+
invalid_value: (message, facts) => new EnlittError(protocol.ENLITT_ERROR_CODE.invalid_value, message, facts),
|
|
136
|
+
unsupported_parameter: (message, facts) => new EnlittError(protocol.ENLITT_ERROR_CODE.unsupported_parameter, message, facts),
|
|
137
|
+
unsupported_value: (message, facts) => new EnlittError(protocol.ENLITT_ERROR_CODE.unsupported_value, message, facts),
|
|
138
|
+
reauthentication_required: (message, facts) => new EnlittError(protocol.ENLITT_ERROR_CODE.reauthentication_required, message, facts),
|
|
139
|
+
payment_declined: (message, facts) => new EnlittError(protocol.ENLITT_ERROR_CODE.payment_declined, message, facts),
|
|
140
|
+
invalid_sign_in_code: (message, facts) => new EnlittError(protocol.ENLITT_ERROR_CODE.invalid_sign_in_code, message, facts),
|
|
141
|
+
not_found: (message, facts) => new EnlittError(protocol.ENLITT_ERROR_CODE.not_found, message, facts),
|
|
142
|
+
request_too_large: (message, facts) => new EnlittError(protocol.ENLITT_ERROR_CODE.request_too_large, message, facts),
|
|
143
|
+
server_error: (message, facts) => new EnlittError(protocol.ENLITT_ERROR_CODE.server_error, message, facts),
|
|
144
|
+
provider_error: (message, facts) => new EnlittError(protocol.ENLITT_ERROR_CODE.provider_error, message, facts),
|
|
145
|
+
business_selection_required: (message, facts) => new EnlittError(protocol.ENLITT_ERROR_CODE.business_selection_required, message, facts),
|
|
146
|
+
bot_verification_failed: (message, facts) => new EnlittError(protocol.ENLITT_ERROR_CODE.bot_verification_failed, message, facts),
|
|
147
|
+
phone_verification_required: (message, facts) => new EnlittError(protocol.ENLITT_ERROR_CODE.phone_verification_required, message, facts),
|
|
148
|
+
invalid_phone_code: (message, facts) => new EnlittError(protocol.ENLITT_ERROR_CODE.invalid_phone_code, message, facts),
|
|
149
|
+
phone_number_not_supported: (message, facts) => new EnlittError(protocol.ENLITT_ERROR_CODE.phone_number_not_supported, message, facts),
|
|
150
|
+
phone_number_unavailable: (message, facts) => new EnlittError(protocol.ENLITT_ERROR_CODE.phone_number_unavailable, message, facts),
|
|
151
|
+
business_name_unavailable: (message, facts) => new EnlittError(protocol.ENLITT_ERROR_CODE.business_name_unavailable, message, facts),
|
|
152
|
+
// The four CLI device-flow codes (RFC 8628). No SDK route can return them, but
|
|
153
|
+
// the mapping is exhaustive over the record, so they surface as the base class.
|
|
154
|
+
authorization_pending: (message, facts) => new EnlittError(protocol.ENLITT_ERROR_CODE.authorization_pending, message, facts),
|
|
155
|
+
slow_down: (message, facts) => new EnlittError(protocol.ENLITT_ERROR_CODE.slow_down, message, facts),
|
|
156
|
+
access_denied: (message, facts) => new EnlittError(protocol.ENLITT_ERROR_CODE.access_denied, message, facts),
|
|
157
|
+
expired_token: (message, facts) => new EnlittError(protocol.ENLITT_ERROR_CODE.expired_token, message, facts)
|
|
158
|
+
};
|
|
159
|
+
function hasKind(value) {
|
|
160
|
+
return typeof value === "object" && value !== null && "kind" in value;
|
|
161
|
+
}
|
|
162
|
+
function parseRetryAfterMs(header) {
|
|
163
|
+
if (header === void 0) {
|
|
164
|
+
return void 0;
|
|
165
|
+
}
|
|
166
|
+
const seconds = Number(header);
|
|
167
|
+
if (!Number.isFinite(seconds) || seconds < 0) {
|
|
168
|
+
return void 0;
|
|
169
|
+
}
|
|
170
|
+
return seconds * 1e3;
|
|
171
|
+
}
|
|
172
|
+
function normalizeHttpErrorResponse(input) {
|
|
173
|
+
const requestId = input.headers["x-request-id"];
|
|
174
|
+
const classified = protocol.classifyEnlittErrorResponse(input.status, input.body);
|
|
175
|
+
if (classified === null) {
|
|
176
|
+
return new EnlittError(
|
|
177
|
+
"malformed_response",
|
|
178
|
+
`Enlitt returned HTTP ${String(input.status)} with a body that is not an Enlitt error.`,
|
|
179
|
+
requestId !== void 0 ? { requestId } : {}
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
const message = classified.message ?? "Enlitt refused the request.";
|
|
183
|
+
if (classified.recognized && protocol.isEnlittErrorCode(classified.code)) {
|
|
184
|
+
const retryAfterMs = parseRetryAfterMs(input.headers["retry-after"]);
|
|
185
|
+
const facts2 = {
|
|
186
|
+
...retryAfterMs !== void 0 ? { retryAfterMs } : {},
|
|
187
|
+
...requestId !== void 0 ? { requestId } : {},
|
|
188
|
+
...classified.authorizeUrl !== void 0 ? { authorizeUrl: classified.authorizeUrl } : {}
|
|
189
|
+
};
|
|
190
|
+
return WIRE_CODE_FACTORY[classified.code](message, facts2, {
|
|
191
|
+
...classified.limitRule !== void 0 ? { limitRule: classified.limitRule } : {},
|
|
192
|
+
...classified.admissibleMaxChargeNanoUsd !== void 0 ? { admissibleMaxChargeNanoUsd: classified.admissibleMaxChargeNanoUsd } : {}
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
const upgradeMessage = `Enlitt returned error code "${classified.code}" (HTTP ${String(classified.status)}, type "${classified.type ?? "none"}"), which this version of @enlitt/sdk does not recognize. Upgrade @enlitt/sdk to handle it.` + (classified.message !== null ? ` ${classified.message}` : "");
|
|
196
|
+
const facts = {
|
|
197
|
+
...requestId !== void 0 ? { requestId } : {},
|
|
198
|
+
...classified.authorizeUrl !== void 0 ? { authorizeUrl: classified.authorizeUrl } : {},
|
|
199
|
+
retryable: classified.retryable
|
|
200
|
+
};
|
|
201
|
+
if (classified.creditRefusal) {
|
|
202
|
+
return new EnlittInsufficientCreditsError(classified.code, upgradeMessage, facts);
|
|
203
|
+
}
|
|
204
|
+
return new EnlittError(classified.code, upgradeMessage, facts);
|
|
205
|
+
}
|
|
206
|
+
function normalizeEnlittModelError(error, providerInvoked) {
|
|
207
|
+
if (hasKind(error)) {
|
|
208
|
+
switch (error.kind) {
|
|
209
|
+
case "http_error":
|
|
210
|
+
return normalizeHttpErrorResponse(error);
|
|
211
|
+
case "transport_failed": {
|
|
212
|
+
const input2 = error;
|
|
213
|
+
return new EnlittError(
|
|
214
|
+
"transport_failed",
|
|
215
|
+
input2.message ?? "The request to Enlitt failed before a response was received."
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
case "request_canceled": {
|
|
219
|
+
const input2 = error;
|
|
220
|
+
return new EnlittError("request_canceled", input2.message ?? "The request was canceled before it completed.");
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
const input = hasKind(error) && error.kind === "malformed_response" ? error : void 0;
|
|
225
|
+
return new EnlittError("malformed_response", input?.message ?? "Enlitt's response could not be parsed.");
|
|
226
|
+
}
|
|
227
|
+
var ENLITT_SESSION_COOKIE_NAME = "enlitt_session";
|
|
228
|
+
var MAX_SESSION_TOKEN_LENGTH = 4096;
|
|
229
|
+
function enlittSession(token) {
|
|
230
|
+
if (typeof token !== "string" || token.length === 0 || token.length > MAX_SESSION_TOKEN_LENGTH) {
|
|
231
|
+
throw new EnlittConfigurationError(
|
|
232
|
+
`enlittSession() requires a non-empty session token no longer than ${MAX_SESSION_TOKEN_LENGTH} characters.`
|
|
233
|
+
);
|
|
234
|
+
}
|
|
235
|
+
return { token };
|
|
236
|
+
}
|
|
237
|
+
var sessionContext = new async_hooks.AsyncLocalStorage();
|
|
238
|
+
function enlittSessionMiddleware(options) {
|
|
239
|
+
const cookieName = options?.cookieName ?? ENLITT_SESSION_COOKIE_NAME;
|
|
240
|
+
return async function enlittMiddleware(request, next) {
|
|
241
|
+
const token = readCookie(request, cookieName);
|
|
242
|
+
const session = token === null ? null : enlittSession(token);
|
|
243
|
+
return sessionContext.run(session, next);
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
function runWithEnlittSession(session, fn) {
|
|
247
|
+
return sessionContext.run(session, fn);
|
|
248
|
+
}
|
|
249
|
+
function getEnlittSession() {
|
|
250
|
+
if (!hasEnlittSessionContext()) {
|
|
251
|
+
throw new EnlittConfigurationError(
|
|
252
|
+
"getEnlittSession() was called with no enlittSessionMiddleware() (or runWithEnlittSession()) context installed on this request path."
|
|
253
|
+
);
|
|
254
|
+
}
|
|
255
|
+
return sessionContext.getStore() ?? null;
|
|
256
|
+
}
|
|
257
|
+
function hasEnlittSessionContext() {
|
|
258
|
+
return sessionContext.getStore() !== void 0;
|
|
259
|
+
}
|
|
260
|
+
function readCookie(request, name) {
|
|
261
|
+
const header = request.headers.get("cookie");
|
|
262
|
+
if (header === null) {
|
|
263
|
+
return null;
|
|
264
|
+
}
|
|
265
|
+
for (const part of header.split(";")) {
|
|
266
|
+
const separatorIndex = part.indexOf("=");
|
|
267
|
+
if (separatorIndex === -1) {
|
|
268
|
+
continue;
|
|
269
|
+
}
|
|
270
|
+
const rawName = part.slice(0, separatorIndex).trim();
|
|
271
|
+
if (rawName !== name) {
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
const rawValue = part.slice(separatorIndex + 1).trim();
|
|
275
|
+
try {
|
|
276
|
+
return decodeURIComponent(rawValue);
|
|
277
|
+
} catch {
|
|
278
|
+
return rawValue;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
return null;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// src/server/secrets.ts
|
|
285
|
+
var ENV_KEY = "ENLITT_SECRET_KEY";
|
|
286
|
+
var USABLE_SECRET = /^[!-~]+$/;
|
|
287
|
+
function assertServerEnvironment() {
|
|
288
|
+
if (typeof window !== "undefined" && typeof document !== "undefined") {
|
|
289
|
+
throw new EnlittConfigurationError(
|
|
290
|
+
"@enlitt/sdk: server-only module imported in a browser environment. Use @enlitt/sdk/browser for code you ship to consumers."
|
|
291
|
+
);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
assertServerEnvironment();
|
|
295
|
+
function readEnvironmentSecret() {
|
|
296
|
+
const runtime = globalThis;
|
|
297
|
+
return runtime.process?.env?.[ENV_KEY];
|
|
298
|
+
}
|
|
299
|
+
function resolveBusinessAuthorizationHeader(config) {
|
|
300
|
+
assertServerEnvironment();
|
|
301
|
+
const configured = config.secretKey;
|
|
302
|
+
const candidate = configured === void 0 ? readEnvironmentSecret() : configured;
|
|
303
|
+
if (typeof candidate !== "string" || !USABLE_SECRET.test(candidate)) {
|
|
304
|
+
throw new EnlittConfigurationError(
|
|
305
|
+
`@enlitt/sdk: no usable Enlitt secret key. Pass one as { secretKey } or set the ${ENV_KEY} environment variable on the server. The value must be a non-empty string of visible ASCII characters.`
|
|
306
|
+
);
|
|
307
|
+
}
|
|
308
|
+
return `Bearer ${candidate}`;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// src/core/transport.ts
|
|
312
|
+
var SDK_VERSION = "0.1.0";
|
|
313
|
+
var LOCAL_HTTP_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
314
|
+
var DEFAULT_RATE_LIMIT_FLOOR_MS = 1e3;
|
|
315
|
+
var DEFAULT_RATE_LIMIT_MAX_ATTEMPTS = 3;
|
|
316
|
+
var DEFAULT_RATE_LIMIT_MAX_TOTAL_WAIT_MS = 3e4;
|
|
317
|
+
var TERMINAL_REPORT_MAX_ATTEMPTS = 3;
|
|
318
|
+
var TERMINAL_REPORT_RETRY_DELAY_MS = 500;
|
|
319
|
+
var MAX_RESPONSE_HEADER_BYTES = 32 * 1024;
|
|
320
|
+
var MAX_RESPONSE_BODY_BYTES = 1024 * 1024;
|
|
321
|
+
function createInternalClient(options) {
|
|
322
|
+
assertServerRuntime();
|
|
323
|
+
const baseUrl = resolveBaseUrl(options.baseUrl);
|
|
324
|
+
const businessAuthorization = resolveBusinessAuthorizationHeader(
|
|
325
|
+
options.secretKey !== void 0 ? { secretKey: options.secretKey } : {}
|
|
326
|
+
);
|
|
327
|
+
const rateLimitOptions = options.rateLimit;
|
|
328
|
+
const maxAttempts = rateLimitOptions?.maxAttempts ?? DEFAULT_RATE_LIMIT_MAX_ATTEMPTS;
|
|
329
|
+
if (!Number.isSafeInteger(maxAttempts) || maxAttempts < 1) {
|
|
330
|
+
throw new EnlittConfigurationError("rateLimit.maxAttempts must be an integer of at least 1.");
|
|
331
|
+
}
|
|
332
|
+
const rateLimit = {
|
|
333
|
+
maxAttempts,
|
|
334
|
+
maxTotalWaitMs: rateLimitOptions?.maxTotalWaitMs ?? DEFAULT_RATE_LIMIT_MAX_TOTAL_WAIT_MS,
|
|
335
|
+
...rateLimitOptions?.onRateLimit !== void 0 ? { onRateLimit: rateLimitOptions.onRateLimit } : {}
|
|
336
|
+
};
|
|
337
|
+
const explicitSession = options.session;
|
|
338
|
+
return {
|
|
339
|
+
baseUrl,
|
|
340
|
+
businessAuthorization,
|
|
341
|
+
sdkVersion: SDK_VERSION,
|
|
342
|
+
resolveSession: () => {
|
|
343
|
+
if (explicitSession !== void 0) {
|
|
344
|
+
return explicitSession;
|
|
345
|
+
}
|
|
346
|
+
const session = getEnlittSession();
|
|
347
|
+
if (session === null) {
|
|
348
|
+
throw normalizeEnlittModelError(
|
|
349
|
+
{
|
|
350
|
+
kind: "http_error",
|
|
351
|
+
status: 401,
|
|
352
|
+
body: loginRequiredBody(),
|
|
353
|
+
headers: {}
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
return session;
|
|
357
|
+
},
|
|
358
|
+
rateLimit,
|
|
359
|
+
...options.onTerminalReportError !== void 0 ? { onTerminalReportError: options.onTerminalReportError } : {}
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
var DEFAULT_ENLITT_ORIGIN = "https://api.enlitt.com";
|
|
363
|
+
var BASE_URL_ENV_KEY = "ENLITT_BASE_URL";
|
|
364
|
+
function assertServerRuntime() {
|
|
365
|
+
if (typeof window !== "undefined" && typeof document !== "undefined") {
|
|
366
|
+
throw new EnlittConfigurationError(
|
|
367
|
+
"enlitt() was called in a browser environment. It is server-only; ship @enlitt/sdk/browser to consumers instead."
|
|
368
|
+
);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
function resolveBaseUrl(optionBaseUrl) {
|
|
372
|
+
const candidate = optionBaseUrl ?? readBaseUrlFromEnv() ?? DEFAULT_ENLITT_ORIGIN;
|
|
373
|
+
try {
|
|
374
|
+
assertHttps(candidate);
|
|
375
|
+
} catch (thrown) {
|
|
376
|
+
if (thrown instanceof EnlittConfigurationError) {
|
|
377
|
+
throw thrown;
|
|
378
|
+
}
|
|
379
|
+
throw new EnlittConfigurationError(`Enlitt base URL is not a valid URL: ${String(candidate)}.`);
|
|
380
|
+
}
|
|
381
|
+
return candidate;
|
|
382
|
+
}
|
|
383
|
+
function readBaseUrlFromEnv() {
|
|
384
|
+
const runtime = globalThis;
|
|
385
|
+
return runtime.process?.env?.[BASE_URL_ENV_KEY];
|
|
386
|
+
}
|
|
387
|
+
function loginRequiredBody() {
|
|
388
|
+
return {
|
|
389
|
+
error: {
|
|
390
|
+
message: "No Enlitt session is available for this request. Send the user through Enlitt login.",
|
|
391
|
+
type: "authentication_error",
|
|
392
|
+
param: null,
|
|
393
|
+
code: protocol.ENLITT_ERROR_CODE.personal_login_required
|
|
394
|
+
}
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
async function requestEnlitt(client, init) {
|
|
398
|
+
assertHttps(client.baseUrl);
|
|
399
|
+
const url = new URL(init.path, client.baseUrl).toString();
|
|
400
|
+
const session = client.resolveSession();
|
|
401
|
+
const headers = {
|
|
402
|
+
Authorization: client.businessAuthorization,
|
|
403
|
+
"X-Enlitt-User-Authorization": `Bearer ${session.token}`,
|
|
404
|
+
Accept: init.accept,
|
|
405
|
+
"X-Request-Id": generateRequestId(),
|
|
406
|
+
[protocol.ENLITT_VERSION_HEADER]: protocol.ENLITT_API_VERSION,
|
|
407
|
+
"X-Enlitt-SDK-Version": client.sdkVersion
|
|
408
|
+
};
|
|
409
|
+
if (init.method !== "GET") {
|
|
410
|
+
if (init.callId === void 0) {
|
|
411
|
+
throw new EnlittConfigurationError("An Enlitt POST request requires a call ID for its Idempotency-Key.");
|
|
412
|
+
}
|
|
413
|
+
headers["Idempotency-Key"] = init.callId;
|
|
414
|
+
headers["Content-Type"] = "application/json";
|
|
415
|
+
}
|
|
416
|
+
const waitStartedAtMs = Date.now();
|
|
417
|
+
for (let attempt = 1; ; attempt++) {
|
|
418
|
+
const response = await sendOnce(url, headers, init);
|
|
419
|
+
if (response.ok) {
|
|
420
|
+
assertBoundedResponse(response);
|
|
421
|
+
return response;
|
|
422
|
+
}
|
|
423
|
+
const error = await normalizeResponse(response);
|
|
424
|
+
if (error.code !== protocol.ENLITT_ERROR_CODE.rate_limit_exceeded) {
|
|
425
|
+
throw error;
|
|
426
|
+
}
|
|
427
|
+
const canRetry = attempt < client.rateLimit.maxAttempts && Date.now() - waitStartedAtMs < client.rateLimit.maxTotalWaitMs;
|
|
428
|
+
if (!canRetry) {
|
|
429
|
+
throw error;
|
|
430
|
+
}
|
|
431
|
+
const floorMs = error.retryAfterMs ?? DEFAULT_RATE_LIMIT_FLOOR_MS;
|
|
432
|
+
const delayMs = floorMs + Math.random() * (floorMs / 2);
|
|
433
|
+
client.rateLimit.onRateLimit?.(attempt, delayMs);
|
|
434
|
+
await sleep(delayMs, init.signal);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
async function reportEnlittPremiumTerminal(client, init) {
|
|
438
|
+
for (let attempt = 1; ; attempt++) {
|
|
439
|
+
try {
|
|
440
|
+
return await requestEnlitt(client, init);
|
|
441
|
+
} catch (thrown) {
|
|
442
|
+
const error = thrown instanceof EnlittError ? thrown : normalizeEnlittModelError(thrown);
|
|
443
|
+
const canRetry = isTransientTerminalReportFailure(error) && attempt < TERMINAL_REPORT_MAX_ATTEMPTS;
|
|
444
|
+
if (!canRetry) {
|
|
445
|
+
client.onTerminalReportError?.(error);
|
|
446
|
+
throw error;
|
|
447
|
+
}
|
|
448
|
+
await sleep(TERMINAL_REPORT_RETRY_DELAY_MS, init.signal);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
function isTransientTerminalReportFailure(error) {
|
|
453
|
+
if (error.code === "transport_failed") {
|
|
454
|
+
return true;
|
|
455
|
+
}
|
|
456
|
+
return error.retryable && error.code !== protocol.ENLITT_ERROR_CODE.rate_limit_exceeded;
|
|
457
|
+
}
|
|
458
|
+
async function sendOnce(url, headers, init) {
|
|
459
|
+
let response;
|
|
460
|
+
try {
|
|
461
|
+
response = await fetch(url, {
|
|
462
|
+
method: init.method ?? "POST",
|
|
463
|
+
headers,
|
|
464
|
+
...init.method === "GET" ? {} : { body: JSON.stringify(init.body) },
|
|
465
|
+
redirect: "manual",
|
|
466
|
+
...init.signal !== void 0 ? { signal: init.signal } : {}
|
|
467
|
+
});
|
|
468
|
+
} catch (thrown) {
|
|
469
|
+
const message = describeThrown(thrown);
|
|
470
|
+
if (init.signal?.aborted === true) {
|
|
471
|
+
throw normalizeEnlittModelError(
|
|
472
|
+
{ kind: "request_canceled", ...message !== void 0 ? { message } : {} });
|
|
473
|
+
}
|
|
474
|
+
throw normalizeEnlittModelError(
|
|
475
|
+
{ kind: "transport_failed", ...message !== void 0 ? { message } : {} });
|
|
476
|
+
}
|
|
477
|
+
if (isRedirectResponse(response)) throw redirectRefused(response);
|
|
478
|
+
return response;
|
|
479
|
+
}
|
|
480
|
+
var REDIRECT_REFUSED_MESSAGE = "Enlitt answered with a redirect, which the SDK never follows.";
|
|
481
|
+
function isRedirectResponse(response) {
|
|
482
|
+
return response.type === "opaqueredirect" || response.status >= 300 && response.status < 400;
|
|
483
|
+
}
|
|
484
|
+
function redirectRefused(response) {
|
|
485
|
+
void response.body?.cancel().catch(() => void 0);
|
|
486
|
+
return normalizeEnlittModelError(
|
|
487
|
+
{ kind: "transport_failed", message: REDIRECT_REFUSED_MESSAGE });
|
|
488
|
+
}
|
|
489
|
+
async function normalizeResponse(response) {
|
|
490
|
+
if (!isBoundedHeaderSet(response.headers)) {
|
|
491
|
+
return normalizeEnlittModelError(
|
|
492
|
+
{ kind: "malformed_response", message: "Response headers exceeded the bounded size." });
|
|
493
|
+
}
|
|
494
|
+
const text = await readBoundedBody(response);
|
|
495
|
+
if (text === void 0) {
|
|
496
|
+
return normalizeEnlittModelError(
|
|
497
|
+
{ kind: "malformed_response", message: "Response body exceeded the bounded size." });
|
|
498
|
+
}
|
|
499
|
+
let body;
|
|
500
|
+
try {
|
|
501
|
+
body = JSON.parse(text);
|
|
502
|
+
} catch {
|
|
503
|
+
return normalizeEnlittModelError(
|
|
504
|
+
{ kind: "malformed_response", message: "Response body was not valid JSON." });
|
|
505
|
+
}
|
|
506
|
+
return normalizeEnlittModelError(
|
|
507
|
+
{
|
|
508
|
+
kind: "http_error",
|
|
509
|
+
status: response.status,
|
|
510
|
+
body,
|
|
511
|
+
headers: {
|
|
512
|
+
"retry-after": response.headers.get("retry-after") ?? void 0,
|
|
513
|
+
"x-request-id": response.headers.get("x-request-id") ?? void 0
|
|
514
|
+
}
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
function isBoundedHeaderSet(headers) {
|
|
518
|
+
let total = 0;
|
|
519
|
+
for (const [name, value] of headers.entries()) {
|
|
520
|
+
total += name.length + value.length;
|
|
521
|
+
if (total > MAX_RESPONSE_HEADER_BYTES) {
|
|
522
|
+
return false;
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
return true;
|
|
526
|
+
}
|
|
527
|
+
async function readBoundedBody(response) {
|
|
528
|
+
const contentLength = response.headers.get("content-length");
|
|
529
|
+
if (contentLength !== null && Number(contentLength) > MAX_RESPONSE_BODY_BYTES) {
|
|
530
|
+
return void 0;
|
|
531
|
+
}
|
|
532
|
+
const body = response.body;
|
|
533
|
+
if (body === null) {
|
|
534
|
+
return "";
|
|
535
|
+
}
|
|
536
|
+
const reader = body.getReader();
|
|
537
|
+
const chunks = [];
|
|
538
|
+
let total = 0;
|
|
539
|
+
try {
|
|
540
|
+
for (; ; ) {
|
|
541
|
+
const { done, value } = await reader.read();
|
|
542
|
+
if (done) {
|
|
543
|
+
break;
|
|
544
|
+
}
|
|
545
|
+
total += value.byteLength;
|
|
546
|
+
if (total > MAX_RESPONSE_BODY_BYTES) {
|
|
547
|
+
await reader.cancel();
|
|
548
|
+
return void 0;
|
|
549
|
+
}
|
|
550
|
+
chunks.push(value);
|
|
551
|
+
}
|
|
552
|
+
} finally {
|
|
553
|
+
reader.releaseLock();
|
|
554
|
+
}
|
|
555
|
+
return new TextDecoder().decode(concatChunks(chunks, total));
|
|
556
|
+
}
|
|
557
|
+
async function readEnlittJson(response) {
|
|
558
|
+
const text = await readBoundedBody(response);
|
|
559
|
+
if (text === void 0) {
|
|
560
|
+
throw normalizeEnlittModelError(
|
|
561
|
+
{ kind: "malformed_response", message: "Response body exceeded the bounded size." });
|
|
562
|
+
}
|
|
563
|
+
try {
|
|
564
|
+
return JSON.parse(text);
|
|
565
|
+
} catch {
|
|
566
|
+
throw normalizeEnlittModelError(
|
|
567
|
+
{ kind: "malformed_response", message: "Response body was not valid JSON." });
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
function concatChunks(chunks, total) {
|
|
571
|
+
const merged = new Uint8Array(total);
|
|
572
|
+
let offset = 0;
|
|
573
|
+
for (const chunk of chunks) {
|
|
574
|
+
merged.set(chunk, offset);
|
|
575
|
+
offset += chunk.byteLength;
|
|
576
|
+
}
|
|
577
|
+
return merged;
|
|
578
|
+
}
|
|
579
|
+
function assertBoundedResponse(response) {
|
|
580
|
+
if (!isBoundedHeaderSet(response.headers)) {
|
|
581
|
+
throw normalizeEnlittModelError(
|
|
582
|
+
{ kind: "malformed_response", message: "Response headers exceeded the bounded size." });
|
|
583
|
+
}
|
|
584
|
+
const contentLength = response.headers.get("content-length");
|
|
585
|
+
if (contentLength !== null && Number(contentLength) > MAX_RESPONSE_BODY_BYTES) {
|
|
586
|
+
throw normalizeEnlittModelError(
|
|
587
|
+
{ kind: "malformed_response", message: "Response body exceeded the bounded size." });
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
function assertHttps(baseUrl) {
|
|
591
|
+
const parsed = new URL(baseUrl);
|
|
592
|
+
if (parsed.protocol === "https:") {
|
|
593
|
+
return;
|
|
594
|
+
}
|
|
595
|
+
if (parsed.protocol === "http:" && LOCAL_HTTP_HOSTS.has(parsed.hostname)) {
|
|
596
|
+
return;
|
|
597
|
+
}
|
|
598
|
+
throw new EnlittConfigurationError(
|
|
599
|
+
`Enlitt base URL must use https: outside local development (got ${parsed.protocol} for host ${parsed.hostname}). There is no environment flag that relaxes this.`
|
|
600
|
+
);
|
|
601
|
+
}
|
|
602
|
+
function generateRequestId() {
|
|
603
|
+
return crypto.randomUUID();
|
|
604
|
+
}
|
|
605
|
+
function describeThrown(thrown) {
|
|
606
|
+
if (thrown instanceof Error) {
|
|
607
|
+
return thrown.message.slice(0, 500);
|
|
608
|
+
}
|
|
609
|
+
return void 0;
|
|
610
|
+
}
|
|
611
|
+
function sleep(delayMs, signal) {
|
|
612
|
+
if (signal?.aborted === true) {
|
|
613
|
+
return Promise.reject(signal.reason);
|
|
614
|
+
}
|
|
615
|
+
return new Promise((resolve, reject) => {
|
|
616
|
+
const timer = setTimeout(() => {
|
|
617
|
+
signal?.removeEventListener("abort", onAbort);
|
|
618
|
+
resolve();
|
|
619
|
+
}, delayMs);
|
|
620
|
+
function onAbort() {
|
|
621
|
+
clearTimeout(timer);
|
|
622
|
+
reject(signal?.reason);
|
|
623
|
+
}
|
|
624
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
625
|
+
});
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
// src/core/premium.ts
|
|
629
|
+
var VISIBLE_ASCII = /^[\x21-\x7e]+$/;
|
|
630
|
+
var IDEMPOTENCY_KEY_OPTION_MIN_LENGTH = protocol.IDEMPOTENCY_KEY_MIN_LENGTH;
|
|
631
|
+
var IDEMPOTENCY_KEY_OPTION_MAX_LENGTH = 200;
|
|
632
|
+
function assertNanoUsd(value, label) {
|
|
633
|
+
try {
|
|
634
|
+
protocol.parseCanonicalInteger(value, label);
|
|
635
|
+
} catch (thrown) {
|
|
636
|
+
if (thrown instanceof protocol.CanonicalIntegerError) {
|
|
637
|
+
throw new EnlittConfigurationError(thrown.message);
|
|
638
|
+
}
|
|
639
|
+
throw thrown;
|
|
640
|
+
}
|
|
641
|
+
return value;
|
|
642
|
+
}
|
|
643
|
+
function assertIdempotencyKeyBase(value, label) {
|
|
644
|
+
if (typeof value !== "string" || value.length < IDEMPOTENCY_KEY_OPTION_MIN_LENGTH || value.length > IDEMPOTENCY_KEY_OPTION_MAX_LENGTH || !VISIBLE_ASCII.test(value)) {
|
|
645
|
+
throw new EnlittConfigurationError(
|
|
646
|
+
`${label} must be ${IDEMPOTENCY_KEY_OPTION_MIN_LENGTH}-${IDEMPOTENCY_KEY_OPTION_MAX_LENGTH} visible ASCII characters.`
|
|
647
|
+
);
|
|
648
|
+
}
|
|
649
|
+
return value;
|
|
650
|
+
}
|
|
651
|
+
function assertReportingDeadlineMs(value, label) {
|
|
652
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) {
|
|
653
|
+
throw new EnlittConfigurationError(`${label} must be a positive safe integer.`);
|
|
654
|
+
}
|
|
655
|
+
return value;
|
|
656
|
+
}
|
|
657
|
+
function assertCallerMetadata(value, label) {
|
|
658
|
+
const validated = protocol.validateCallerMetadata(value, label);
|
|
659
|
+
if (!validated.ok) {
|
|
660
|
+
throw new EnlittConfigurationError(`${validated.error.message} (${validated.error.param})`);
|
|
661
|
+
}
|
|
662
|
+
return validated.value;
|
|
663
|
+
}
|
|
664
|
+
function assertCallId(callId) {
|
|
665
|
+
try {
|
|
666
|
+
return protocol.assertIdempotencyKey(callId);
|
|
667
|
+
} catch (thrown) {
|
|
668
|
+
if (thrown instanceof protocol.IdempotencyKeyError) {
|
|
669
|
+
throw new EnlittConfigurationError(
|
|
670
|
+
`The call ID "${callId}" is not a valid Idempotency-Key (must be ${protocol.IDEMPOTENCY_KEY_MIN_LENGTH}-${protocol.IDEMPOTENCY_KEY_MAX_LENGTH} visible ASCII characters).`
|
|
671
|
+
);
|
|
672
|
+
}
|
|
673
|
+
throw thrown;
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
function generateRandomCallId() {
|
|
677
|
+
return crypto.randomUUID();
|
|
678
|
+
}
|
|
679
|
+
var BEGIN_PREMIUM_OPERATION_PATH = "/v1/enlitt/operations";
|
|
680
|
+
function terminalReportPath(operationId) {
|
|
681
|
+
return `/v1/enlitt/operations/${encodeURIComponent(operationId)}/terminal`;
|
|
682
|
+
}
|
|
683
|
+
async function beginPremiumOperation(client, request, callId) {
|
|
684
|
+
const body = {
|
|
685
|
+
mode: "premium",
|
|
686
|
+
max_charge_nano_usd: request.maxCharge,
|
|
687
|
+
provider: { id: request.provider.id, model: request.provider.model }
|
|
688
|
+
};
|
|
689
|
+
if (request.reportingDeadlineMs !== void 0) {
|
|
690
|
+
body.reporting_deadline_ms = request.reportingDeadlineMs;
|
|
691
|
+
}
|
|
692
|
+
if (request.metadata !== void 0) {
|
|
693
|
+
body.metadata = request.metadata;
|
|
694
|
+
}
|
|
695
|
+
const validated = protocol.validateBeginPremiumOperationRequest(body);
|
|
696
|
+
if (!validated.ok) {
|
|
697
|
+
throw new EnlittConfigurationError(
|
|
698
|
+
`The premium operation request is invalid: ${validated.error.message} (${validated.error.param}).`
|
|
699
|
+
);
|
|
700
|
+
}
|
|
701
|
+
const response = await requestEnlitt(client, {
|
|
702
|
+
path: BEGIN_PREMIUM_OPERATION_PATH,
|
|
703
|
+
body: validated.value,
|
|
704
|
+
callId,
|
|
705
|
+
accept: "application/json",
|
|
706
|
+
...request.signal !== void 0 ? { signal: request.signal } : {}
|
|
707
|
+
});
|
|
708
|
+
const parsed = protocol.validateBeginPremiumOperationResponse(await readEnlittJson(response), { mode: "tolerant" });
|
|
709
|
+
if (!parsed.ok) {
|
|
710
|
+
throw new EnlittError(
|
|
711
|
+
"malformed_response",
|
|
712
|
+
`Enlitt's premium operation response could not be validated: ${parsed.error.message} (${parsed.error.param}).`
|
|
713
|
+
);
|
|
714
|
+
}
|
|
715
|
+
return {
|
|
716
|
+
operationId: parsed.value.operation_id,
|
|
717
|
+
effectiveMaxChargeNanoUsd: parsed.value.effective_max_charge_nano_usd,
|
|
718
|
+
terminalDeadline: parsed.value.terminal_deadline
|
|
719
|
+
};
|
|
720
|
+
}
|
|
721
|
+
async function reportPremiumTerminalState(client, operation, report) {
|
|
722
|
+
const body = {
|
|
723
|
+
report_id: report.reportId,
|
|
724
|
+
status: report.status,
|
|
725
|
+
charge_nano_usd: report.chargeNanoUsd
|
|
726
|
+
};
|
|
727
|
+
if (report.usage !== void 0) {
|
|
728
|
+
const usage = {};
|
|
729
|
+
if (report.usage.inputTokens !== void 0) usage.input_tokens = report.usage.inputTokens;
|
|
730
|
+
if (report.usage.outputTokens !== void 0) usage.output_tokens = report.usage.outputTokens;
|
|
731
|
+
if (report.usage.cachedInputTokens !== void 0) usage.cached_input_tokens = report.usage.cachedInputTokens;
|
|
732
|
+
if (report.usage.reasoningTokens !== void 0) usage.reasoning_tokens = report.usage.reasoningTokens;
|
|
733
|
+
body.usage = usage;
|
|
734
|
+
}
|
|
735
|
+
if (report.finishReason !== void 0) body.finish_reason = report.finishReason;
|
|
736
|
+
if (report.providerResponseId !== void 0) body.provider_response_id = report.providerResponseId;
|
|
737
|
+
if (report.delivery !== void 0) {
|
|
738
|
+
body.delivery = { output_started: report.delivery.outputStarted, output_completed: report.delivery.outputCompleted };
|
|
739
|
+
}
|
|
740
|
+
if (report.timing !== void 0) {
|
|
741
|
+
body.timing = { started_at: report.timing.startedAt, ended_at: report.timing.endedAt };
|
|
742
|
+
}
|
|
743
|
+
if (report.errorCategory !== void 0) body.error_category = report.errorCategory;
|
|
744
|
+
const validated = protocol.validateReportPremiumTerminalRequest(body);
|
|
745
|
+
if (!validated.ok) {
|
|
746
|
+
client.onTerminalReportError?.(
|
|
747
|
+
new EnlittConfigurationError(
|
|
748
|
+
`The premium terminal report is invalid and was not sent: ${validated.error.message} (${validated.error.param}).`
|
|
749
|
+
)
|
|
750
|
+
);
|
|
751
|
+
return;
|
|
752
|
+
}
|
|
753
|
+
try {
|
|
754
|
+
const response = await reportEnlittPremiumTerminal(client, {
|
|
755
|
+
path: terminalReportPath(operation.operationId),
|
|
756
|
+
body: validated.value,
|
|
757
|
+
callId: report.reportId,
|
|
758
|
+
accept: "application/json"
|
|
759
|
+
});
|
|
760
|
+
const parsed = protocol.validateReportPremiumTerminalResponse(await readEnlittJson(response), { mode: "tolerant" });
|
|
761
|
+
if (!parsed.ok) {
|
|
762
|
+
client.onTerminalReportError?.(
|
|
763
|
+
new EnlittError(
|
|
764
|
+
"malformed_response",
|
|
765
|
+
`Enlitt's terminal report response could not be validated: ${parsed.error.message} (${parsed.error.param}).`
|
|
766
|
+
)
|
|
767
|
+
);
|
|
768
|
+
}
|
|
769
|
+
} catch (thrown) {
|
|
770
|
+
if (thrown instanceof EnlittError && thrown.code === "malformed_response") {
|
|
771
|
+
client.onTerminalReportError?.(thrown);
|
|
772
|
+
} else if (!(thrown instanceof EnlittError)) {
|
|
773
|
+
client.onTerminalReportError?.(normalizeEnlittModelError(thrown));
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
function isCancellation(thrown, signal) {
|
|
778
|
+
if (signal?.aborted === true) {
|
|
779
|
+
return true;
|
|
780
|
+
}
|
|
781
|
+
return typeof thrown === "object" && thrown !== null && thrown.name === "AbortError";
|
|
782
|
+
}
|
|
783
|
+
async function runPremiumCharge(client, request, run) {
|
|
784
|
+
const callId = assertCallId(request.callId ?? generateRandomCallId());
|
|
785
|
+
const operation = await beginPremiumOperation(client, request, callId);
|
|
786
|
+
const startedAt = /* @__PURE__ */ new Date();
|
|
787
|
+
let recordedChargeNanoUsd = "0";
|
|
788
|
+
let facts = {};
|
|
789
|
+
let reportSent = false;
|
|
790
|
+
const charge = (amountNanoUsd) => {
|
|
791
|
+
if (reportSent) {
|
|
792
|
+
throw new EnlittConfigurationError("charge() was called after the terminal report was sent.");
|
|
793
|
+
}
|
|
794
|
+
recordedChargeNanoUsd = assertNanoUsd(amountNanoUsd, "charge amount");
|
|
795
|
+
};
|
|
796
|
+
const handle = {
|
|
797
|
+
operationId: operation.operationId,
|
|
798
|
+
effectiveMaxChargeNanoUsd: operation.effectiveMaxChargeNanoUsd,
|
|
799
|
+
terminalDeadline: operation.terminalDeadline,
|
|
800
|
+
describe: (next) => {
|
|
801
|
+
facts = next;
|
|
802
|
+
}
|
|
803
|
+
};
|
|
804
|
+
const report = async (status) => {
|
|
805
|
+
reportSent = true;
|
|
806
|
+
const effective = BigInt(operation.effectiveMaxChargeNanoUsd);
|
|
807
|
+
const recorded = BigInt(recordedChargeNanoUsd);
|
|
808
|
+
const chargeNanoUsd = status === "failed" ? "0" : recorded > effective ? operation.effectiveMaxChargeNanoUsd : recordedChargeNanoUsd;
|
|
809
|
+
await reportPremiumTerminalState(client, operation, {
|
|
810
|
+
// The describe() timing wins when the business supplied one; otherwise
|
|
811
|
+
// the lifecycle's own bracket around `run` is the best content-free fact.
|
|
812
|
+
timing: { startedAt: startedAt.toISOString(), endedAt: (/* @__PURE__ */ new Date()).toISOString() },
|
|
813
|
+
...facts,
|
|
814
|
+
reportId: crypto.randomUUID(),
|
|
815
|
+
status,
|
|
816
|
+
chargeNanoUsd
|
|
817
|
+
});
|
|
818
|
+
};
|
|
819
|
+
let value;
|
|
820
|
+
try {
|
|
821
|
+
value = await run(charge, handle);
|
|
822
|
+
} catch (thrown) {
|
|
823
|
+
await report(isCancellation(thrown, request.signal) ? "canceled" : "failed");
|
|
824
|
+
throw thrown;
|
|
825
|
+
}
|
|
826
|
+
await report("completed");
|
|
827
|
+
return value;
|
|
828
|
+
}
|
|
829
|
+
async function withPremiumCharge(options, run) {
|
|
830
|
+
const client = createInternalClient({
|
|
831
|
+
...options.secretKey !== void 0 ? { secretKey: options.secretKey } : {},
|
|
832
|
+
...options.baseUrl !== void 0 ? { baseUrl: options.baseUrl } : {},
|
|
833
|
+
...options.session !== void 0 ? { session: options.session } : {},
|
|
834
|
+
...options.rateLimit !== void 0 ? { rateLimit: options.rateLimit } : {},
|
|
835
|
+
...options.onTerminalReportError !== void 0 ? { onTerminalReportError: options.onTerminalReportError } : {}
|
|
836
|
+
});
|
|
837
|
+
const maxCharge = assertNanoUsd(options.maxCharge, "maxCharge");
|
|
838
|
+
const callId = options.idempotencyKey !== void 0 ? assertIdempotencyKeyBase(options.idempotencyKey, "idempotencyKey") : void 0;
|
|
839
|
+
const reportingDeadlineMs = options.reportingDeadlineMs !== void 0 ? assertReportingDeadlineMs(options.reportingDeadlineMs, "reportingDeadlineMs") : void 0;
|
|
840
|
+
const metadata = options.metadata !== void 0 ? assertCallerMetadata(options.metadata, "metadata") : void 0;
|
|
841
|
+
return runPremiumCharge(
|
|
842
|
+
client,
|
|
843
|
+
{
|
|
844
|
+
maxCharge,
|
|
845
|
+
provider: { id: options.provider.id, model: options.provider.model },
|
|
846
|
+
...callId !== void 0 ? { callId } : {},
|
|
847
|
+
...reportingDeadlineMs !== void 0 ? { reportingDeadlineMs } : {},
|
|
848
|
+
...metadata !== void 0 ? { metadata } : {},
|
|
849
|
+
...options.signal !== void 0 ? { signal: options.signal } : {}
|
|
850
|
+
},
|
|
851
|
+
run
|
|
852
|
+
);
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
exports.ENLITT_SESSION_COOKIE_NAME = ENLITT_SESSION_COOKIE_NAME;
|
|
856
|
+
exports.EnlittAuthenticationError = EnlittAuthenticationError;
|
|
857
|
+
exports.EnlittAuthorizationError = EnlittAuthorizationError;
|
|
858
|
+
exports.EnlittConfigurationError = EnlittConfigurationError;
|
|
859
|
+
exports.EnlittError = EnlittError;
|
|
860
|
+
exports.EnlittInsufficientCreditsError = EnlittInsufficientCreditsError;
|
|
861
|
+
exports.EnlittLimitExceededError = EnlittLimitExceededError;
|
|
862
|
+
exports.EnlittLoginRequiredError = EnlittLoginRequiredError;
|
|
863
|
+
exports.EnlittRateLimitError = EnlittRateLimitError;
|
|
864
|
+
exports.EnlittSubscriptionInactiveError = EnlittSubscriptionInactiveError;
|
|
865
|
+
exports.assertCallId = assertCallId;
|
|
866
|
+
exports.assertCallerMetadata = assertCallerMetadata;
|
|
867
|
+
exports.assertIdempotencyKeyBase = assertIdempotencyKeyBase;
|
|
868
|
+
exports.assertNanoUsd = assertNanoUsd;
|
|
869
|
+
exports.assertReportingDeadlineMs = assertReportingDeadlineMs;
|
|
870
|
+
exports.createInternalClient = createInternalClient;
|
|
871
|
+
exports.enlittSession = enlittSession;
|
|
872
|
+
exports.enlittSessionMiddleware = enlittSessionMiddleware;
|
|
873
|
+
exports.generateRandomCallId = generateRandomCallId;
|
|
874
|
+
exports.getEnlittSession = getEnlittSession;
|
|
875
|
+
exports.isCancellation = isCancellation;
|
|
876
|
+
exports.readEnlittJson = readEnlittJson;
|
|
877
|
+
exports.requestEnlitt = requestEnlitt;
|
|
878
|
+
exports.resolveBusinessAuthorizationHeader = resolveBusinessAuthorizationHeader;
|
|
879
|
+
exports.runPremiumCharge = runPremiumCharge;
|
|
880
|
+
exports.runWithEnlittSession = runWithEnlittSession;
|
|
881
|
+
exports.withPremiumCharge = withPremiumCharge;
|
|
882
|
+
//# sourceMappingURL=chunk-26SW63P5.cjs.map
|
|
883
|
+
//# sourceMappingURL=chunk-26SW63P5.cjs.map
|