@scalemule/nextjs 0.1.70 → 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.
@@ -3,6 +3,7 @@ import { createMoneyClient } from '@scalemule/money';
3
3
  import { cookies, headers } from 'next/headers';
4
4
  import { NextResponse } from 'next/server';
5
5
  import { LedveryClient } from '@scalemule/ledvery';
6
+ import { createFetchTransport, ScaleMuleAi } from '@scalemule/ai';
6
7
  import { createHmac, timingSafeEqual } from 'crypto';
7
8
  import { FlagClient } from '@scalemule/sdk/flags/server';
8
9
 
@@ -2844,6 +2845,224 @@ function createPushRoutes(config) {
2844
2845
  };
2845
2846
  return { GET, POST, PUT, DELETE };
2846
2847
  }
2848
+ var RUN_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
2849
+ var MAX_BODY_BYTES2 = 1048576;
2850
+ var IDEMPOTENCY_KEY = /^[\x21-\x7e]{1,200}$/;
2851
+ var OPERATION_KEY = /^[a-z0-9_-]{1,100}$/;
2852
+ function errorResponse3(code, message, status) {
2853
+ return new Response(JSON.stringify({ success: false, error: { code, message } }), {
2854
+ status,
2855
+ headers: { "Content-Type": "application/json", "Cache-Control": "no-store" }
2856
+ });
2857
+ }
2858
+ function resolveAiTarget(method, segments) {
2859
+ if (segments[0] === "operations") {
2860
+ if (segments.length === 1) return method === "GET" ? { kind: "operations" } : null;
2861
+ const operation = segments[1];
2862
+ if (!operation || !OPERATION_KEY.test(operation) || segments.length !== 3) return null;
2863
+ if (segments[2] === "preference" && (method === "PUT" || method === "DELETE")) return { kind: "preference", method, operation };
2864
+ if (segments[2] === "settings" && (method === "GET" || method === "PUT")) return { kind: "settings", method, operation };
2865
+ return null;
2866
+ }
2867
+ if (segments[0] !== "runs") return null;
2868
+ if (segments.length === 1) return method === "POST" ? { kind: "create" } : null;
2869
+ const runId = segments[1];
2870
+ if (!runId || !RUN_ID.test(runId)) return null;
2871
+ if (segments.length === 2) return method === "GET" ? { kind: "get", runId } : null;
2872
+ if (segments.length === 3 && segments[2] === "events" && method === "GET") return { kind: "events", runId };
2873
+ if (segments.length === 3 && segments[2] === "cancel" && method === "POST") return { kind: "cancel", runId };
2874
+ return null;
2875
+ }
2876
+ function hasSessionCookie(request) {
2877
+ const cookieHeader = request.headers.get("cookie") ?? "";
2878
+ return cookieHeader.split(";").some((part) => {
2879
+ const [name, ...rest] = part.trim().split("=");
2880
+ return name === SESSION_COOKIE_NAME && rest.join("=").length > 0;
2881
+ });
2882
+ }
2883
+ function csrfRequestView(request) {
2884
+ const maybe = request;
2885
+ if (maybe.cookies && typeof maybe.cookies.get === "function") {
2886
+ return request;
2887
+ }
2888
+ const jar = /* @__PURE__ */ new Map();
2889
+ for (const part of (request.headers.get("cookie") ?? "").split(";")) {
2890
+ const [name, ...rest] = part.trim().split("=");
2891
+ if (name) jar.set(name, decodeURIComponent(rest.join("=")));
2892
+ }
2893
+ return {
2894
+ headers: request.headers,
2895
+ cookies: { get: (name) => jar.has(name) ? { value: jar.get(name) } : void 0 }
2896
+ };
2897
+ }
2898
+ async function resolveAccount(config, request, session) {
2899
+ if (typeof config.accountId === "function") {
2900
+ const value = await config.accountId(request, session);
2901
+ return value ? String(value) : null;
2902
+ }
2903
+ return config.accountId ?? null;
2904
+ }
2905
+ function createAiRoutes(config) {
2906
+ const { apiKey, gatewayUrl, csrf = true } = config;
2907
+ const fetcher = config.fetch ?? globalThis.fetch;
2908
+ if (!apiKey) throw new Error("createAiRoutes: apiKey is required");
2909
+ if (!gatewayUrl) throw new Error("createAiRoutes: gatewayUrl is required");
2910
+ const base = gatewayUrl.replace(/\/+$/, "");
2911
+ async function readJsonBody(request) {
2912
+ const declared = Number(request.headers.get("content-length") ?? "0");
2913
+ if (Number.isFinite(declared) && declared > MAX_BODY_BYTES2) {
2914
+ return { error: errorResponse3("INPUT_INVALID", "Request body too large", 413) };
2915
+ }
2916
+ const body = await request.text();
2917
+ if (new TextEncoder().encode(body).byteLength > MAX_BODY_BYTES2) {
2918
+ return { error: errorResponse3("INPUT_INVALID", "Request body too large", 413) };
2919
+ }
2920
+ if (!body) return { error: errorResponse3("INPUT_INVALID", "A JSON body is required", 400) };
2921
+ return { body };
2922
+ }
2923
+ async function proxy(request, method, segments) {
2924
+ const target = resolveAiTarget(method, segments);
2925
+ if (!target) return errorResponse3("NOT_FOUND", "Unknown AI route", 404);
2926
+ if (!hasSessionCookie(request)) {
2927
+ return errorResponse3("SESSION_REQUIRED", "Sign in to use AI features", 401);
2928
+ }
2929
+ const session = getSessionFromRequest(request);
2930
+ if (!session?.sessionToken) {
2931
+ return errorResponse3("SESSION_REQUIRED", "Sign in to use AI features", 401);
2932
+ }
2933
+ const headers3 = {
2934
+ "x-api-key": apiKey,
2935
+ authorization: `Bearer ${session.sessionToken}`,
2936
+ accept: target.kind === "events" ? "text/event-stream" : "application/json"
2937
+ };
2938
+ Object.assign(
2939
+ headers3,
2940
+ buildClientContextHeaders(
2941
+ extractClientContext(request)
2942
+ )
2943
+ );
2944
+ const accountId = await resolveAccount(config, request, session);
2945
+ if (accountId) headers3["x-requested-account-id"] = accountId;
2946
+ let path;
2947
+ const init = { method, headers: headers3, redirect: "error", signal: request.signal };
2948
+ switch (target.kind) {
2949
+ case "create": {
2950
+ const key = request.headers.get("x-idempotency-key")?.trim() ?? "";
2951
+ if (!IDEMPOTENCY_KEY.test(key)) {
2952
+ return errorResponse3(
2953
+ "IDEMPOTENCY_KEY_REQUIRED",
2954
+ "Send an x-idempotency-key header generated before the first attempt",
2955
+ 400
2956
+ );
2957
+ }
2958
+ headers3["x-idempotency-key"] = key;
2959
+ const read = await readJsonBody(request);
2960
+ if ("error" in read) return read.error;
2961
+ headers3["content-type"] = "application/json";
2962
+ init.body = read.body;
2963
+ path = "/v1/ai/runs";
2964
+ break;
2965
+ }
2966
+ case "operations":
2967
+ path = "/v1/ai/operations";
2968
+ break;
2969
+ case "preference": {
2970
+ if (target.method === "PUT") {
2971
+ const read = await readJsonBody(request);
2972
+ if ("error" in read) return read.error;
2973
+ headers3["content-type"] = "application/json";
2974
+ init.body = read.body;
2975
+ }
2976
+ path = `/v1/ai/operations/${encodeURIComponent(target.operation)}/preference`;
2977
+ break;
2978
+ }
2979
+ case "settings": {
2980
+ if (target.method === "PUT") {
2981
+ const read = await readJsonBody(request);
2982
+ if ("error" in read) return read.error;
2983
+ headers3["content-type"] = "application/json";
2984
+ init.body = read.body;
2985
+ }
2986
+ path = `/v1/ai/operations/${encodeURIComponent(target.operation)}/settings`;
2987
+ break;
2988
+ }
2989
+ case "get":
2990
+ path = `/v1/ai/runs/${encodeURIComponent(target.runId)}`;
2991
+ break;
2992
+ case "cancel":
2993
+ path = `/v1/ai/runs/${encodeURIComponent(target.runId)}/cancel`;
2994
+ break;
2995
+ case "events": {
2996
+ const lastEventId = request.headers.get("last-event-id")?.trim();
2997
+ if (lastEventId && /^\d{1,10}$/.test(lastEventId)) headers3["last-event-id"] = lastEventId;
2998
+ const after = new URL(request.url).searchParams.get("after");
2999
+ path = `/v1/ai/runs/${encodeURIComponent(target.runId)}/events${after && /^\d{1,10}$/.test(after) ? `?after=${after}` : ""}`;
3000
+ break;
3001
+ }
3002
+ }
3003
+ let upstream;
3004
+ try {
3005
+ upstream = await fetcher(`${base}${path}`, init);
3006
+ } catch (error2) {
3007
+ if (request.signal?.aborted) return new Response(null, { status: 499 });
3008
+ return errorResponse3("UPSTREAM_UNAVAILABLE", `AI facade unreachable: ${String(error2)}`, 502);
3009
+ }
3010
+ if (target.kind === "events" && upstream.ok && upstream.body) {
3011
+ return new Response(upstream.body, {
3012
+ status: 200,
3013
+ headers: {
3014
+ "Content-Type": "text/event-stream; charset=utf-8",
3015
+ "Cache-Control": "no-cache, no-transform",
3016
+ "X-Accel-Buffering": "no"
3017
+ }
3018
+ });
3019
+ }
3020
+ const text = await upstream.text();
3021
+ const responseHeaders = {
3022
+ "Content-Type": upstream.headers.get("content-type") || "application/json",
3023
+ "Cache-Control": "no-store"
3024
+ };
3025
+ const requestId = upstream.headers.get("x-request-id");
3026
+ if (requestId) responseHeaders["x-request-id"] = requestId;
3027
+ const retryAfter = upstream.headers.get("retry-after");
3028
+ if (retryAfter) responseHeaders["Retry-After"] = retryAfter;
3029
+ return new Response(text, { status: upstream.status, headers: responseHeaders });
3030
+ }
3031
+ async function segmentsOf(context) {
3032
+ const params = await context?.params;
3033
+ return params?.action ?? [];
3034
+ }
3035
+ const GET = async (request, context) => {
3036
+ try {
3037
+ return await proxy(request, "GET", await segmentsOf(context));
3038
+ } catch (error2) {
3039
+ return errorResponse3("INTERNAL_ERROR", String(error2), 500);
3040
+ }
3041
+ };
3042
+ function mutating(method) {
3043
+ return async (request, context) => {
3044
+ if (csrf) {
3045
+ const csrfError = validateCSRFToken(csrfRequestView(request));
3046
+ if (csrfError) return errorResponse3("CSRF_ERROR", "CSRF validation failed", 403);
3047
+ }
3048
+ try {
3049
+ return await proxy(request, method, await segmentsOf(context));
3050
+ } catch (error2) {
3051
+ return errorResponse3("INTERNAL_ERROR", String(error2), 500);
3052
+ }
3053
+ };
3054
+ }
3055
+ return { GET, POST: mutating("POST"), PUT: mutating("PUT"), DELETE: mutating("DELETE") };
3056
+ }
3057
+ function createServiceAiClient(config) {
3058
+ if (!config.apiKey) throw new Error("createServiceAiClient: apiKey is required");
3059
+ const transport = config.transport ?? createFetchTransport({
3060
+ baseUrl: config.gatewayUrl,
3061
+ fetch: config.fetch,
3062
+ headers: () => ({ "x-api-key": config.apiKey })
3063
+ });
3064
+ return new ScaleMuleAi({ transport, accountId: config.accountId });
3065
+ }
2847
3066
 
