@scalemule/nextjs 0.1.69 → 0.1.71
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/dist/ai-DFsYPvk8.d.mts +270 -0
- package/dist/ai-DFsYPvk8.d.ts +270 -0
- package/dist/server/ai.d.mts +2 -0
- package/dist/server/ai.d.ts +2 -0
- package/dist/server/ai.js +425 -0
- package/dist/server/ai.mjs +421 -0
- package/dist/server/index.d.mts +4 -151
- package/dist/server/index.d.ts +4 -151
- package/dist/server/index.js +224 -3
- package/dist/server/index.mjs +223 -4
- package/package.json +7 -1
package/dist/server/index.d.ts
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
import { S as ServerConfig } from '../webhook-handler-C7XK0Tjs.js';
|
|
2
2
|
export { a as ScaleMuleServer, V as VideoFailedEvent, b as VideoReadyEvent, c as VideoTranscodedEvent, d as VideoUploadedEvent, W as WebhookEvent, e as WebhookRoutesConfig, f as createServerClient, g as createWebhookHandler, h as createWebhookRoutes, p as parseWebhookEvent, r as registerVideoWebhook, i as resolveGatewayUrl, v as verifyWebhookSignature } from '../webhook-handler-C7XK0Tjs.js';
|
|
3
3
|
import { q as ClientContext, A as ApiError } from '../index-BOPHR50i.js';
|
|
4
|
+
import { S as SessionCookieOptions, a as SessionData } from '../ai-DFsYPvk8.js';
|
|
5
|
+
export { A as AiAccountResolver, b as AiRoutesConfig, K as KNOWN_ACCOUNTS_COOKIE_NAME, c as KnownAccountEntry, d as SESSION_COOKIE_NAME, e as ServiceAiClientConfig, U as USER_ID_COOKIE_NAME, f as appendKnownAccountCookie, g as clearKnownAccountsCookie, h as clearSession, i as createAiRoutes, j as createServiceAiClient, k as getKnownAccountsCookieRaw, l as getKnownAccountsFromRequest, m as getSession, n as getSessionFromRequest, o as normalizeKnownAccountsCookie, r as removeKnownAccountFromCookie, p as requireSession, w as withSession } from '../ai-DFsYPvk8.js';
|
|
4
6
|
export { L as LedveryRoutesConfig, a as LedverySessionData, S as SM_LEDVERY_ACCESS_TOKEN_COOKIE, b as SM_LEDVERY_ID_TOKEN_COOKIE, c as SM_LEDVERY_NONCE_COOKIE, d as SM_LEDVERY_PKCE_VERIFIER_COOKIE, e as SM_LEDVERY_STATE_COOKIE, f as createLedveryRoutes, g as getLedverySession } from '../ledvery-CxPzZpxP.js';
|
|
5
7
|
import { NextRequest, NextResponse } from 'next/server';
|
|
6
8
|
import '@scalemule/sdk';
|
|
7
9
|
import '@scalemule/money';
|
|
10
|
+
import '@scalemule/ai';
|
|
8
11
|
|
|
9
12
|
/**
|
|
10
13
|
* Client Context Extraction Utilities (Next.js)
|
|
@@ -109,156 +112,6 @@ declare function buildClientContextHeaders(context: ClientContext | undefined):
|
|
|
109
112
|
*/
|
|
110
113
|
declare function buildFlagContext(clientContext: Pick<ClientContext, 'ip'> | undefined, extraContext?: Record<string, unknown>): Record<string, unknown>;
|
|
111
114
|
|
|
112
|
-
/**
|
|
113
|
-
* Cookie Utilities for Secure Session Management
|
|
114
|
-
*
|
|
115
|
-
* Handles HTTP-only secure cookies for authentication.
|
|
116
|
-
* Tokens are never exposed to the browser.
|
|
117
|
-
*/
|
|
118
|
-
declare const SESSION_COOKIE_NAME = "sm_session";
|
|
119
|
-
declare const USER_ID_COOKIE_NAME = "sm_user_id";
|
|
120
|
-
/**
|
|
121
|
-
* Known accounts cookie — stores display metadata (email, name, avatar) for
|
|
122
|
-
* accounts that have logged in on this device. NOT httpOnly so client JS can
|
|
123
|
-
* read it to render the account switcher UI. Contains NO tokens or secrets.
|
|
124
|
-
*/
|
|
125
|
-
declare const KNOWN_ACCOUNTS_COOKIE_NAME = "sm_known_accounts";
|
|
126
|
-
interface SessionCookieOptions {
|
|
127
|
-
/** Isolate an embedded session in the top-level site cookie partition (CHIPS). */
|
|
128
|
-
partitioned?: boolean;
|
|
129
|
-
/** Cookie max age in seconds (default: 7 days) */
|
|
130
|
-
maxAge?: number;
|
|
131
|
-
/** Cookie domain (default: current domain) */
|
|
132
|
-
domain?: string;
|
|
133
|
-
/** Cookie path (default: '/') */
|
|
134
|
-
path?: string;
|
|
135
|
-
/** SameSite attribute (default: 'lax') */
|
|
136
|
-
sameSite?: 'strict' | 'lax' | 'none';
|
|
137
|
-
/** Whether to use secure cookies (default: true in production) */
|
|
138
|
-
secure?: boolean;
|
|
139
|
-
}
|
|
140
|
-
interface SessionData {
|
|
141
|
-
sessionToken: string;
|
|
142
|
-
userId: string;
|
|
143
|
-
expiresAt: Date;
|
|
144
|
-
}
|
|
145
|
-
/**
|
|
146
|
-
* Create a Response with session cookies set
|
|
147
|
-
*
|
|
148
|
-
* Use this after successful login to set HTTP-only cookies and return user data.
|
|
149
|
-
* The session token is stored in cookies, never sent to the browser in JSON.
|
|
150
|
-
*
|
|
151
|
-
* @example
|
|
152
|
-
* ```ts
|
|
153
|
-
* const result = await sm.auth.login({ email, password })
|
|
154
|
-
* if (result.success) {
|
|
155
|
-
* return withSession(result.data, { user: result.data.user })
|
|
156
|
-
* }
|
|
157
|
-
* ```
|
|
158
|
-
*/
|
|
159
|
-
declare function withSession<T extends Record<string, unknown>>(loginResponse: {
|
|
160
|
-
session_token: string;
|
|
161
|
-
user: {
|
|
162
|
-
id: string;
|
|
163
|
-
};
|
|
164
|
-
}, responseBody: T, options?: SessionCookieOptions): Response;
|
|
165
|
-
/**
|
|
166
|
-
* Create a Response that clears session cookies
|
|
167
|
-
*
|
|
168
|
-
* Use this after logout to clear HTTP-only cookies.
|
|
169
|
-
*
|
|
170
|
-
* @example
|
|
171
|
-
* ```ts
|
|
172
|
-
* await sm.auth.logout(sessionToken)
|
|
173
|
-
* return clearSession({ message: 'Logged out' })
|
|
174
|
-
* ```
|
|
175
|
-
*/
|
|
176
|
-
declare function clearSession<T extends Record<string, unknown>>(responseBody: T, options?: SessionCookieOptions, status?: number): Response;
|
|
177
|
-
/**
|
|
178
|
-
* Get session data from request cookies
|
|
179
|
-
*
|
|
180
|
-
* Use this in API routes to get the current session.
|
|
181
|
-
* Returns null if no valid session cookie exists.
|
|
182
|
-
*
|
|
183
|
-
* @example
|
|
184
|
-
* ```ts
|
|
185
|
-
* const session = await getSession()
|
|
186
|
-
* if (!session) {
|
|
187
|
-
* return Response.json({ error: 'Not authenticated' }, { status: 401 })
|
|
188
|
-
* }
|
|
189
|
-
* const user = await sm.auth.me(session.sessionToken)
|
|
190
|
-
* ```
|
|
191
|
-
*/
|
|
192
|
-
declare function getSession(options?: {
|
|
193
|
-
allowBearer?: boolean;
|
|
194
|
-
}): Promise<SessionData | null>;
|
|
195
|
-
/**
|
|
196
|
-
* Get session from a Request object (for edge/middleware)
|
|
197
|
-
*
|
|
198
|
-
* Use this when you need to read cookies from a Request directly.
|
|
199
|
-
*/
|
|
200
|
-
declare function getSessionFromRequest(request: Request): SessionData | null;
|
|
201
|
-
/**
|
|
202
|
-
* Known account entry stored in cookie.
|
|
203
|
-
* Contains display metadata ONLY — no tokens, no secrets.
|
|
204
|
-
*/
|
|
205
|
-
interface KnownAccountEntry {
|
|
206
|
-
userId: string;
|
|
207
|
-
email?: string;
|
|
208
|
-
fullName?: string;
|
|
209
|
-
avatarUrl?: string;
|
|
210
|
-
provider?: string;
|
|
211
|
-
lastActiveAt: string;
|
|
212
|
-
displayLabel?: string;
|
|
213
|
-
colorIndex?: number;
|
|
214
|
-
}
|
|
215
|
-
type AccountSwitcherPrivacy = 'full' | 'masked' | 'minimal';
|
|
216
|
-
/**
|
|
217
|
-
* Add an account to the known accounts cookie.
|
|
218
|
-
* Called after successful login. The cookie is NOT httpOnly so client JS
|
|
219
|
-
* can read it to render the account switcher UI.
|
|
220
|
-
*
|
|
221
|
-
* Appends Set-Cookie headers to an existing Headers object.
|
|
222
|
-
*/
|
|
223
|
-
declare function appendKnownAccountCookie(headers: Headers, account: KnownAccountEntry, existingCookie: string | null, options?: SessionCookieOptions, privacy?: AccountSwitcherPrivacy): void;
|
|
224
|
-
/**
|
|
225
|
-
* Remove a specific account from the known accounts cookie.
|
|
226
|
-
*/
|
|
227
|
-
declare function removeKnownAccountFromCookie(headers: Headers, userId: string, existingCookie: string | null, options?: SessionCookieOptions): void;
|
|
228
|
-
/**
|
|
229
|
-
* Clear the known accounts cookie entirely.
|
|
230
|
-
*/
|
|
231
|
-
declare function clearKnownAccountsCookie(headers: Headers, options?: SessionCookieOptions): void;
|
|
232
|
-
/**
|
|
233
|
-
* Read known accounts from a Request's cookies.
|
|
234
|
-
*/
|
|
235
|
-
declare function getKnownAccountsFromRequest(request: Request): KnownAccountEntry[];
|
|
236
|
-
/**
|
|
237
|
-
* Read the raw known accounts cookie value from a Request.
|
|
238
|
-
*/
|
|
239
|
-
declare function getKnownAccountsCookieRaw(request: Request): string | null;
|
|
240
|
-
/**
|
|
241
|
-
* Normalize all entries in the known accounts cookie to the given privacy level.
|
|
242
|
-
* Returns a Set-Cookie header string if any entries changed, or null if nothing changed.
|
|
243
|
-
* Used on /me requests to migrate legacy full-PII cookies to the configured privacy level.
|
|
244
|
-
*/
|
|
245
|
-
declare function normalizeKnownAccountsCookie(request: Request, privacy: AccountSwitcherPrivacy | undefined, options?: SessionCookieOptions): string | null;
|
|
246
|
-
/**
|
|
247
|
-
* Require authentication - throws Response if not authenticated
|
|
248
|
-
*
|
|
249
|
-
* Use this at the start of protected API routes.
|
|
250
|
-
*
|
|
251
|
-
* @example
|
|
252
|
-
* ```ts
|
|
253
|
-
* export async function GET() {
|
|
254
|
-
* const session = await requireSession()
|
|
255
|
-
* // session is guaranteed to exist here
|
|
256
|
-
* const files = await sm.storage.list(session.userId)
|
|
257
|
-
* }
|
|
258
|
-
* ```
|
|
259
|
-
*/
|
|
260
|
-
declare function requireSession(): Promise<SessionData>;
|
|
261
|
-
|
|
262
115
|
/**
|
|
263
116
|
* Ready-Made API Route Handlers
|
|
264
117
|
*
|
|
@@ -1363,4 +1216,4 @@ declare const DEFAULT_PERMISSIONS_POLICY: PermissionsPolicyMap;
|
|
|
1363
1216
|
*/
|
|
1364
1217
|
declare function buildSecurityHeaders(opts?: BuildSecurityHeadersOptions): SecurityHeaderEntry[];
|
|
1365
1218
|
|
|
1366
|
-
export { type AnalyticsRoutesConfig, type AnalyticsTrackingGateConfig, type AuthMiddlewareConfig, type AuthRoutesConfig, type BuildSecurityHeadersOptions, CSRF_COOKIE_NAME, CSRF_HEADER_NAME, DEFAULT_PERMISSIONS_POLICY, type HandlerContext, type HandlerOptions,
|
|
1219
|
+
export { type AnalyticsRoutesConfig, type AnalyticsTrackingGateConfig, type AuthMiddlewareConfig, type AuthRoutesConfig, type BuildSecurityHeadersOptions, CSRF_COOKIE_NAME, CSRF_HEADER_NAME, DEFAULT_PERMISSIONS_POLICY, type HandlerContext, type HandlerOptions, type MySqlBundle, type NewsletterRoutesConfig, type NotificationRoutesConfig, OAUTH_STATE_COOKIE_NAME, type OAuthBundle, type PermissionsPolicyMap, type PermissionsPolicyValue, type PostgresBundle, type PushRoutesConfig, type RedisBundle, type S3Bundle, type SafeRedirectOptions, ScaleMuleError, type SecurityHeaderEntry, ServerConfig, SessionCookieOptions, SessionData, type SmtpBundle, apiHandler, buildClientContextHeaders, buildFlagContext, buildSecurityHeaders, clearOAuthState, configureBundles, configureSecrets, createAnalyticsRoutes, createAuthMiddleware, createAuthRoutes, createNewsletterRoutes, createNotificationRoutes, createPushRoutes, errorCodeToStatus, extractClientContext, extractClientContextFromReq, generateCSRFToken, getAppSecret, getAppSecretOrDefault, getBootstrapFlags, getBundle, getCSRFToken, getMySqlBundle, getOAuthBundle, getPostgresBundle, getRedisBundle, getS3Bundle, getSmtpBundle, invalidateBundleCache, invalidateSecretCache, isSafeRedirect, newsletterRoute, prefetchBundles, prefetchSecrets, requireAppSecret, requireBundle, setOAuthState, unwrap, validateCSRFToken, validateCSRFTokenAsync, validateOAuthState, validateOAuthStateAsync, validateSafeRedirect, withAuth, withCSRFProtection, withCSRFToken };
|
package/dist/server/index.js
CHANGED
|
@@ -5,6 +5,7 @@ var money = require('@scalemule/money');
|
|
|
5
5
|
var headers = require('next/headers');
|
|
6
6
|
var server = require('next/server');
|
|
7
7
|
var ledvery = require('@scalemule/ledvery');
|
|
8
|
+
var ai = require('@scalemule/ai');
|
|
8
9
|
var crypto$1 = require('crypto');
|
|
9
10
|
var server$1 = require('@scalemule/sdk/flags/server');
|
|
10
11
|
|
|
@@ -2846,6 +2847,224 @@ function createPushRoutes(config) {
|
|
|
2846
2847
|
};
|
|
2847
2848
|
return { GET, POST, PUT, DELETE };
|
|
2848
2849
|
}
|
|
2850
|
+
var RUN_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
|
|
2851
|
+
var MAX_BODY_BYTES2 = 1048576;
|
|
2852
|
+
var IDEMPOTENCY_KEY = /^[\x21-\x7e]{1,200}$/;
|
|
2853
|
+
var OPERATION_KEY = /^[a-z0-9_-]{1,100}$/;
|
|
2854
|
+
function errorResponse3(code, message, status) {
|
|
2855
|
+
return new Response(JSON.stringify({ success: false, error: { code, message } }), {
|
|
2856
|
+
status,
|
|
2857
|
+
headers: { "Content-Type": "application/json", "Cache-Control": "no-store" }
|
|
2858
|
+
});
|
|
2859
|
+
}
|
|
2860
|
+
function resolveAiTarget(method, segments) {
|
|
2861
|
+
if (segments[0] === "operations") {
|
|
2862
|
+
if (segments.length === 1) return method === "GET" ? { kind: "operations" } : null;
|
|
2863
|
+
const operation = segments[1];
|
|
2864
|
+
if (!operation || !OPERATION_KEY.test(operation) || segments.length !== 3) return null;
|
|
2865
|
+
if (segments[2] === "preference" && (method === "PUT" || method === "DELETE")) return { kind: "preference", method, operation };
|
|
2866
|
+
if (segments[2] === "settings" && (method === "GET" || method === "PUT")) return { kind: "settings", method, operation };
|
|
2867
|
+
return null;
|
|
2868
|
+
}
|
|
2869
|
+
if (segments[0] !== "runs") return null;
|
|
2870
|
+
if (segments.length === 1) return method === "POST" ? { kind: "create" } : null;
|
|
2871
|
+
const runId = segments[1];
|
|
2872
|
+
if (!runId || !RUN_ID.test(runId)) return null;
|
|
2873
|
+
if (segments.length === 2) return method === "GET" ? { kind: "get", runId } : null;
|
|
2874
|
+
if (segments.length === 3 && segments[2] === "events" && method === "GET") return { kind: "events", runId };
|
|
2875
|
+
if (segments.length === 3 && segments[2] === "cancel" && method === "POST") return { kind: "cancel", runId };
|
|
2876
|
+
return null;
|
|
2877
|
+
}
|
|
2878
|
+
function hasSessionCookie(request) {
|
|
2879
|
+
const cookieHeader = request.headers.get("cookie") ?? "";
|
|
2880
|
+
return cookieHeader.split(";").some((part) => {
|
|
2881
|
+
const [name, ...rest] = part.trim().split("=");
|
|
2882
|
+
return name === SESSION_COOKIE_NAME && rest.join("=").length > 0;
|
|
2883
|
+
});
|
|
2884
|
+
}
|
|
2885
|
+
function csrfRequestView(request) {
|
|
2886
|
+
const maybe = request;
|
|
2887
|
+
if (maybe.cookies && typeof maybe.cookies.get === "function") {
|
|
2888
|
+
return request;
|
|
2889
|
+
}
|
|
2890
|
+
const jar = /* @__PURE__ */ new Map();
|
|
2891
|
+
for (const part of (request.headers.get("cookie") ?? "").split(";")) {
|
|
2892
|
+
const [name, ...rest] = part.trim().split("=");
|
|
2893
|
+
if (name) jar.set(name, decodeURIComponent(rest.join("=")));
|
|
2894
|
+
}
|
|
2895
|
+
return {
|
|
2896
|
+
headers: request.headers,
|
|
2897
|
+
cookies: { get: (name) => jar.has(name) ? { value: jar.get(name) } : void 0 }
|
|
2898
|
+
};
|
|
2899
|
+
}
|
|
2900
|
+
async function resolveAccount(config, request, session) {
|
|
2901
|
+
if (typeof config.accountId === "function") {
|
|
2902
|
+
const value = await config.accountId(request, session);
|
|
2903
|
+
return value ? String(value) : null;
|
|
2904
|
+
}
|
|
2905
|
+
return config.accountId ?? null;
|
|
2906
|
+
}
|
|
2907
|
+
function createAiRoutes(config) {
|
|
2908
|
+
const { apiKey, gatewayUrl, csrf = true } = config;
|
|
2909
|
+
const fetcher = config.fetch ?? globalThis.fetch;
|
|
2910
|
+
if (!apiKey) throw new Error("createAiRoutes: apiKey is required");
|
|
2911
|
+
if (!gatewayUrl) throw new Error("createAiRoutes: gatewayUrl is required");
|
|
2912
|
+
const base = gatewayUrl.replace(/\/+$/, "");
|
|
2913
|
+
async function readJsonBody(request) {
|
|
2914
|
+
const declared = Number(request.headers.get("content-length") ?? "0");
|
|
2915
|
+
if (Number.isFinite(declared) && declared > MAX_BODY_BYTES2) {
|
|
2916
|
+
return { error: errorResponse3("INPUT_INVALID", "Request body too large", 413) };
|
|
2917
|
+
}
|
|
2918
|
+
const body = await request.text();
|
|
2919
|
+
if (new TextEncoder().encode(body).byteLength > MAX_BODY_BYTES2) {
|
|
2920
|
+
return { error: errorResponse3("INPUT_INVALID", "Request body too large", 413) };
|
|
2921
|
+
}
|
|
2922
|
+
if (!body) return { error: errorResponse3("INPUT_INVALID", "A JSON body is required", 400) };
|
|
2923
|
+
return { body };
|
|
2924
|
+
}
|
|
2925
|
+
async function proxy(request, method, segments) {
|
|
2926
|
+
const target = resolveAiTarget(method, segments);
|
|
2927
|
+
if (!target) return errorResponse3("NOT_FOUND", "Unknown AI route", 404);
|
|
2928
|
+
if (!hasSessionCookie(request)) {
|
|
2929
|
+
return errorResponse3("SESSION_REQUIRED", "Sign in to use AI features", 401);
|
|
2930
|
+
}
|
|
2931
|
+
const session = getSessionFromRequest(request);
|
|
2932
|
+
if (!session?.sessionToken) {
|
|
2933
|
+
return errorResponse3("SESSION_REQUIRED", "Sign in to use AI features", 401);
|
|
2934
|
+
}
|
|
2935
|
+
const headers3 = {
|
|
2936
|
+
"x-api-key": apiKey,
|
|
2937
|
+
authorization: `Bearer ${session.sessionToken}`,
|
|
2938
|
+
accept: target.kind === "events" ? "text/event-stream" : "application/json"
|
|
2939
|
+
};
|
|
2940
|
+
Object.assign(
|
|
2941
|
+
headers3,
|
|
2942
|
+
buildClientContextHeaders(
|
|
2943
|
+
extractClientContext(request)
|
|
2944
|
+
)
|
|
2945
|
+
);
|
|
2946
|
+
const accountId = await resolveAccount(config, request, session);
|
|
2947
|
+
if (accountId) headers3["x-requested-account-id"] = accountId;
|
|
2948
|
+
let path;
|
|
2949
|
+
const init = { method, headers: headers3, redirect: "error", signal: request.signal };
|
|
2950
|
+
switch (target.kind) {
|
|
2951
|
+
case "create": {
|
|
2952
|
+
const key = request.headers.get("x-idempotency-key")?.trim() ?? "";
|
|
2953
|
+
if (!IDEMPOTENCY_KEY.test(key)) {
|
|
2954
|
+
return errorResponse3(
|
|
2955
|
+
"IDEMPOTENCY_KEY_REQUIRED",
|
|
2956
|
+
"Send an x-idempotency-key header generated before the first attempt",
|
|
2957
|
+
400
|
|
2958
|
+
);
|
|
2959
|
+
}
|
|
2960
|
+
headers3["x-idempotency-key"] = key;
|
|
2961
|
+
const read = await readJsonBody(request);
|
|
2962
|
+
if ("error" in read) return read.error;
|
|
2963
|
+
headers3["content-type"] = "application/json";
|
|
2964
|
+
init.body = read.body;
|
|
2965
|
+
path = "/v1/ai/runs";
|
|
2966
|
+
break;
|
|
2967
|
+
}
|
|
2968
|
+
case "operations":
|
|
2969
|
+
path = "/v1/ai/operations";
|
|
2970
|
+
break;
|
|
2971
|
+
case "preference": {
|
|
2972
|
+
if (target.method === "PUT") {
|
|
2973
|
+
const read = await readJsonBody(request);
|
|
2974
|
+
if ("error" in read) return read.error;
|
|
2975
|
+
headers3["content-type"] = "application/json";
|
|
2976
|
+
init.body = read.body;
|
|
2977
|
+
}
|
|
2978
|
+
path = `/v1/ai/operations/${encodeURIComponent(target.operation)}/preference`;
|
|
2979
|
+
break;
|
|
2980
|
+
}
|
|
2981
|
+
case "settings": {
|
|
2982
|
+
if (target.method === "PUT") {
|
|
2983
|
+
const read = await readJsonBody(request);
|
|
2984
|
+
if ("error" in read) return read.error;
|
|
2985
|
+
headers3["content-type"] = "application/json";
|
|
2986
|
+
init.body = read.body;
|
|
2987
|
+
}
|
|
2988
|
+
path = `/v1/ai/operations/${encodeURIComponent(target.operation)}/settings`;
|
|
2989
|
+
break;
|
|
2990
|
+
}
|
|
2991
|
+
case "get":
|
|
2992
|
+
path = `/v1/ai/runs/${encodeURIComponent(target.runId)}`;
|
|
2993
|
+
break;
|
|
2994
|
+
case "cancel":
|
|
2995
|
+
path = `/v1/ai/runs/${encodeURIComponent(target.runId)}/cancel`;
|
|
2996
|
+
break;
|
|
2997
|
+
case "events": {
|
|
2998
|
+
const lastEventId = request.headers.get("last-event-id")?.trim();
|
|
2999
|
+
if (lastEventId && /^\d{1,10}$/.test(lastEventId)) headers3["last-event-id"] = lastEventId;
|
|
3000
|
+
const after = new URL(request.url).searchParams.get("after");
|
|
3001
|
+
path = `/v1/ai/runs/${encodeURIComponent(target.runId)}/events${after && /^\d{1,10}$/.test(after) ? `?after=${after}` : ""}`;
|
|
3002
|
+
break;
|
|
3003
|
+
}
|
|
3004
|
+
}
|
|
3005
|
+
let upstream;
|
|
3006
|
+
try {
|
|
3007
|
+
upstream = await fetcher(`${base}${path}`, init);
|
|
3008
|
+
} catch (error2) {
|
|
3009
|
+
if (request.signal?.aborted) return new Response(null, { status: 499 });
|
|
3010
|
+
return errorResponse3("UPSTREAM_UNAVAILABLE", `AI facade unreachable: ${String(error2)}`, 502);
|
|
3011
|
+
}
|
|
3012
|
+
if (target.kind === "events" && upstream.ok && upstream.body) {
|
|
3013
|
+
return new Response(upstream.body, {
|
|
3014
|
+
status: 200,
|
|
3015
|
+
headers: {
|
|
3016
|
+
"Content-Type": "text/event-stream; charset=utf-8",
|
|
3017
|
+
"Cache-Control": "no-cache, no-transform",
|
|
3018
|
+
"X-Accel-Buffering": "no"
|
|
3019
|
+
}
|
|
3020
|
+
});
|
|
3021
|
+
}
|
|
3022
|
+
const text = await upstream.text();
|
|
3023
|
+
const responseHeaders = {
|
|
3024
|
+
"Content-Type": upstream.headers.get("content-type") || "application/json",
|
|
3025
|
+
"Cache-Control": "no-store"
|
|
3026
|
+
};
|
|
3027
|
+
const requestId = upstream.headers.get("x-request-id");
|
|
3028
|
+
if (requestId) responseHeaders["x-request-id"] = requestId;
|
|
3029
|
+
const retryAfter = upstream.headers.get("retry-after");
|
|
3030
|
+
if (retryAfter) responseHeaders["Retry-After"] = retryAfter;
|
|
3031
|
+
return new Response(text, { status: upstream.status, headers: responseHeaders });
|
|
3032
|
+
}
|
|
3033
|
+
async function segmentsOf(context) {
|
|
3034
|
+
const params = await context?.params;
|
|
3035
|
+
return params?.action ?? [];
|
|
3036
|
+
}
|
|
3037
|
+
const GET = async (request, context) => {
|
|
3038
|
+
try {
|
|
3039
|
+
return await proxy(request, "GET", await segmentsOf(context));
|
|
3040
|
+
} catch (error2) {
|
|
3041
|
+
return errorResponse3("INTERNAL_ERROR", String(error2), 500);
|
|
3042
|
+
}
|
|
3043
|
+
};
|
|
3044
|
+
function mutating(method) {
|
|
3045
|
+
return async (request, context) => {
|
|
3046
|
+
if (csrf) {
|
|
3047
|
+
const csrfError = validateCSRFToken(csrfRequestView(request));
|
|
3048
|
+
if (csrfError) return errorResponse3("CSRF_ERROR", "CSRF validation failed", 403);
|
|
3049
|
+
}
|
|
3050
|
+
try {
|
|
3051
|
+
return await proxy(request, method, await segmentsOf(context));
|
|
3052
|
+
} catch (error2) {
|
|
3053
|
+
return errorResponse3("INTERNAL_ERROR", String(error2), 500);
|
|
3054
|
+
}
|
|
3055
|
+
};
|
|
3056
|
+
}
|
|
3057
|
+
return { GET, POST: mutating("POST"), PUT: mutating("PUT"), DELETE: mutating("DELETE") };
|
|
3058
|
+
}
|
|
3059
|
+
function createServiceAiClient(config) {
|
|
3060
|
+
if (!config.apiKey) throw new Error("createServiceAiClient: apiKey is required");
|
|
3061
|
+
const transport = config.transport ?? ai.createFetchTransport({
|
|
3062
|
+
baseUrl: config.gatewayUrl,
|
|
3063
|
+
fetch: config.fetch,
|
|
3064
|
+
headers: () => ({ "x-api-key": config.apiKey })
|
|
3065
|
+
});
|
|
3066
|
+
return new ai.ScaleMuleAi({ transport, accountId: config.accountId });
|
|
3067
|
+
}
|
|
2849
3068
|
|
|
2850
3069
|
// src/server/notifications.ts
|
|
2851
3070
|
function createNotificationRoutes(config) {
|
|
@@ -2915,7 +3134,7 @@ function createNotificationRoutes(config) {
|
|
|
2915
3134
|
}
|
|
2916
3135
|
|
|
2917
3136
|
// src/server/newsletters.ts
|
|
2918
|
-
var
|
|
3137
|
+
var MAX_BODY_BYTES3 = 16 * 1024;
|
|
2919
3138
|
var SLUG = /^[a-z0-9][a-z0-9-]{0,78}[a-z0-9]$/;
|
|
2920
3139
|
function newsletterRoute(method, action) {
|
|
2921
3140
|
const path = action.join("/");
|
|
@@ -3000,8 +3219,8 @@ function createNewsletterRoutes(config) {
|
|
|
3000
3219
|
const init = { method, headers: headers3 };
|
|
3001
3220
|
if (method !== "GET") {
|
|
3002
3221
|
const declared = Number(request.headers.get("content-length") ?? "0");
|
|
3003
|
-
if (declared >
|
|
3004
|
-
const body = await readCapped(request,
|
|
3222
|
+
if (declared > MAX_BODY_BYTES3) return json(413, "PAYLOAD_TOO_LARGE", "Request body too large");
|
|
3223
|
+
const body = await readCapped(request, MAX_BODY_BYTES3);
|
|
3005
3224
|
if (body === null) return json(413, "PAYLOAD_TOO_LARGE", "Request body too large");
|
|
3006
3225
|
if (body) init.body = body;
|
|
3007
3226
|
}
|
|
@@ -3730,6 +3949,7 @@ exports.clearOAuthState = clearOAuthState;
|
|
|
3730
3949
|
exports.clearSession = clearSession;
|
|
3731
3950
|
exports.configureBundles = configureBundles;
|
|
3732
3951
|
exports.configureSecrets = configureSecrets;
|
|
3952
|
+
exports.createAiRoutes = createAiRoutes;
|
|
3733
3953
|
exports.createAnalyticsRoutes = createAnalyticsRoutes;
|
|
3734
3954
|
exports.createAuthMiddleware = createAuthMiddleware;
|
|
3735
3955
|
exports.createAuthRoutes = createAuthRoutes;
|
|
@@ -3738,6 +3958,7 @@ exports.createNewsletterRoutes = createNewsletterRoutes;
|
|
|
3738
3958
|
exports.createNotificationRoutes = createNotificationRoutes;
|
|
3739
3959
|
exports.createPushRoutes = createPushRoutes;
|
|
3740
3960
|
exports.createServerClient = createServerClient;
|
|
3961
|
+
exports.createServiceAiClient = createServiceAiClient;
|
|
3741
3962
|
exports.createWebhookHandler = createWebhookHandler;
|
|
3742
3963
|
exports.createWebhookRoutes = createWebhookRoutes;
|
|
3743
3964
|
exports.errorCodeToStatus = errorCodeToStatus;
|