2848
3067
  // src/server/notifications.ts
2849
3068
  function createNotificationRoutes(config) {
@@ -2913,7 +3132,7 @@ function createNotificationRoutes(config) {
2913
3132
  }
2914
3133
 
2915
3134
  // src/server/newsletters.ts
2916
- var MAX_BODY_BYTES2 = 16 * 1024;
3135
+ var MAX_BODY_BYTES3 = 16 * 1024;
2917
3136
  var SLUG = /^[a-z0-9][a-z0-9-]{0,78}[a-z0-9]$/;
2918
3137
  function newsletterRoute(method, action) {
2919
3138
  const path = action.join("/");
@@ -2998,8 +3217,8 @@ function createNewsletterRoutes(config) {
2998
3217
  const init = { method, headers: headers3 };
2999
3218
  if (method !== "GET") {
3000
3219
  const declared = Number(request.headers.get("content-length") ?? "0");
3001
- if (declared > MAX_BODY_BYTES2) return json(413, "PAYLOAD_TOO_LARGE", "Request body too large");
3002
- const body = await readCapped(request, MAX_BODY_BYTES2);
3220
+ if (declared > MAX_BODY_BYTES3) return json(413, "PAYLOAD_TOO_LARGE", "Request body too large");
3221
+ const body = await readCapped(request, MAX_BODY_BYTES3);
3003
3222
  if (body === null) return json(413, "PAYLOAD_TOO_LARGE", "Request body too large");
3004
3223
  if (body) init.body = body;
3005
3224
  }
@@ -3704,4 +3923,4 @@ function buildSecurityHeaders(opts = {}) {
3704
3923
  return headers3;
3705
3924
  }
3706
3925
 
3707
- export { CSRF_COOKIE_NAME, CSRF_HEADER_NAME, DEFAULT_PERMISSIONS_POLICY, KNOWN_ACCOUNTS_COOKIE_NAME, OAUTH_STATE_COOKIE_NAME, SESSION_COOKIE_NAME, SM_LEDVERY_ACCESS_TOKEN_COOKIE, SM_LEDVERY_ID_TOKEN_COOKIE, SM_LEDVERY_NONCE_COOKIE, SM_LEDVERY_PKCE_VERIFIER_COOKIE, SM_LEDVERY_STATE_COOKIE, ScaleMuleError, ScaleMuleServer, USER_ID_COOKIE_NAME, apiHandler, appendKnownAccountCookie, buildClientContextHeaders, buildFlagContext, buildSecurityHeaders, clearKnownAccountsCookie, clearOAuthState, clearSession, configureBundles, configureSecrets, createAnalyticsRoutes, createAuthMiddleware, createAuthRoutes, createLedveryRoutes, createNewsletterRoutes, createNotificationRoutes, createPushRoutes, createServerClient, createWebhookHandler, createWebhookRoutes, errorCodeToStatus, extractClientContext, extractClientContextFromReq, generateCSRFToken, getAppSecret, getAppSecretOrDefault, getBootstrapFlags, getBundle, getCSRFToken, getKnownAccountsCookieRaw, getKnownAccountsFromRequest, getLedverySession, getMySqlBundle, getOAuthBundle, getPostgresBundle, getRedisBundle, getS3Bundle, getSession, getSessionFromRequest, getSmtpBundle, invalidateBundleCache, invalidateSecretCache, isSafeRedirect, newsletterRoute, normalizeKnownAccountsCookie, parseWebhookEvent, prefetchBundles, prefetchSecrets, registerVideoWebhook, removeKnownAccountFromCookie, requireAppSecret, requireBundle, requireSession, resolveGatewayUrl, setOAuthState, unwrap, validateCSRFToken, validateCSRFTokenAsync, validateOAuthState, validateOAuthStateAsync, validateSafeRedirect, verifyWebhookSignature, withAuth, withCSRFProtection, withCSRFToken, withSession };
3926
+ export { CSRF_COOKIE_NAME, CSRF_HEADER_NAME, DEFAULT_PERMISSIONS_POLICY, KNOWN_ACCOUNTS_COOKIE_NAME, OAUTH_STATE_COOKIE_NAME, SESSION_COOKIE_NAME, SM_LEDVERY_ACCESS_TOKEN_COOKIE, SM_LEDVERY_ID_TOKEN_COOKIE, SM_LEDVERY_NONCE_COOKIE, SM_LEDVERY_PKCE_VERIFIER_COOKIE, SM_LEDVERY_STATE_COOKIE, ScaleMuleError, ScaleMuleServer, USER_ID_COOKIE_NAME, apiHandler, appendKnownAccountCookie, buildClientContextHeaders, buildFlagContext, buildSecurityHeaders, clearKnownAccountsCookie, clearOAuthState, clearSession, configureBundles, configureSecrets, createAiRoutes, createAnalyticsRoutes, createAuthMiddleware, createAuthRoutes, createLedveryRoutes, createNewsletterRoutes, createNotificationRoutes, createPushRoutes, createServerClient, createServiceAiClient, createWebhookHandler, createWebhookRoutes, errorCodeToStatus, extractClientContext, extractClientContextFromReq, generateCSRFToken, getAppSecret, getAppSecretOrDefault, getBootstrapFlags, getBundle, getCSRFToken, getKnownAccountsCookieRaw, getKnownAccountsFromRequest, getLedverySession, getMySqlBundle, getOAuthBundle, getPostgresBundle, getRedisBundle, getS3Bundle, getSession, getSessionFromRequest, getSmtpBundle, invalidateBundleCache, invalidateSecretCache, isSafeRedirect, newsletterRoute, normalizeKnownAccountsCookie, parseWebhookEvent, prefetchBundles, prefetchSecrets, registerVideoWebhook, removeKnownAccountFromCookie, requireAppSecret, requireBundle, requireSession, resolveGatewayUrl, setOAuthState, unwrap, validateCSRFToken, validateCSRFTokenAsync, validateOAuthState, validateOAuthStateAsync, validateSafeRedirect, verifyWebhookSignature, withAuth, withCSRFProtection, withCSRFToken, withSession };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scalemule/nextjs",
3
- "version": "0.1.70",
3
+ "version": "0.1.71",
4
4
  "description": "ScaleMule SDK for Next.js applications - authentication, storage, and user management",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -72,7 +72,7 @@
72
72
  "release": "npm run build && npm test && npm run type-check && npm publish --access public"
73
73
  },
74
74
  "dependencies": {
75
- "@scalemule/ai": "^0.0.1",
75
+ "@scalemule/ai": "^0.0.2",
76
76
  "@scalemule/ledvery": "^0.0.1",
77
77
  "@scalemule/money": "^0.0.2",
78
78
  "@scalemule/sdk": "^0.0.77"