chore: add mobile app

This commit is contained in:
2026-02-07 22:33:02 +01:00
parent db34640acc
commit e89384ad4e
29327 changed files with 3886944 additions and 12 deletions
@@ -0,0 +1,59 @@
/**
* Copyright © 2025 650 Industries.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
declare const ImmutableHeaders_base: {
new (init?: HeadersInit): Headers;
prototype: Headers;
};
/**
* An immutable version of the Fetch API's [`Headers`](https://developer.mozilla.org/en-US/docs/Web/API/Headers) object which prevents mutations.
*/
declare class ImmutableHeaders extends ImmutableHeaders_base {
#private;
set(): void;
append(): void;
delete(): void;
}
/** @hidden */
export type _ImmutableRequest = Omit<Request, 'body' | 'bodyUsed' | 'arrayBuffer' | 'blob' | 'formData' | 'json' | 'text' | 'bytes' | 'headers'> & {
headers: ImmutableHeaders;
};
/**
* An immutable version of the Fetch API's [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) object which prevents mutations to the request body and headers.
*/
export declare class ImmutableRequest implements _ImmutableRequest, RequestInit {
#private;
constructor(request: Request);
get cache(): RequestCache;
get credentials(): RequestCredentials;
get destination(): RequestDestination;
get integrity(): string;
get keepalive(): boolean;
get method(): string;
get mode(): RequestMode;
get redirect(): RequestRedirect;
get referrer(): string;
get referrerPolicy(): ReferrerPolicy;
get signal(): AbortSignal;
get url(): string;
get bodyUsed(): boolean;
get duplex(): "half" | undefined;
get headers(): ImmutableHeaders;
/** The request body is not accessible in immutable requests. */
get body(): never;
arrayBuffer(): Promise<void>;
blob(): Promise<void>;
bytes(): Promise<void>;
formData(): Promise<void>;
json(): Promise<void>;
text(): Promise<void>;
/**
* Creates a mutable clone of the original request. This is provided as an escape hatch.
*/
clone(): Request;
}
export declare function assertRuntimeFetchAPISupport({ Request, Response, Headers, process, }?: any): void;
export {};
+159
View File
@@ -0,0 +1,159 @@
"use strict";
/**
* Copyright © 2025 650 Industries.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ImmutableRequest = void 0;
exports.assertRuntimeFetchAPISupport = assertRuntimeFetchAPISupport;
const getHeadersConstructor = () => {
if (typeof Headers !== 'undefined') {
return Headers;
}
else {
// NOTE(@kitten): The `assertRuntimeFetchAPISupport` helper will catch this. Currently only an issue in Jest
return (globalThis.Headers ??
class _MockHeaders {
constructor() {
throw new Error('Runtime built-in Headers API is not available.');
}
});
}
};
/**
* An immutable version of the Fetch API's [`Headers`](https://developer.mozilla.org/en-US/docs/Web/API/Headers) object which prevents mutations.
*/
class ImmutableHeaders extends getHeadersConstructor() {
// TODO(@hassankhan): Merge with `ReadonlyHeaders` from `expo-router`
#throwImmutableError() {
throw new Error('This operation is not allowed on immutable headers.');
}
set() {
this.#throwImmutableError();
}
append() {
this.#throwImmutableError();
}
delete() {
this.#throwImmutableError();
}
}
/**
* An immutable version of the Fetch API's [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) object which prevents mutations to the request body and headers.
*/
class ImmutableRequest {
#headers;
#request;
constructor(request) {
this.#headers = new ImmutableHeaders(request.headers);
this.#request = request;
}
get cache() {
return this.#request.cache;
}
get credentials() {
return this.#request.credentials;
}
get destination() {
return this.#request.destination;
}
get integrity() {
return this.#request.integrity;
}
get keepalive() {
return this.#request.keepalive;
}
get method() {
return this.#request.method;
}
get mode() {
return this.#request.mode;
}
get redirect() {
return this.#request.redirect;
}
get referrer() {
return this.#request.referrer;
}
get referrerPolicy() {
return this.#request.referrerPolicy;
}
get signal() {
return this.#request.signal;
}
get url() {
return this.#request.url;
}
get bodyUsed() {
return this.#request.bodyUsed;
}
get duplex() {
return this.#request.duplex;
}
get headers() {
return this.#headers;
}
#throwImmutableBodyError() {
throw new Error('This operation is not allowed on immutable requests.');
}
/** The request body is not accessible in immutable requests. */
get body() {
// NOTE(@kitten): `new Request(req.url, req)` may internally access `req.body` to copy the request
// We can pretend it is `null`. Marking `bodyUsed` makes no sense here as it manipulates the subsequent
// code paths, but pretending there was no body should be safe
return null;
}
async arrayBuffer() {
this.#throwImmutableBodyError();
}
async blob() {
this.#throwImmutableBodyError();
}
async bytes() {
this.#throwImmutableBodyError();
}
async formData() {
this.#throwImmutableBodyError();
}
async json() {
this.#throwImmutableBodyError();
}
async text() {
this.#throwImmutableBodyError();
}
/**
* Creates a mutable clone of the original request. This is provided as an escape hatch.
*/
clone() {
return this.#request.clone();
}
}
exports.ImmutableRequest = ImmutableRequest;
// Add assertions to improve usage in non-standard environments.
function assertRuntimeFetchAPISupport({ Request, Response, Headers, process, } = globalThis) {
// Check if Request and Response are available.
if (typeof Request === 'undefined' ||
typeof Response === 'undefined' ||
typeof Headers === 'undefined') {
// Detect if `--no-experimental-fetch` flag is enabled and warn that it must be disabled.
if (typeof process !== 'undefined' && process.env && process.env.NODE_OPTIONS) {
const nodeOptions = process.env.NODE_OPTIONS;
if (nodeOptions.includes('--no-experimental-fetch')) {
throw new Error('NODE_OPTIONS="--no-experimental-fetch" is not supported with Expo server. Node.js built-in Request/Response APIs are required to continue.');
}
}
// If Node.js is <18, throw an error.
if (typeof process !== 'undefined' && process.version) {
const version = process.version;
const majorVersion = parseInt(version.replace(/v/g, '').split('.')[0], 10);
if (majorVersion < 18) {
throw new Error(`Node.js version ${majorVersion} is not supported. Upgrade to Node.js 20 or newer.`);
}
}
// Default error event for missing APIs.
throw new Error('Runtime built-in Request/Response/Headers APIs are not available. If running Node ensure that Node Fetch API, first available in Node.js 18, is enabled.');
}
}
//# sourceMappingURL=ImmutableRequest.js.map
@@ -0,0 +1 @@
{"version":3,"file":"ImmutableRequest.js","sourceRoot":"","sources":["../../src/ImmutableRequest.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAmKH,oEAqCC;AAtMD,MAAM,qBAAqB,GAAG,GAAmB,EAAE;IACjD,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE,CAAC;QACnC,OAAO,OAAO,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,4GAA4G;QAC5G,OAAO,CACL,UAAU,CAAC,O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RequestInit {
duplex?: 'half';
}
interface Request {
duplex?: 'half';
}
interface Response {
cf?: unknown;
webSocket?: unknown;
}
}
export {};
+3
View File
@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=global.types.js.map
@@ -0,0 +1 @@
{"version":3,"file":"global.types.js","sourceRoot":"","sources":["../../src/global.types.ts"],"names":[],"mappings":""}
+2
View File
@@ -0,0 +1,2 @@
export * from './runtime/api';
export type * from './types';
+18
View File
@@ -0,0 +1,18 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./runtime/api"), exports);
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,gDAA8B"}
+28
View File
@@ -0,0 +1,28 @@
export interface MiddlewareInfo {
/**
* Path to the module that contains the middleware function as a default export.
*
* @example _expo/functions/+middleware.js
*/
file: string;
}
export interface RouteInfo<TRegex = RegExp | string> {
file: string;
page: string;
namedRegex: TRegex;
routeKeys: Record<string, string>;
permanent?: boolean;
methods?: string[];
}
export interface RoutesManifest<TRegex = RegExp | string> {
middleware?: MiddlewareInfo;
headers?: Record<string, string | string[]>;
apiRoutes: RouteInfo<TRegex>[];
htmlRoutes: RouteInfo<TRegex>[];
notFoundRoutes: RouteInfo<TRegex>[];
redirects: RouteInfo<TRegex>[];
rewrites: RouteInfo<TRegex>[];
}
export type RawManifest = RoutesManifest<string>;
export type Manifest = RoutesManifest<RegExp>;
export type Route = RouteInfo<RegExp>;
+3
View File
@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=manifest.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"manifest.js","sourceRoot":"","sources":["../../src/manifest.ts"],"names":[],"mappings":""}
+36
View File
@@ -0,0 +1,36 @@
/**
* Copyright © 2024 650 Industries.
* Copyright © 2024 dai-shi.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* https://github.com/dai-shi/waku/blob/f9111ed7d96c95d7e128b37e8f7ae2d80122218e/packages/waku/src/lib/middleware/rsc.ts#L1
*/
type ResolvedConfig = any;
export type RenderRscArgs = {
config: ResolvedConfig;
input: string;
searchParams: URLSearchParams;
platform: string;
engine?: 'hermes' | null;
method: 'GET' | 'POST';
body?: ReadableStream | null;
contentType?: string | undefined;
decodedBody?: unknown;
moduleIdCallback?: ((id: string) => void) | undefined;
onError?: (err: unknown) => void;
headers: Record<string, string>;
};
export declare const decodeInput: (encodedInput: string) => string;
export declare function getRscMiddleware(options: {
config: ResolvedConfig;
baseUrl: string;
rscPath: string;
renderRsc: (args: RenderRscArgs) => Promise<ReadableStream<any>>;
onError?: (err: unknown) => void;
}): {
GET: (req: Request) => Promise<Response>;
POST: (req: Request) => Promise<Response>;
};
export {};
+124
View File
@@ -0,0 +1,124 @@
"use strict";
/**
* Copyright © 2024 650 Industries.
* Copyright © 2024 dai-shi.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* https://github.com/dai-shi/waku/blob/f9111ed7d96c95d7e128b37e8f7ae2d80122218e/packages/waku/src/lib/middleware/rsc.ts#L1
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.decodeInput = void 0;
exports.getRscMiddleware = getRscMiddleware;
const decodeInput = (encodedInput) => {
if (encodedInput === 'index.txt') {
return '';
}
if (encodedInput?.endsWith('.txt')) {
return encodedInput.slice(0, -'.txt'.length);
}
const err = new Error('Invalid encoded input');
err.statusCode = 400;
throw err;
};
exports.decodeInput = decodeInput;
// Production / Development API Route for handling RSC. Must be applied to the RSC paths, e.g. `/_flight/[...slug]+api.tsx`
function getRscMiddleware(options) {
let rscPathPrefix = options.rscPath;
if (rscPathPrefix !== '/' && !rscPathPrefix.endsWith('/')) {
rscPathPrefix += '/';
}
async function getOrPostAsync(req) {
const url = new URL(req.url);
const { method } = req;
if (method !== 'GET' && method !== 'POST') {
throw new Error(`Unsupported method '${method}'`);
}
const platform = url.searchParams.get('platform') ?? req.headers.get('expo-platform');
if (typeof platform !== 'string' || !platform) {
return new Response('Missing expo-platform header or platform query parameter', {
status: 500,
headers: {
'Content-Type': 'text/plain',
},
});
}
const engine = url.searchParams.get('transform.engine');
// TODO: Will the hermes flag apply in production later?
if (engine && !['hermes'].includes(engine)) {
return new Response(`Query parameter "transform.engine" is an unsupported value: ${engine}`, {
status: 500,
headers: {
'Content-Type': 'text/plain',
},
});
}
let encodedInput = url.pathname.replace(
// TODO: baseUrl support
rscPathPrefix, '');
// First segment should be the target platform.
// This is used for aligning with production exports which are statically exported to a single location at build-time.
encodedInput = encodedInput.replace(new RegExp(`^${platform}/`), '');
try {
encodedInput = (0, exports.decodeInput)(encodedInput);
}
catch {
return new Response(`Invalid encoded input: "${encodedInput}"`, {
status: 400,
headers: {
'Content-Type': 'text/plain',
},
});
}
try {
const args = {
config: options.config,
platform,
engine: engine,
input: encodedInput,
searchParams: url.searchParams,
method,
body: req.body,
contentType: req.headers.get('Content-Type') ?? '',
decodedBody: req.headers.get('X-Expo-Params'),
onError: options.onError,
headers: headersToRecord(req.headers),
};
const readable = await options.renderRsc(args);
return new Response(readable, {
headers: {
// The response is a streamed text file
'Content-Type': 'text/plain',
},
});
}
catch (err) {
if (err instanceof Response) {
return err;
}
if (process.env.NODE_ENV !== 'development') {
throw err;
}
console.error(err);
return new Response(`Unexpected server error rendering RSC: ` + err.message, {
status: 'statusCode' in err ? err.statusCode : 500,
headers: {
'Content-Type': 'text/plain',
},
});
}
}
return {
GET: getOrPostAsync,
POST: getOrPostAsync,
};
}
function headersToRecord(headers) {
const record = {};
for (const [key, value] of headers.entries()) {
record[key] = value;
}
return record;
}
//# sourceMappingURL=rsc.js.map
@@ -0,0 +1 @@
{"version":3,"file":"rsc.js","sourceRoot":"","sources":["../../../src/middleware/rsc.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;;AAgCH,4CA6GC;AA1HM,MAAM,WAAW,GAAG,CAAC,YAAoB,EAAE,EAAE;IAClD,IAAI,YAAY,KAAK,WAAW,EAAE,CAAC;QACjC,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,IAAI,YAAY,EAAE,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;QACnC,OAAO,YAAY,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IAC/C,CAAC;IACD,MAAM,GAAG,GAAG,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAC;IAC9C,GAAW,CAAC,UAAU,GAAG,GAAG,CAAC;IAC9B,MAAM,GAAG,CAAC;AACZ,CAAC,CAAC;AAVW,QAAA,WAAW,eAUtB;AAEF,2HAA2H;AAC3H,SAAgB,gBAAgB,CAAC,OAMhC;IAIC,IAAI,aAAa,GAAG,OAAO,CAAC,OAAO,CAAC;IACpC,IAAI,aAAa,KAAK,GAAG,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QAC1D,aAAa,IAAI,GAAG,CAAC;IACvB,CAAC;IAED,KAAK,UAAU,cAAc,CAAC,GAAY;QACxC,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAC7B,MAAM,EAAE,MAAM,EAAE,GAAG,GAAG,CAAC;QACv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AC,CAAC,GAAG;gBAClD,OAAO,EAAE;oBACP,cAAc,EAAE,YAAY;iBAC7B;aACF,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,OAAO;QACL,GAAG,EAAE,cAAc;QACnB,IAAI,EAAE,cAAc;KACrB,CAAC;AACJ,CAAC;AAED,SAAS,eAAe,CAAC,OAAgB;IACvC,MAAM,MAAM,GAA2B,EAAE,CAAC;IAC1C,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC;QAC7C,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;IACtB,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC"}
+2
View File
@@ -0,0 +1,2 @@
export { type RenderRscArgs, getRscMiddleware } from './middleware/rsc';
export type * from './manifest';
+6
View File
@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getRscMiddleware = void 0;
var rsc_1 = require("./middleware/rsc");
Object.defineProperty(exports, "getRscMiddleware", { enumerable: true, get: function () { return rsc_1.getRscMiddleware; } });
//# sourceMappingURL=private.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"private.js","sourceRoot":"","sources":["../../src/private.ts"],"names":[],"mappings":";;;AAAA,wCAAwE;AAA3C,uGAAA,gBAAgB,OAAA"}
+47
View File
@@ -0,0 +1,47 @@
export { StatusError } from './error';
/** Returns the current request's origin URL.
*
* This typically returns the request's `Origin` header, which contains the
* request origin URL or defaults to `null`.
* @returns A request origin
*/
export declare function origin(): string | null;
/** Returns the request's environment, if the server runtime supports this.
*
* In EAS Hosting, the returned environment name is the
* [alias or deployment identifier](https://docs.expo.dev/eas/hosting/deployments-and-aliases/),
* but the value may differ for other providers.
*
* @returns A request environment name, or `null` for production.
*/
export declare function environment(): string | null;
/** Runs a task immediately and instructs the runtime to complete the task.
*
* A request handler may be terminated as soon as the client has finished the full `Response`
* and unhandled promise rejections may not be logged properly. To run tasks concurrently to
* a request handler and keep the request alive until the task is completed, pass a task
* function to `runTask` instead. The request handler will be kept alive until the task
* completes.
*
* @param fn - A task function to execute. The request handler will be kept alive until this task finishes.
*/
export declare function runTask(fn: () => Promise<unknown>): void;
/** Defers a task until after a response has been sent.
*
* This only calls the task function once the request handler has finished resolving a `Response`
* and keeps the request handler alive until the task is completed. This is useful to run non-critical
* tasks after the request handler, for example to log analytics datapoints. If the request handler
* rejects with an error, deferred tasks won't be executed.
*
* @param fn - A task function to execute after the request handler has finished.
*/
export declare function deferTask(fn: () => Promise<unknown> | void): void;
/** Sets headers on the `Response` the current request handler will return.
*
* This only updates the headers once the request handler has finished and resolved a `Response`.
* It will either receive a set of `Headers` or an equivalent object containing headers, which will
* be merged into the response's headers once it's returned.
*
* @param updateHeaders - A `Headers` object, a record of headers, or a function that receives `Headers` to be updated or can return a `Headers` object that will be merged into the response headers.
*/
export declare function setResponseHeaders(updateHeaders: Headers | Record<string, string | string[]> | ((headers: Headers) => Headers | void)): void;
+84
View File
@@ -0,0 +1,84 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StatusError = void 0;
exports.origin = origin;
exports.environment = environment;
exports.runTask = runTask;
exports.deferTask = deferTask;
exports.setResponseHeaders = setResponseHeaders;
const scope_1 = require("./scope");
function enforcedRequestScope() {
const scope = scope_1.scopeRef.current?.getStore();
if (scope === undefined) {
throw new Error('Invalid server runtime API call. Runtime APIs can only be called during ongoing requests.\n' +
'- You may be calling this API in the global scope.\n' +
'- You might be calling this API outside of a promise scoped to a request.\n' +
'- You might have more than one copy of this API installed.');
}
return scope;
}
function assertSupport(name, v) {
if (v === undefined) {
throw new Error(`Unsupported server runtime API call: ${name}. This API is not supported in your current environment.`);
}
return v;
}
var error_1 = require("./error");
Object.defineProperty(exports, "StatusError", { enumerable: true, get: function () { return error_1.StatusError; } });
/** Returns the current request's origin URL.
*
* This typically returns the request's `Origin` header, which contains the
* request origin URL or defaults to `null`.
* @returns A request origin
*/
function origin() {
return assertSupport('origin()', enforcedRequestScope().origin);
}
/** Returns the request's environment, if the server runtime supports this.
*
* In EAS Hosting, the returned environment name is the
* [alias or deployment identifier](https://docs.expo.dev/eas/hosting/deployments-and-aliases/),
* but the value may differ for other providers.
*
* @returns A request environment name, or `null` for production.
*/
function environment() {
return assertSupport('environment()', enforcedRequestScope().environment);
}
/** Runs a task immediately and instructs the runtime to complete the task.
*
* A request handler may be terminated as soon as the client has finished the full `Response`
* and unhandled promise rejections may not be logged properly. To run tasks concurrently to
* a request handler and keep the request alive until the task is completed, pass a task
* function to `runTask` instead. The request handler will be kept alive until the task
* completes.
*
* @param fn - A task function to execute. The request handler will be kept alive until this task finishes.
*/
function runTask(fn) {
assertSupport('runTask()', enforcedRequestScope().waitUntil)(fn());
}
/** Defers a task until after a response has been sent.
*
* This only calls the task function once the request handler has finished resolving a `Response`
* and keeps the request handler alive until the task is completed. This is useful to run non-critical
* tasks after the request handler, for example to log analytics datapoints. If the request handler
* rejects with an error, deferred tasks won't be executed.
*
* @param fn - A task function to execute after the request handler has finished.
*/
function deferTask(fn) {
assertSupport('deferTask()', enforcedRequestScope().deferTask)(fn);
}
/** Sets headers on the `Response` the current request handler will return.
*
* This only updates the headers once the request handler has finished and resolved a `Response`.
* It will either receive a set of `Headers` or an equivalent object containing headers, which will
* be merged into the response's headers once it's returned.
*
* @param updateHeaders - A `Headers` object, a record of headers, or a function that receives `Headers` to be updated or can return a `Headers` object that will be merged into the response headers.
*/
function setResponseHeaders(updateHeaders) {
assertSupport('setResponseHeaders()', enforcedRequestScope().setResponseHeaders)(updateHeaders);
}
//# sourceMappingURL=api.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"api.js","sourceRoot":"","sources":["../../../src/runtime/api.ts"],"names":[],"mappings":";;;AAgCA,wBAEC;AAUD,kCAEC;AAYD,0BAEC;AAWD,8BAEC;AAUD,gDAOC;AA1FD,mCAAoD;AAEpD,SAAS,oBAAoB;IAC3B,MAAM,KAAK,GAAG,gBAAQ,CAAC,OAAO,EAAE,QAAQ,EAAE,CAAC;IAC3C,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACxB,MAAM,IAAI,KAAK,CACb,6FAA6F;YAC3F,sDAAsD;YACtD,6EAA6E;YAC7E,4DAA4D,CAC/D,CAAC;IACJ,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,aAAa,CAAI,IAAY,EAAE,CAAgB;IACtD,IAAI,CAAC,KAAK,SAAS,EAAE,CAAC;QACpB,MAAM,IAAI,KAAK,CACb,wCAAwC,IAAI,0DAA0D,CACvG,CAAC;IACJ,CAAC;IACD,OAAO,CAAC,CAAC;AACX,CAAC;AAED,iCAAsC;AAA7B,oGAAA,WAAW,OAAA;AAEpB;;;;;GAKG;AACH,SAAgB,MAAM;IACpB,OAAO,aAAa,CAAC,UAAU,EAAE,oBAAoB,EAAE,CAAC,MAAM,CAAC,CAAC;AAClE,CAAC;AAED;;;;;;;GAOG;AACH,SAAgB,WAAW;IACzB,OAAO,aAAa,CAAC,eAAe,EAAE,oBAAoB,EAAE,CAAC,WAAW,CAAC,CAAC;AAC5E,CAAC;AAED;;;;;;;;;GASG;AACH,SAAgB,OAAO,CAAC,EAA0B;IAChD,aAAa,CAAC,WAAW,EAAE,oBAAoB,EAAE,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AACrE,CAAC;AAED;;;;;;;;GAQG;AACH,SAAgB,SAAS,CAAC,EAAiC;IACzD,aAAa,CAAC,aAAa,EAAE,oBAAoB,EAAE,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC;AACrE,CAAC;AAED;;;;;;;GAOG;AACH,SAAgB,kBAAkB,CAChC,aAG0C;IAE1C,aAAa,CAAC,sBAAsB,EAAE,oBAAoB,EAAE,CAAC,kBAAkB,CAAC,CAAC,aAAa,CAAC,CAAC;AAClG,CAAC"}
+36
View File
@@ -0,0 +1,36 @@
/** An error response representation which can be thrown anywhere in server-side code.
*
* A `StatusError` can be thrown by a request handler and will be caught by the `expo-server`
* runtime and replaced by a `Response` with the `status` and `body` that's been passed to
* the `StatusError`.
*
* @example
* ```ts
* import { StatusError } from 'expo-server';
*
* export function GET(request, { postId }) {
* if (!postId) {
* throw new StatusError(400, 'postId parameter is required');
* }
* }
* ```
*/
export declare class StatusError extends Error {
status: number;
body: string;
constructor(status?: number, body?: {
error?: string;
[key: string]: any;
} | Error | string);
constructor(status?: number, errorOptions?: {
cause: unknown;
error?: string;
});
constructor(status?: number, body?: {
error?: string;
[key: string]: any;
} | Error | string, errorOptions?: {
cause?: unknown;
});
}
export declare function errorToResponse(error: Error): Response;
+86
View File
@@ -0,0 +1,86 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StatusError = void 0;
exports.errorToResponse = errorToResponse;
/** An error response representation which can be thrown anywhere in server-side code.
*
* A `StatusError` can be thrown by a request handler and will be caught by the `expo-server`
* runtime and replaced by a `Response` with the `status` and `body` that's been passed to
* the `StatusError`.
*
* @example
* ```ts
* import { StatusError } from 'expo-server';
*
* export function GET(request, { postId }) {
* if (!postId) {
* throw new StatusError(400, 'postId parameter is required');
* }
* }
* ```
*/
class StatusError extends Error {
status;
body;
constructor(status = 500, body, errorOptions) {
const cause = (errorOptions != null && errorOptions.cause) ??
(body != null && typeof body === 'object' && body.cause != null ? body.cause : undefined);
let message = typeof body === 'object' ? (body instanceof Error ? body.message : body.error) : body;
if (message == null) {
switch (status) {
case 400:
message = 'Bad Request';
break;
case 401:
message = 'Unauthorized';
break;
case 403:
message = 'Forbidden';
break;
case 404:
message = 'Not Found';
break;
case 500:
message = 'Internal Server Error';
break;
default:
message = 'Unknown Error';
}
}
super(message, cause ? { cause } : undefined);
this.name = 'StatusError';
this.status = status;
if (body instanceof Error) {
this.body = JSON.stringify({ error: body.message }, null, 2);
}
else {
this.body =
typeof body === 'object'
? JSON.stringify(body, null, 2)
: (body ?? JSON.stringify({ error: message }, null, 2));
}
}
}
exports.StatusError = StatusError;
function errorToResponse(error) {
if (error instanceof StatusError) {
return new Response(error.body, {
status: error.status,
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
});
}
else if ('status' in error && typeof error.status === 'number') {
const body = 'body' in error && typeof error.body === 'string'
? error.body
: JSON.stringify({ error: error.message }, null, 2);
return new Response(body, {
status: error.status,
});
}
else {
return new Response(`${error}`, { status: 500 });
}
}
//# sourceMappingURL=error.js.map
@@ -0,0 +1 @@
{"version":3,"file":"error.js","sourceRoot":"","sources":["../../../src/runtime/error.ts"],"names":[],"mappings":";;;AAyEA,0CAmBC;AA5FD;;;;;;;;;;;;;;;;GAgBG;AACH,MAAa,WAAY,SAAQ,KAAK;IACpC,MAAM,CAAS;IACf,IAAI,CAAS;IASb,YACE,MAAM,GAAG,GAAG,EACZ,IAA+E,EAC/E,YAAkC;QAElC,MAAM,KAAK,GACT,CAAC,YAAY,IAAI,IAAI,IAAI,YAAY,CAAC,KAAK,CAAC;YAC5C,CAAC,IAAI,IAAI,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;QAC5F,IAAI,OAAO,GACT,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAI,YAAY,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;QACxF,IAAI,OAAO,IAAI,IAAI,EAAE,CAAC;YACpB,QAAQ,MAAM,EAAE,CAAC;gBACf,KAAK,GAAG;oBACN,OAAO,GAAG,aAAa,CAAC;oBACxB,MAAM;gBACR,KAAK,GAAG;oBACN,OAAO,GAAG,cAAc,CAAC;oBACzB,MAAM;gBACR,KAAK,GAAG;oBACN,OAAO,GAAG,WAAW,CAAC;oBACtB,MAAM;gBACR,KAAK,GAAG;oBAC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AAI,KAAK,IAAI,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ;YAC/C,CAAC,CAAC,KAAK,CAAC,IAAI;YACZ,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;QACxD,OAAO,IAAI,QAAQ,CAAC,IAAI,EAAE;YACxB,MAAM,EAAE,KAAK,CAAC,MAAM;SACrB,CAAC,CAAC;IACL,CAAC;SAAM,CAAC;QACN,OAAO,IAAI,QAAQ,CAAC,GAAG,KAAK,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC;IACnD,CAAC;AACH,CAAC"}
+10
View File
@@ -0,0 +1,10 @@
import { type ScopeDefinition, type RequestAPI } from './scope';
export interface RequestAPISetup extends RequestAPI {
origin?: string;
environment?: string | null;
waitUntil?(promise: Promise<unknown>): void;
}
type RequestContextFactory = (...args: any[]) => Partial<RequestAPISetup>;
type RequestScopeRunner<F extends RequestContextFactory> = (fn: (...args: Parameters<F>) => Promise<Response>, ...args: Parameters<F>) => Promise<Response>;
export declare function createRequestScope<F extends RequestContextFactory>(scopeDefinition: ScopeDefinition, makeRequestAPISetup: F): RequestScopeRunner<F>;
export {};
+112
View File
@@ -0,0 +1,112 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createRequestScope = createRequestScope;
const error_1 = require("./error");
const scope_1 = require("./scope");
const importMetaRegistry_1 = require("../utils/importMetaRegistry");
function setupRuntime() {
try {
Object.defineProperty(globalThis, 'origin', {
enumerable: true,
configurable: true,
get() {
return scope_1.scopeRef.current?.getStore()?.origin || 'null';
},
});
}
catch { }
try {
Object.defineProperty(globalThis, '__ExpoImportMetaRegistry', {
enumerable: true,
configurable: true,
get() {
return importMetaRegistry_1.importMetaRegistry;
},
});
}
catch { }
}
function createRequestScope(scopeDefinition, makeRequestAPISetup) {
setupRuntime();
// NOTE(@kitten): For long-running servers, this will always be a noop. It therefore
// makes sense for us to provide a default that doesn't do anything.
function defaultWaitUntil(promise) {
promise.finally(() => { });
}
return async (run, ...args) => {
// Initialize the scope definition which is used to isolate the runtime API between
// requests. The implementation of scopes differs per runtime, and is only initialized
// once the first request is received
scope_1.scopeRef.current = scopeDefinition;
const setup = makeRequestAPISetup(...args);
const { waitUntil = defaultWaitUntil } = setup;
const deferredTasks = [];
const responseHeadersUpdates = [];
const scope = {
...setup,
origin: setup.origin,
environment: setup.environment,
waitUntil,
deferTask: setup.deferTask,
setResponseHeaders(updateHeaders) {
responseHeadersUpdates.push(updateHeaders);
},
};
if (!scope.deferTask) {
scope.deferTask = function deferTask(fn) {
deferredTasks.push(fn);
};
}
let result;
try {
result =
scope_1.scopeRef.current != null
? await scope_1.scopeRef.current.run(scope, () => run(...args))
: await run(...args);
}
catch (error) {
if (error != null && error instanceof Response && !error.bodyUsed) {
result = error;
}
else if (error != null && error instanceof Error && 'status' in error) {
return (0, error_1.errorToResponse)(error);
}
else {
throw error;
}
}
deferredTasks.forEach((fn) => {
const maybePromise = fn();
if (maybePromise != null)
waitUntil(maybePromise);
});
for (const updateHeaders of responseHeadersUpdates) {
let headers = result.headers;
if (typeof updateHeaders === 'function') {
headers = updateHeaders(result.headers) || headers;
}
else if (updateHeaders instanceof Headers) {
headers = updateHeaders;
}
else if (typeof updateHeaders === 'object' && updateHeaders) {
for (const headerName in updateHeaders) {
if (Array.isArray(updateHeaders[headerName])) {
for (const headerValue of updateHeaders[headerName]) {
headers.append(headerName, headerValue);
}
}
else if (updateHeaders[headerName] != null) {
headers.set(headerName, updateHeaders[headerName]);
}
}
}
if (headers !== result.headers) {
for (const [headerName, headerValue] of headers) {
result.headers.set(headerName, headerValue);
}
}
}
return result;
};
}
//# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/runtime/index.ts"],"names":[],"mappings":";;AAsCA,gDAuFC;AA7HD,mCAA0C;AAC1C,mC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H,KAAK,MAAM,aAAa,IAAI,sBAAsB,EAAE,CAAC;YACnD,IAAI,OAAO,GAAY,MAAM,CAAC,OAAO,CAAC;YACtC,IAAI,OAAO,aAAa,KAAK,UAAU,EAAE,CAAC;gBACxC,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC;YACrD,CAAC;iBAAM,IAAI,aAAa,YAAY,OAAO,EAAE,CAAC;gBAC5C,OAAO,GAAG,aAAa,CAAC;YAC1B,CAAC;iBAAM,IAAI,OAAO,aAAa,KAAK,QAAQ,IAAI,aAAa,EAAE,CAAC;gBAC9D,KAAK,MAAM,UAAU,IAAI,aAAa,EAAE,CAAC;oBACvC,IAAI,KAAK,CAAC,OAAO,CAAC,aAAa,CAAC,UAAU,CAAC,CAAC,EAAE,CAAC;wBAC7C,KAAK,MAAM,WAAW,IAAI,aAAa,CAAC,UAAU,CAAC,EAAE,CAAC;4BACpD,OAAO,CAAC,MAAM,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC;wBAC1C,CAAC;oBACH,CAAC;yBAAM,IAAI,aAAa,CAAC,UAAU,CAAC,IAAI,IAAI,EAAE,CAAC;wBAC7C,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE,aAAa,CAAC,UAAU,CAAC,CAAC,CAAC;oBACrD,CAAC;gBACH,CAAC;YACH,CAAC;YACD,IAAI,OAAO,KAAK,MAAM,CAAC,OAAO,EAAE,CAAC;gBAC/B,KAAK,MAAM,CAAC,UAAU,EAAE,WAAW,CAAC,IAAI,OAAO,EAAE,CAAC;oBAChD,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC;gBAC9C,CAAC;YACH,CAAC;QACH,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC"}
+17
View File
@@ -0,0 +1,17 @@
export type UpdateResponseHeaders = Headers | Record<string, string | string[]> | ((headers: Headers) => Headers | void);
export interface RequestAPI {
origin?: string;
environment?: string | null;
waitUntil?(promise: Promise<unknown>): void;
deferTask?(fn: () => Promise<unknown> | void): void;
setResponseHeaders?(updateHeaders: UpdateResponseHeaders): void;
}
export interface ScopeDefinition<Scope extends RequestAPI = any> {
getStore(): Scope | undefined;
run<R>(scope: Scope, runner: () => R): R;
run<R, TArgs extends any[]>(scope: Scope, runner: (...args: TArgs) => R, ...args: TArgs): R;
}
declare const scopeRef: {
current: ScopeDefinition<RequestAPI> | null;
};
export { scopeRef };
+12
View File
@@ -0,0 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.scopeRef = void 0;
// NOTE(@kitten): When multiple versions of `@expo/server` are bundled, we still want to reuse the same scope definition
const scopeSymbol = Symbol.for('expoServerRuntime');
const sharedScope = globalThis;
const scopeRef = sharedScope[scopeSymbol] ||
(sharedScope[scopeSymbol] = {
current: null,
});
exports.scopeRef = scopeRef;
//# sourceMappingURL=scope.js.map
@@ -0,0 +1 @@
{"version":3,"file":"scope.js","sourceRoot":"","sources":["../../../src/runtime/scope.ts"],"names":[],"mappings":";;;AAmBA,wHAAwH;AACxH,MAAM,WAAW,GAAG,MAAM,CAAC,GAAG,CAAC,mBAAmB,CAAC,CAAC;AACpD,MAAM,WAAW,GACf,UAAU,CAAC;AAEb,MAAM,QAAQ,GACZ,WAAW,CAAC,WAAW,CAAC;IACxB,CAAC,WAAW,CAAC,WAAW,CAAC,GAAG;QAC1B,OAAO,EAAE,IAAI;KACd,CAAC,CAAC;AAEI,4BAAQ"}
+57
View File
@@ -0,0 +1,57 @@
import type { _ImmutableRequest } from './ImmutableRequest';
/** An immutable version of the Fetch API's `Request` as received by middleware functions.
* It cannot be mutated or modified, its headers are immutable, and you won't have access to the request body.
*/
export interface ImmutableRequest extends _ImmutableRequest {
readonly url: string;
readonly method: string;
}
/**
* Middleware function type. Middleware run for every request in your app, or on
* specified conditonally matched methods and path patterns, as per {@link MiddlewareMatcher}.
* @param request - An `ImmutableRequest` with read-only headers and no body access
* @example
* ```ts
* import type { MiddlewareFunction } from 'expo-server';
*
* const middleware: MiddlewareFunction = async (request) => {
* console.log(`Middleware executed for: ${request.url}`);
* };
*
* export default middleware;
* ```
* @see https://docs.expo.dev/router/reference/middleware/
*/
export type MiddlewareFunction = (request: ImmutableRequest) => Promise<Response | void> | Response | void;
/** Middleware matcher settings that restricts the middleware to run conditionally. */
export interface MiddlewareMatcher {
/** Set this to a list of path patterns to conditionally run middleware on. This may be exact paths,
* paths containing parameter or catch-all segments (`'/posts/[postId]'` or `'/blog/[...slug]'`), or
* regular expressions matching paths.
* @example ['/api', '/posts/[id]', '/blog/[...slug]']
*/
patterns?: (string | RegExp)[];
/** Set this to a list of HTTP methods to conditionally run middleware on. By default, middleware will
* match all HTTP methods.
* @example ['POST', 'PUT', 'DELETE']
*/
methods?: string[];
}
/** Exported from a `+middleware.ts` file to configure the server-side middleware function.
* @example
* ```ts
* import type { MiddlewareSettings } from 'expo-server';
*
* export const unstable_settings: MiddlewareSettings = {
* matcher: {
* methods: ['GET'],
* patterns: ['/api', '/admin/[...path]'],
* },
* };
* ```
* @see https://docs.expo.dev/router/reference/middleware/
*/
export interface MiddlewareSettings {
/** Matcher definition that restricts the middleware to run conditionally. */
matcher?: MiddlewareMatcher;
}
+3
View File
@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=types.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":""}
@@ -0,0 +1,15 @@
/**
* Copyright © 2025 650 Industries.
* Copyright (c) Remix Software Inc. 2020-2021
* Copyright (c) Shopify Inc. 2022-2024
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* Original license https://github.com/remix-run/remix/blob/6d6caaed5dfc436242962dcb2ff9617757a11e17/LICENSE.md
* Code from https://github.com/remix-run/remix/blob/6d6caaed5dfc436242962dcb2ff9617757a11e17/packages/remix-node/stream.ts#L66
*/
import type { Readable } from 'node:stream';
export declare const createReadableStreamFromReadable: (source: Readable & {
readableHighWaterMark?: number;
}) => ReadableStream<Uint8Array<ArrayBufferLike>>;
@@ -0,0 +1,97 @@
"use strict";
/**
* Copyright © 2025 650 Industries.
* Copyright (c) Remix Software Inc. 2020-2021
* Copyright (c) Shopify Inc. 2022-2024
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* Original license https://github.com/remix-run/remix/blob/6d6caaed5dfc436242962dcb2ff9617757a11e17/LICENSE.md
* Code from https://github.com/remix-run/remix/blob/6d6caaed5dfc436242962dcb2ff9617757a11e17/packages/remix-node/stream.ts#L66
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.createReadableStreamFromReadable = void 0;
const node_stream_1 = require("node:stream");
const createReadableStreamFromReadable = (source) => {
const pump = new StreamPump(source);
const stream = new ReadableStream(pump, pump);
return stream;
};
exports.createReadableStreamFromReadable = createReadableStreamFromReadable;
class StreamPump {
highWaterMark;
accumalatedSize;
stream;
controller;
constructor(stream) {
this.highWaterMark =
stream.readableHighWaterMark || new node_stream_1.Stream.Readable().readableHighWaterMark;
this.accumalatedSize = 0;
this.stream = stream;
this.enqueue = this.enqueue.bind(this);
this.error = this.error.bind(this);
this.close = this.close.bind(this);
}
size(chunk) {
return chunk?.byteLength || 0;
}
start(controller) {
this.controller = controller;
this.stream.on('data', this.enqueue);
this.stream.once('error', this.error);
this.stream.once('end', this.close);
this.stream.once('close', this.close);
}
pull() {
this.resume();
}
cancel(reason) {
if (this.stream.destroy) {
this.stream.destroy(reason);
}
this.stream.off('data', this.enqueue);
this.stream.off('error', this.error);
this.stream.off('end', this.close);
this.stream.off('close', this.close);
}
enqueue(chunk) {
if (this.controller) {
try {
const bytes = chunk instanceof Uint8Array ? chunk : Buffer.from(chunk);
const available = (this.controller.desiredSize || 0) - bytes.byteLength;
this.controller.enqueue(bytes);
if (available <= 0) {
this.pause();
}
}
catch {
this.controller.error(new Error('Could not create Buffer, chunk must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object'));
this.cancel();
}
}
}
pause() {
if (this.stream.pause) {
this.stream.pause();
}
}
resume() {
if (this.stream.readable && this.stream.resume) {
this.stream.resume();
}
}
close() {
if (this.controller) {
this.controller.close();
delete this.controller;
}
}
error(error) {
if (this.controller) {
this.controller.error(error);
delete this.controller;
}
}
}
//# sourceMappingURL=createReadableStreamFromReadable.js.map
@@ -0,0 +1 @@
{"version":3,"file":"createReadableStreamFromReadable.js","sourceRoot":"","sources":["../../../src/utils/createReadableStreamFromReadable.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;GAUG;;;AAGH,6CAAqC;AAE9B,MAAM,gCAAgC,GAAG,CAC9C,MAAqD,EACrD,EAAE;IACF,MAAM,IAAI,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC;IACpC,MAAM,MAAM,GAAG,IAAI,cAAc,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAC9C,OAAO,MAAM,CAAC;AAChB,CAAC,CAAC;AANW,QAAA,gCAAgC,oCAM3C;AAEF,MAAM,UAAU;IACP,aAAa,CAAS;IACtB,eAAe,CAAS;IACvB,MAAM,CAMZ;IACM,UAAU,CAAwC;IAE1D,YACE,MAMC;QAED,IAAI,CAAC,aAAa;YAChB,MAAM,CAAC,qBAAqB,IAAI,IAAI,oBAAM,CAAC,QAAQ,EAAE,CAAC,qBAAqB,CAAC;QAC9E,IAAI,CAAC,eAAe,GAAG,CAAC,CAAC;QACzB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACvC,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACnC,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;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AAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;gBAEvE,MAAM,SAAS,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,WAAW,IAAI,CAAC,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC;gBACxE,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,KAAgC,CAAC,CAAC;gBAC1D,IAAI,SAAS,IAAI,CAAC,EAAE,CAAC;oBACnB,IAAI,CAAC,KAAK,EAAE,CAAC;gBACf,CAAC;YACH,CAAC;YAAC,MAAM,CAAC;gBACP,IAAI,CAAC,UAAU,CAAC,KAAK,CACnB,IAAI,KAAK,CACP,+HAA+H,CAChI,CACF,CAAC;gBACF,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,CAAC;QACH,CAAC;IACH,CAAC;IAED,KAAK;QACH,IAAI,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;YACtB,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;QACtB,CAAC;IACH,CAAC;IAED,MAAM;QACJ,IAAI,IAAI,CAAC,MAAM,CAAC,QAAQ,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;YAC/C,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;QACvB,CAAC;IACH,CAAC;IAED,KAAK;QACH,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;YACpB,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;YACxB,OAAO,IAAI,CAAC,UAAU,CAAC;QACzB,CAAC;IACH,CAAC;IAED,KAAK,CAAC,KAAY;QAChB,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;YACpB,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;YAC7B,OAAO,IAAI,CAAC,UAAU,CAAC;QACzB,CAAC;IACH,CAAC;CACF"}
+1
View File
@@ -0,0 +1 @@
export declare const appendHeadersRecord: (headers: Headers, updateHeaders: Record<string, string | string[]>, shouldOverwrite: boolean) => void;
+20
View File
@@ -0,0 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.appendHeadersRecord = void 0;
const appendHeadersRecord = (headers, updateHeaders, shouldOverwrite) => {
for (const headerName in updateHeaders) {
if (Array.isArray(updateHeaders[headerName])) {
for (const headerValue of updateHeaders[headerName]) {
headers.append(headerName, headerValue);
}
}
else if (!shouldOverwrite && headers.has(headerName)) {
continue;
}
else if (updateHeaders[headerName] != null) {
headers.set(headerName, updateHeaders[headerName]);
}
}
};
exports.appendHeadersRecord = appendHeadersRecord;
//# sourceMappingURL=headers.js.map
@@ -0,0 +1 @@
{"version":3,"file":"headers.js","sourceRoot":"","sources":["../../../src/utils/headers.ts"],"names":[],"mappings":";;;AAAO,MAAM,mBAAmB,GAAG,CACjC,OAAgB,EAChB,aAAgD,EAChD,eAAwB,EAClB,EAAE;IACR,KAAK,MAAM,UAAU,IAAI,aAAa,EAAE,CAAC;QACvC,IAAI,KAAK,CAAC,OAAO,CAAC,aAAa,CAAC,UAAU,CAAC,CAAC,EAAE,CAAC;YAC7C,KAAK,MAAM,WAAW,IAAI,aAAa,CAAC,UAAU,CAAC,EAAE,CAAC;gBACpD,OAAO,CAAC,MAAM,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC;YAC1C,CAAC;QACH,CAAC;aAAM,IAAI,CAAC,eAAe,IAAI,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE,CAAC;YACvD,SAAS;QACX,CAAC;aAAM,IAAI,aAAa,CAAC,UAAU,CAAC,IAAI,IAAI,EAAE,CAAC;YAC7C,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE,aAAa,CAAC,UAAU,CAAC,CAAC,CAAC;QACrD,CAAC;IACH,CAAC;AACH,CAAC,CAAC;AAhBW,QAAA,mBAAmB,uBAgB9B"}
@@ -0,0 +1,3 @@
export declare const importMetaRegistry: {
readonly url: any;
};
@@ -0,0 +1,30 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.importMetaRegistry = void 0;
const DEFAULT_SCRIPT_NAME = 'file:///__main.js';
// - ./runtime/importMetaRegistry.ts (this file) -> importMetaRegistry.url
// - ./runtime/index.ts -> globalThis.__ExpoImportMetaRegistry
// - <source>
const CALL_DEPTH = 3;
function getFileName(offset = 0) {
const originalStackFormatter = Error.prepareStackTrace;
const originalStackTraceLimit = Error.stackTraceLimit;
try {
Error.stackTraceLimit = offset;
Error.prepareStackTrace = (_err, stack) => stack[offset - 1]?.getFileName();
return new Error().stack;
}
finally {
Error.prepareStackTrace = originalStackFormatter;
Error.stackTraceLimit = originalStackTraceLimit;
}
}
exports.importMetaRegistry = {
get url() {
let scriptName = getFileName(CALL_DEPTH);
if (scriptName?.[0] === '/')
scriptName = `file://${scriptName}`;
return scriptName || DEFAULT_SCRIPT_NAME;
},
};
//# sourceMappingURL=importMetaRegistry.js.map
@@ -0,0 +1 @@
{"version":3,"file":"importMetaRegistry.js","sourceRoot":"","sources":["../../../src/utils/importMetaRegistry.ts"],"names":[],"mappings":";;;AAAA,MAAM,mBAAmB,GAAG,mBAAmB,CAAC;AAEhD,0EAA0E;AAC1E,8DAA8D;AAC9D,aAAa;AACb,MAAM,UAAU,GAAG,CAAC,CAAC;AAErB,SAAS,WAAW,CAAC,MAAM,GAAG,CAAC;IAC7B,MAAM,sBAAsB,GAAG,KAAK,CAAC,iBAAiB,CAAC;IACvD,MAAM,uBAAuB,GAAG,KAAK,CAAC,eAAe,CAAC;IACtD,IAAI,CAAC;QACH,KAAK,CAAC,eAAe,GAAG,MAAM,CAAC;QAC/B,KAAK,CAAC,iBAAiB,GAAG,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC;QAC5E,OAAO,IAAI,KAAK,EAAE,CAAC,KAAY,CAAC;IAClC,CAAC;YAAS,CAAC;QACT,KAAK,CAAC,iBAAiB,GAAG,sBAAsB,CAAC;QACjD,KAAK,CAAC,eAAe,GAAG,uBAAuB,CAAC;IAClD,CAAC;AACH,CAAC;AAEY,QAAA,kBAAkB,GAAG;IAChC,IAAI,GAAG;QACL,IAAI,UAAU,GAAG,WAAW,CAAC,UAAU,CAAC,CAAC;QACzC,IAAI,UAAU,EAAE,CAAC,CAAC,CAAC,KAAK,GAAG;YAAE,UAAU,GAAG,UAAU,UAAU,EAAE,CAAC;QACjE,OAAO,UAAU,IAAI,mBAAmB,CAAC;IAC3C,CAAC;CACF,CAAC"}
+12
View File
@@ -0,0 +1,12 @@
import type { Route } from '../manifest';
export declare function isResponse(input: unknown): input is Response;
export declare function parseParams(request: Request, route: Route): Record<string, string>;
export declare function getRedirectRewriteLocation(url: URL, request: Request, route: Route): URL;
/** Match `[page]` -> `page`
* @privateRemarks Ported from `expo-router/src/matchers.tsx`
*/
export declare function matchDynamicName(name: string): string | undefined;
/** Match `[...page]` -> `page`
* @privateRemarks Ported from `expo-router/src/matchers.tsx`
*/
export declare function matchDeepDynamicRouteName(name: string): string | undefined;
+76
View File
@@ -0,0 +1,76 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isResponse = isResponse;
exports.parseParams = parseParams;
exports.getRedirectRewriteLocation = getRedirectRewriteLocation;
exports.matchDynamicName = matchDynamicName;
exports.matchDeepDynamicRouteName = matchDeepDynamicRouteName;
function isResponse(input) {
return !!input && typeof input === 'object' && input instanceof Response;
}
function parseParams(request, route) {
const params = {};
const { pathname } = new URL(request.url);
const match = route.namedRegex.exec(pathname);
if (match?.groups) {
for (const [key, value] of Object.entries(match.groups)) {
const namedKey = route.routeKeys[key];
params[namedKey] = value;
}
}
return params;
}
function getRedirectRewriteLocation(url, request, route) {
const originalQueryParams = url.searchParams.entries();
const params = parseParams(request, route);
const target = route.page
.split('/')
.map((segment) => {
let match;
if ((match = matchDynamicName(segment))) {
const value = params[match];
delete params[match];
return typeof value === 'string'
? value.split('/')[0] /* If we are redirecting from a catch-all route, we need to remove the extra segments */
: (value ?? segment);
}
else if ((match = matchDeepDynamicRouteName(segment))) {
const value = params[match];
delete params[match];
return value ?? segment;
}
else {
return segment;
}
})
.join('/');
const targetUrl = new URL(target, url.origin);
// NOTE: React Navigation doesn't differentiate between a path parameter
// and a search parameter. We have to preserve leftover search parameters
// to ensure we don't lose any intentional parameters with special meaning
for (const key in params)
targetUrl.searchParams.append(key, params[key]);
// NOTE(@krystofwoldrich): Query matching is not supported at the moment.
// Copy original query parameters to the target URL
for (const [key, value] of originalQueryParams) {
// NOTE(@krystofwoldrich): Params created from route overwrite existing (might be unexpected to the user)
if (!targetUrl.searchParams.has(key)) {
targetUrl.searchParams.append(key, value);
}
}
return targetUrl;
}
/** Match `[page]` -> `page`
* @privateRemarks Ported from `expo-router/src/matchers.tsx`
*/
function matchDynamicName(name) {
// Don't match `...` or `[` or `]` inside the brackets
return name.match(/^\[([^[\](?:\.\.\.)]+?)\]$/)?.[1]; // eslint-disable-line no-useless-escape
}
/** Match `[...page]` -> `page`
* @privateRemarks Ported from `expo-router/src/matchers.tsx`
*/
function matchDeepDynamicRouteName(name) {
return name.match(/^\[\.\.\.([^/]+?)\]$/)?.[1];
}
//# sourceMappingURL=matchers.js.map
@@ -0,0 +1 @@
{"version":3,"file":"matchers.js","sourceRoot":"","sources":["../../../src/utils/matchers.ts"],"names":[],"mappings":";;AAEA,gCAEC;AAED,kCAWC;AAED,gEAyCC;AAKD,4CAGC;AAKD,8DAEC;AAzED,SAAgB,UAAU,CAAC,KAAc;IACvC,OAAO,CAAC,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,YAAY,QAAQ,CAAC;AAC3E,CAAC;AAED,SAAgB,WAAW,CAAC,OAAgB,EAAE,KAAY;IACxD,MAAM,MAAM,GAA2B,EAAE,CAAC;IAC1C,MAAM,EAAE,QAAQ,EAAE,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IAC1C,MAAM,KAAK,GAAG,KAAK,C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C,KAAK,CAAC,CAAC;YACrB,OAAO,KAAK,IAAI,OAAO,CAAC;QAC1B,CAAC;aAAM,CAAC;YACN,OAAO,OAAO,CAAC;QACjB,CAAC;IACH,CAAC,CAAC;SACD,IAAI,CAAC,GAAG,CAAC,CAAC;IACb,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IAE9C,wEAAwE;IACxE,yEAAyE;IACzE,0EAA0E;IAC1E,KAAK,MAAM,GAAG,IAAI,MAAM;QAAE,SAAS,CAAC,YAAY,CAAC,MAAM,CAAC,GAAG,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;IAE1E,yEAAyE;IACzE,mDAAmD;IACnD,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,mBAAmB,EAAE,CAAC;QAC/C,yGAAyG;QACzG,IAAI,CAAC,SAAS,CAAC,YAAY,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC;YACrC,SAAS,CAAC,YAAY,CAAC,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QAC5C,CAAC;IACH,CAAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC;AAED;;GAEG;AACH,SAAgB,gBAAgB,CAAC,IAAY;IAC3C,sDAAsD;IACtD,OAAO,IAAI,CAAC,KAAK,CAAC,4BAA4B,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,wCAAwC;AAChG,CAAC;AAED;;GAEG;AACH,SAAgB,yBAAyB,CAAC,IAAY;IACpD,OAAO,IAAI,CAAC,KAAK,CAAC,sBAAsB,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AACjD,CAAC"}
@@ -0,0 +1,9 @@
import type { MiddlewareFunction, MiddlewareSettings } from '../types';
export interface MiddlewareModule {
default: MiddlewareFunction;
unstable_settings?: MiddlewareSettings;
}
/**
* Determines whether middleware should run for a given request based on matcher configuration.
*/
export declare function shouldRunMiddleware(request: Request, middleware: MiddlewareModule): boolean;
+82
View File
@@ -0,0 +1,82 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.shouldRunMiddleware = shouldRunMiddleware;
const matchers_1 = require("./matchers");
/**
* Determines whether middleware should run for a given request based on matcher configuration.
*/
function shouldRunMiddleware(request, middleware) {
const matcher = middleware.unstable_settings?.matcher;
// No matcher means middleware runs on all requests
if (!matcher) {
return true;
}
const url = new URL(request.url);
const pathname = url.pathname;
// Check HTTP methods, if specified
if (matcher.methods) {
const methods = matcher.methods.map((method) => method.toUpperCase());
if (methods.length === 0 || !methods.includes(request.method)) {
return false;
}
}
// Check path patterns, if specified
if (matcher.patterns) {
const patterns = Array.isArray(matcher.patterns) ? matcher.patterns : [matcher.patterns];
if (patterns.length === 0) {
return false;
}
return patterns.some((pattern) => matchesPattern(pathname, pattern));
}
// If neither methods nor patterns are specified, run middleware on all requests
return true;
}
/**
* Tests if a pathname matches a given pattern. The matching order is as follows:
*
* - Exact string
* - Named parameters (supports `[param]` and `[...param]`)
* - Regular expression
*/
function matchesPattern(pathname, pattern) {
if (typeof pattern === 'string') {
if (pattern === pathname) {
return true;
}
if (hasNamedParameters(pattern)) {
return namedParamToRegex(pattern).test(pathname);
}
}
else if (pattern != null) {
return pattern.test(pathname);
}
return false;
}
/**
* Check if a pattern contains named parameters like `[postId]` or `[...slug]`
*/
function hasNamedParameters(pattern) {
return pattern.split('/').some((segment) => {
return (0, matchers_1.matchDynamicName)(segment) || (0, matchers_1.matchDeepDynamicRouteName)(segment);
});
}
/**
* Convert a pattern with named parameters to regex
*/
function namedParamToRegex(pattern) {
const normalizedPattern = pattern.replace(/\/$/, '') || '/';
const segments = normalizedPattern.split('/');
const regexSegments = segments.map((segment) => {
if (!segment)
return '';
if ((0, matchers_1.matchDeepDynamicRouteName)(segment)) {
return '.+';
}
if ((0, matchers_1.matchDynamicName)(segment)) {
return '[^/]+';
}
return segment.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
});
return new RegExp(`^${regexSegments.join('/')}(?:/)?$`);
}
//# sourceMappingURL=middleware.js.map
@@ -0,0 +1 @@
{"version":3,"file":"middleware.js","sourceRoot":"","sources":["../../../src/utils/middleware.ts"],"names":[],"mappings":";;AAWA,kDA8BC;AAxCD,yCAAyE;AAOzE;;GAEG;AACH,SAAgB,mBAAmB,CAAC,OAAgB,EAAE,UAA4B;IAChF,MAAM,OAAO,GAAG,UAAU,CAAC,iBAAiB,EAAE,OAAO,CAAC;IAEtD,mDAAmD;IACnD,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IACjC,MAAM,QAAQ,GAAG,GAAG,CAAC,QAAQ,CAAC;IAE9B,mCAAmC;IACnC,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;QACpB,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC,CAAC;QACtE,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;YAC9D,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;IAED,oCAAoC;IACpC,IAAI,OAAO,CAAC,QAAQ,EAAE,CAAC;QACrB,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;QACzF,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC1B,OAAO,KAAK,CAAC;QACf,CAAC;QACD,OAAO,QAAQ,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,cAA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ACvC,OAAO,IAAI,CAAC;QACd,CAAC;QAED,IAAI,IAAA,2BAAgB,EAAC,OAAO,CAAC,EAAE,CAAC;YAC9B,OAAO,OAAO,CAAC;QACjB,CAAC;QAED,OAAO,OAAO,CAAC,OAAO,CAAC,qBAAqB,EAAE,MAAM,CAAC,CAAC;IACxD,CAAC,CAAC,CAAC;IAEH,OAAO,IAAI,MAAM,CAAC,IAAI,aAAa,CAAC,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;AAC1D,CAAC"}
+41
View File
@@ -0,0 +1,41 @@
import type { Manifest, MiddlewareInfo, Route } from '../manifest';
import { MiddlewareModule } from '../utils/middleware';
/** Internal errors class to indicate that the server has failed
* @remarks
* This should be thrown for unexpected errors, so they show up as crashes.
* Typically malformed project structure, missing manifest, html or other files.
*/
export declare class ExpoError extends Error {
constructor(message: string);
static isExpoError(error: unknown): error is ExpoError;
}
type ResponseInitLike = Omit<ResponseInit, 'headers'> & {
headers: Headers;
cf?: unknown;
webSocket?: unknown;
};
type CallbackRouteType = 'html' | 'api' | 'notFoundHtml' | 'notAllowedApi';
type CallbackRoute = (Route & {
type: CallbackRouteType;
}) | {
type: null;
};
type BeforeResponseCallback = (responseInit: ResponseInitLike, route: CallbackRoute) => ResponseInitLike;
export interface RequestHandlerParams {
/** Before handler response 4XX, not before unhandled error */
beforeErrorResponse?: BeforeResponseCallback;
/** Before handler responses */
beforeResponse?: BeforeResponseCallback;
/** Before handler HTML responses, not before 404 HTML */
beforeHTMLResponse?: BeforeResponseCallback;
/** Before handler API responses */
beforeAPIResponse?: BeforeResponseCallback;
}
export interface RequestHandlerInput {
getHtml(request: Request, route: Route): Promise<string | Response | null>;
getRoutesManifest(): Promise<Manifest | null>;
getApiRoute(route: Route): Promise<any>;
getMiddleware(route: MiddlewareInfo): Promise<MiddlewareModule>;
}
export declare function createRequestHandler({ getRoutesManifest, getHtml, getApiRoute, getMiddleware, beforeErrorResponse, beforeResponse, beforeHTMLResponse, beforeAPIResponse, }: RequestHandlerParams & RequestHandlerInput): (request: Request) => Promise<Response>;
export {};
+247
View File
@@ -0,0 +1,247 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExpoError = void 0;
exports.createRequestHandler = createRequestHandler;
const ImmutableRequest_1 = require("../ImmutableRequest");
const matchers_1 = require("../utils/matchers");
const middleware_1 = require("../utils/middleware");
/** Internal errors class to indicate that the server has failed
* @remarks
* This should be thrown for unexpected errors, so they show up as crashes.
* Typically malformed project structure, missing manifest, html or other files.
*/
class ExpoError extends Error {
constructor(message) {
super(message);
this.name = 'ExpoError';
}
static isExpoError(error) {
return !!error && error instanceof ExpoError;
}
}
exports.ExpoError = ExpoError;
function noopBeforeResponse(responseInit, _route) {
return responseInit;
}
function createRequestHandler({ getRoutesManifest, getHtml, getApiRoute, getMiddleware, beforeErrorResponse = noopBeforeResponse, beforeResponse = noopBeforeResponse, beforeHTMLResponse = noopBeforeResponse, beforeAPIResponse = noopBeforeResponse, }) {
let manifest = null;
return async function handler(request) {
if (!manifest) {
manifest = await getRoutesManifest();
}
return requestHandler(request, manifest);
};
async function requestHandler(incomingRequest, manifest) {
if (!manifest) {
// NOTE(@EvanBacon): Development error when Expo Router is not setup.
// NOTE(@kitten): If the manifest is not found, we treat this as
// an SSG deployment and do nothing
return createResponse(null, null, 'Not found', {
status: 404,
headers: new Headers({
'Content-Type': 'text/plain',
}),
});
}
let request = incomingRequest;
let url = new URL(request.url);
if (manifest.middleware) {
const middleware = await getMiddleware(manifest.middleware);
if ((0, middleware_1.shouldRunMiddleware)(request, middleware)) {
const middlewareResponse = await middleware.default(new ImmutableRequest_1.ImmutableRequest(request));
if (middlewareResponse instanceof Response) {
return middlewareResponse;
}
// If middleware returns undefined/void, continue to route matching
}
}
if (manifest.redirects) {
for (const route of manifest.redirects) {
if (!route.namedRegex.test(url.pathname)) {
continue;
}
if (route.methods && !route.methods.includes(request.method)) {
continue;
}
return respondRedirect(url, request, route);
}
}
if (manifest.rewrites) {
for (const route of manifest.rewrites) {
if (!route.namedRegex.test(url.pathname)) {
continue;
}
if (route.methods && !route.methods.includes(request.method)) {
continue;
}
// Replace URL and Request with rewrite target
url = (0, matchers_1.getRedirectRewriteLocation)(url, request, route);
request = new Request(url, request);
}
}
// First, test static routes
if (request.method === 'GET' || request.method === 'HEAD') {
for (const route of manifest.htmlRoutes) {
if (!route.namedRegex.test(url.pathname)) {
continue;
}
const html = await getHtml(request, route);
return respondHTML(html, route);
}
}
// Next, test API routes
for (const route of manifest.apiRoutes) {
if (!route.namedRegex.test(url.pathname)) {
continue;
}
const mod = await getApiRoute(route);
return await respondAPI(mod, request, route);
}
// Finally, test 404 routes
if (request.method === 'GET' || request.method === 'HEAD') {
for (const route of manifest.notFoundRoutes) {
if (!route.namedRegex.test(url.pathname)) {
continue;
}
try {
const contents = await getHtml(request, route);
return respondNotFoundHTML(contents, route);
}
catch {
// NOTE(@krystofwoldrich): Should we show a dismissible RedBox in development?
// Handle missing/corrupted not found route files
continue;
}
}
}
// 404
return createResponse(null, null, 'Not found', {
status: 404,
headers: new Headers({ 'Content-Type': 'text/plain' }),
});
}
function createResponse(routeType = null, route, bodyInit, responseInit) {
const originalStatus = responseInit.status;
let callbackRoute;
if (route && routeType) {
route.type = routeType;
callbackRoute = route;
}
else {
callbackRoute = { type: null };
}
let modifiedResponseInit = responseInit;
// Apply user-defined headers, if provided
if (manifest?.headers) {
for (const headerName in manifest.headers) {
if (Array.isArray(manifest.headers[headerName])) {
for (const headerValue of manifest.headers[headerName]) {
modifiedResponseInit.headers.append(headerName, headerValue);
}
}
else if (manifest.headers[headerName] != null &&
!modifiedResponseInit.headers.has(headerName)) {
modifiedResponseInit.headers.set(headerName, manifest.headers[headerName]);
}
}
}
// Callback call order matters, general rule is to call more specific callbacks first.
if (routeType === 'html') {
modifiedResponseInit = beforeHTMLResponse(modifiedResponseInit, callbackRoute);
}
if (routeType === 'api') {
modifiedResponseInit = beforeAPIResponse(modifiedResponseInit, callbackRoute);
}
// Second to last is error response callback
if (typeof originalStatus === 'number' &&
(originalStatus === 0 /* Response.error() */ || originalStatus > 399)) {
modifiedResponseInit = beforeErrorResponse(modifiedResponseInit, callbackRoute);
}
// Generic before response callback last
modifiedResponseInit = beforeResponse(modifiedResponseInit, callbackRoute);
if (originalStatus === 0) {
// Response.error() results in status 0, which will cause new Response() to fail.
// We convert it to 500 only if originally 0, if cbs set the values to 0, we don't protect against it.
modifiedResponseInit.status = 500;
}
return new Response(bodyInit, modifiedResponseInit);
}
function createResponseFrom(routeType = null, route, response) {
const modifiedResponseInit = {
headers: new Headers(response.headers),
status: response.status,
statusText: response.statusText,
cf: response.cf,
webSocket: response.webSocket,
};
return createResponse(routeType, route, response.body, modifiedResponseInit);
}
async function respondNotFoundHTML(html, route) {
if (typeof html === 'string') {
return createResponse('notFoundHtml', route, html, {
status: 404,
headers: new Headers({
'Content-Type': 'text/html',
}),
});
}
if ((0, matchers_1.isResponse)(html)) {
// Only used for development errors
return html;
}
throw new ExpoError(`HTML route file ${route.page}.html could not be loaded`);
}
async function respondAPI(mod, request, route) {
if (!mod || typeof mod !== 'object') {
throw new ExpoError(`API route module ${route.page} could not be loaded`);
}
if ((0, matchers_1.isResponse)(mod)) {
// Only used for development API route bundling errors
return mod;
}
const handler = mod[request.method];
if (!handler || typeof handler !== 'function') {
return createResponse('notAllowedApi', route, 'Method not allowed', {
status: 405,
headers: new Headers({
'Content-Type': 'text/plain',
}),
});
}
const params = (0, matchers_1.parseParams)(request, route);
const response = await handler(request, params);
if (!(0, matchers_1.isResponse)(response)) {
throw new ExpoError(`API route ${request.method} handler ${route.page} resolved to a non-Response result`);
}
return createResponseFrom('api', route, response);
}
function respondHTML(html, route) {
if (typeof html === 'string') {
return createResponse('html', route, html, {
status: 200,
headers: new Headers({
'Content-Type': 'text/html',
}),
});
}
if ((0, matchers_1.isResponse)(html)) {
// Only used for development error responses
return html;
}
throw new ExpoError(`HTML route file ${route.page}.html could not be loaded`);
}
function respondRedirect(url, request, route) {
// NOTE(@krystofwoldrich): @expo/server would not redirect when location was empty,
// it would keep searching for match and eventually return 404. Worker redirects to origin.
const target = (0, matchers_1.getRedirectRewriteLocation)(url, request, route);
let status;
if (request.method === 'GET' || request.method === 'HEAD') {
status = route.permanent ? 301 : 302;
}
else {
status = route.permanent ? 308 : 307;
}
return Response.redirect(target, status);
}
}
//# sourceMappingURL=abstract.js.map
File diff suppressed because one or more lines are too long
+12
View File
@@ -0,0 +1,12 @@
import { type RequestHandlerInput as ExpoRequestHandlerInput, type RequestHandlerParams as ExpoRequestHandlerParams } from './abstract';
export { ExpoError } from './abstract';
export type RequestHandler = (req: Request) => Promise<Response>;
export interface RequestHandlerParams extends ExpoRequestHandlerParams, Partial<ExpoRequestHandlerInput> {
}
/**
* Returns a request handler for Express that serves the response using Remix.
*/
export declare function createRequestHandler(params: {
build: string;
environment?: string | null;
}, setup?: RequestHandlerParams): RequestHandler;
+22
View File
@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExpoError = void 0;
exports.createRequestHandler = createRequestHandler;
const node_async_hooks_1 = require("node:async_hooks");
const abstract_1 = require("./abstract");
const node_1 = require("./environment/node");
var abstract_2 = require("./abstract");
Object.defineProperty(exports, "ExpoError", { enumerable: true, get: function () { return abstract_2.ExpoError; } });
const STORE = new node_async_hooks_1.AsyncLocalStorage();
/**
* Returns a request handler for Express that serves the response using Remix.
*/
function createRequestHandler(params, setup) {
const run = (0, node_1.createNodeRequestScope)(STORE, params);
const onRequest = (0, abstract_1.createRequestHandler)({
...(0, node_1.createNodeEnv)(params),
...setup,
});
return (request) => run(onRequest, request);
}
//# sourceMappingURL=bun.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"bun.js","sourceRoot":"","sources":["../../../src/vendor/bun.ts"],"names":[],"mappings":";;;AAsBA,oDAUC;AAhCD,uDAAqD;AAErD,yCAIoB;AACpB,6CAA2E;AAE3E,uCAAuC;AAA9B,qGAAA,SAAS,OAAA;AAIlB,MAAM,KAAK,GAAG,IAAI,oCAAiB,EAAE,CAAC;AAMtC;;GAEG;AACH,SAAgB,oBAAoB,CAClC,MAAsD,EACtD,KAA4B;IAE5B,MAAM,GAAG,GAAG,IAAA,6BAAsB,EAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAClD,MAAM,SAAS,GAAG,IAAA,+BAAiB,EAAC;QAClC,GAAG,IAAA,oBAAa,EAAC,MAAM,CAAC;QACxB,GAAG,KAAK;KACT,CAAC,CAAC;IACH,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,GAAG,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;AAC9C,CAAC"}
+10
View File
@@ -0,0 +1,10 @@
import { type RequestHandlerParams } from './abstract';
import { ExecutionContext } from './environment/workerd';
export { ExpoError } from './abstract';
export type RequestHandler<Env = unknown> = (req: Request, env: Env, ctx: ExecutionContext) => Promise<Response>;
/**
* Returns a request handler for EAS Hosting deployments.
*/
export declare function createRequestHandler<Env = unknown>(params: {
build?: string;
}, setup?: RequestHandlerParams): RequestHandler<Env>;
+28
View File
@@ -0,0 +1,28 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExpoError = void 0;
exports.createRequestHandler = createRequestHandler;
const node_async_hooks_1 = require("node:async_hooks");
const runtime_1 = require("../runtime");
const abstract_1 = require("./abstract");
const workerd_1 = require("./environment/workerd");
var abstract_2 = require("./abstract");
Object.defineProperty(exports, "ExpoError", { enumerable: true, get: function () { return abstract_2.ExpoError; } });
const STORE = new node_async_hooks_1.AsyncLocalStorage();
/**
* Returns a request handler for EAS Hosting deployments.
*/
function createRequestHandler(params, setup) {
const makeRequestAPISetup = (request, _env, ctx) => ({
origin: request.headers.get('Origin') || 'null',
environment: request.headers.get('eas-environment') || null,
waitUntil: ctx.waitUntil?.bind(ctx),
});
const run = (0, runtime_1.createRequestScope)(STORE, makeRequestAPISetup);
const onRequest = (0, abstract_1.createRequestHandler)({
...(0, workerd_1.createWorkerdEnv)(params),
...setup,
});
return (request, env, ctx) => run(onRequest, request, env, ctx);
}
//# sourceMappingURL=eas.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"eas.js","sourceRoot":"","sources":["../../../src/vendor/eas.ts"],"names":[],"mappings":";;;AAmBA,oDAeC;AAlCD,uDAAqD;AAErD,wCAAgD;AAChD,yCAAkG;AAClG,mDAA2E;AAE3E,uCAAuC;AAA9B,qGAAA,SAAS,OAAA;AAQlB,MAAM,KAAK,GAAG,IAAI,oCAAiB,EAAE,CAAC;AAEtC;;GAEG;AACH,SAAgB,oBAAoB,CAClC,MAA0B,EAC1B,KAA4B;IAE5B,MAAM,mBAAmB,GAAG,CAAC,OAAgB,EAAE,IAAS,EAAE,GAAqB,EAAE,EAAE,CAAC,CAAC;QACnF,MAAM,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,MAAM;QAC/C,WAAW,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,IAAI,IAAI;QAC3D,SAAS,EAAE,GAAG,CAAC,SAAS,EAAE,IAAI,CAAC,GAAG,CAAC;KACpC,CAAC,CAAC;IACH,MAAM,GAAG,GAAG,IAAA,4BAAkB,EAAC,KAAK,EAAE,mBAAmB,CAAC,CAAC;IAC3D,MAAM,SAAS,GAAG,IAAA,+BAAiB,EAAC;QAClC,GAAG,IAAA,0BAAgB,EAAC,MAAM,CAAC;QAC3B,GAAG,KAAK;KACT,CAAC,CAAC;IACH,OAAO,CAAC,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,SAAS,EAAE,OAAO,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;AAClE,CAAC"}
@@ -0,0 +1,13 @@
import type { Manifest, MiddlewareInfo, Route } from '../../manifest';
interface EnvironmentInput {
readText(request: string): Promise<string | null>;
readJson(request: string): Promise<unknown>;
loadModule(request: string): Promise<unknown>;
}
export declare function createEnvironment(input: EnvironmentInput): {
getRoutesManifest(): Promise<Manifest>;
getHtml(_request: Request, route: Route): Promise<string | Response | null>;
getApiRoute(route: Route): Promise<unknown>;
getMiddleware(middleware: MiddlewareInfo): Promise<any>;
};
export {};
@@ -0,0 +1,63 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createEnvironment = createEnvironment;
function initManifestRegExp(manifest) {
return {
...manifest,
htmlRoutes: manifest.htmlRoutes.map((route) => ({
...route,
namedRegex: new RegExp(route.namedRegex),
})),
apiRoutes: manifest.apiRoutes.map((route) => ({
...route,
namedRegex: new RegExp(route.namedRegex),
})),
notFoundRoutes: manifest.notFoundRoutes.map((route) => ({
...route,
namedRegex: new RegExp(route.namedRegex),
})),
redirects: manifest.redirects?.map((route) => ({
...route,
namedRegex: new RegExp(route.namedRegex),
})),
rewrites: manifest.rewrites?.map((route) => ({
...route,
namedRegex: new RegExp(route.namedRegex),
})),
};
}
function createEnvironment(input) {
return {
async getRoutesManifest() {
const json = await input.readJson('_expo/routes.json');
return initManifestRegExp(json);
},
async getHtml(_request, route) {
let html;
if ((html = await input.readText(route.page + '.html')) != null) {
return html;
}
// Serve a static file by route name with hoisted index
// See: https://github.com/expo/expo/pull/27935
const INDEX_PATH = '/index';
if (route.page.endsWith(INDEX_PATH) && route.page.length > INDEX_PATH.length) {
const page = route.page.slice(0, -INDEX_PATH.length);
if ((html = await input.readText(page + '.html')) != null) {
return html;
}
}
return null;
},
async getApiRoute(route) {
return input.loadModule(route.file);
},
async getMiddleware(middleware) {
const mod = (await input.loadModule(middleware.file));
if (typeof mod?.default !== 'function') {
return null;
}
return mod;
},
};
}
//# sourceMappingURL=common.js.map
@@ -0,0 +1 @@
{"version":3,"file":"common.js","sourceRoot":"","sources":["../../../../src/vendor/environment/common.ts"],"names":[],"mappings":";;AAkCA,8CAoCC;AApED,SAAS,kBAAkB,CAAC,QAAqB;IAC/C,OAAO;QACL,GAAG,QAAQ;QACX,UAAU,EAAE,QAAQ,CAAC,UAAU,CAAC,GAA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K,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,GAAG,OAAO,CAAC,CAAC,IAAI,IAAI,EAAE,CAAC;gBAChE,OAAO,IAAI,CAAC;YACd,CAAC;YACD,uDAAuD;YACvD,+CAA+C;YAC/C,MAAM,UAAU,GAAG,QAAQ,CAAC;YAC5B,IAAI,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC,IAAI,KAAK,CAAC,IAAI,CAAC,MAAM,GAAG,UAAU,CAAC,MAAM,EAAE,CAAC;gBAC7E,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;gBACrD,IAAI,CAAC,IAAI,GAAG,MAAM,KAAK,CAAC,QAAQ,CAAC,IAAI,GAAG,OAAO,CAAC,CAAC,IAAI,IAAI,EAAE,CAAC;oBAC1D,OAAO,IAAI,CAAC;gBACd,CAAC;YACH,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC;QAED,KAAK,CAAC,WAAW,CAAC,KAAY;YAC5B,OAAO,KAAK,CAAC,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACtC,CAAC;QAED,KAAK,CAAC,aAAa,CAAC,UAA0B;YAC5C,MAAM,GAAG,GAAG,CAAC,MAAM,KAAK,CAAC,UAAU,CAAC,UAAU,CAAC,IAAI,CAAC,CAAQ,CAAC;YAC7D,IAAI,OAAO,GAAG,EAAE,OAAO,KAAK,UAAU,EAAE,CAAC;gBACvC,OAAO,IAAI,CAAC;YACd,CAAC;YACD,OAAO,GAAG,CAAC;QACb,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,13 @@
import type { ScopeDefinition } from '../../runtime/scope';
interface NodeEnvParams {
build: string;
environment?: string | null;
}
export declare function createNodeEnv(params: NodeEnvParams): {
getRoutesManifest(): Promise<import("../../manifest").Manifest>;
getHtml(_request: Request, route: import("../../manifest").Route): Promise<string | Response | null>;
getApiRoute(route: import("../../manifest").Route): Promise<unknown>;
getMiddleware(middleware: import("../../manifest").MiddlewareInfo): Promise<any>;
};
export declare function createNodeRequestScope(scopeDefinition: ScopeDefinition, params: NodeEnvParams): (fn: (request: Request) => Promise<Response>, request: Request) => Promise<Response>;
export {};
@@ -0,0 +1,55 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createNodeEnv = createNodeEnv;
exports.createNodeRequestScope = createNodeRequestScope;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const common_1 = require("./common");
const ImmutableRequest_1 = require("../../ImmutableRequest");
const runtime_1 = require("../../runtime");
function createNodeEnv(params) {
(0, ImmutableRequest_1.assertRuntimeFetchAPISupport)();
async function readText(request) {
const filePath = node_path_1.default.join(params.build, request);
if (!node_fs_1.default.existsSync(filePath)) {
return null;
}
try {
return await node_fs_1.default.promises.readFile(filePath, 'utf-8');
}
catch {
return null;
}
}
async function readJson(request) {
const json = await readText(request);
return json != null ? JSON.parse(json) : null;
}
async function loadModule(request) {
const filePath = node_path_1.default.join(params.build, request);
if (!node_fs_1.default.existsSync(filePath)) {
return null;
}
else if (/\.c?js$/.test(filePath)) {
return require(filePath);
}
else {
return await import(filePath);
}
}
return (0, common_1.createEnvironment)({
readText,
readJson,
loadModule,
});
}
function createNodeRequestScope(scopeDefinition, params) {
return (0, runtime_1.createRequestScope)(scopeDefinition, (request) => ({
origin: request.headers.get('Origin') || 'null',
environment: params.environment ?? process.env.NODE_ENV,
}));
}
//# sourceMappingURL=node.js.map
@@ -0,0 +1 @@
{"version":3,"file":"node.js","sourceRoot":"","sources":["../../../../src/vendor/environment/node.ts"],"names":[],"mappings":";;;;;AAaA,sCAoCC;AAED,wDAKC;AAxDD,sDAAyB;AACzB,0DAA6B;AAE7B,qCAA6C;AAC7C,6DAAsE;AACtE,2CAAmD;AAQnD,SA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gB,sBAAsB,CAAC,eAAgC,EAAE,MAAqB;IAC5F,OAAO,IAAA,4BAAkB,EAAC,eAAe,EAAE,CAAC,OAAgB,EAAE,EAAE,CAAC,CAAC;QAChE,MAAM,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,MAAM;QAC/C,WAAW,EAAE,MAAM,CAAC,WAAW,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ;KACxD,CAAC,CAAC,CAAC;AACN,CAAC"}
@@ -0,0 +1,17 @@
import type { ScopeDefinition } from '../../runtime/scope';
interface WorkerdEnvParams {
build?: string;
environment?: string | null;
}
export declare function createWorkerdEnv(params: WorkerdEnvParams): {
getRoutesManifest(): Promise<import("../../manifest").Manifest>;
getHtml(_request: Request, route: import("../../manifest").Route): Promise<string | Response | null>;
getApiRoute(route: import("../../manifest").Route): Promise<unknown>;
getMiddleware(middleware: import("../../manifest").MiddlewareInfo): Promise<any>;
};
export interface ExecutionContext {
waitUntil?(promise: Promise<any>): void;
props?: any;
}
export declare function createWorkerdRequestScope<Env = unknown>(scopeDefinition: ScopeDefinition, params: WorkerdEnvParams): (fn: (request: Request, _env: Env, ctx: ExecutionContext) => Promise<Response>, request: Request, _env: Env, ctx: ExecutionContext) => Promise<Response>;
export {};
@@ -0,0 +1,72 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createWorkerdEnv = createWorkerdEnv;
exports.createWorkerdRequestScope = createWorkerdRequestScope;
const common_1 = require("./common");
const runtime_1 = require("../../runtime");
const createCachedImport = () => {
const importCache = new Map();
return async function importCached(request) {
let result = importCache.get(request);
if (!result) {
try {
result = { type: 'success', value: await import(request) };
}
catch (error) {
result = { type: 'error', value: error };
}
importCache.set(request, result);
}
if (result.type === 'success') {
return result.value;
}
else {
throw result.value;
}
};
};
function createWorkerdEnv(params) {
const build = params.build || '.';
const importCached = createCachedImport();
async function readText(request) {
try {
const mod = await importCached(`${build}/${request}`);
return mod.default;
}
catch {
return null;
}
}
async function readJson(request) {
try {
const mod = await importCached(`${build}/${request}`);
if (typeof mod.default === 'string' && mod.default[0] === '{') {
return JSON.parse(mod.default);
}
else {
return mod.default;
}
}
catch {
return null;
}
}
async function loadModule(request) {
const target = `${build}/${request}`;
return (await import(target)).default;
}
return (0, common_1.createEnvironment)({
readText,
readJson,
loadModule,
});
}
function createWorkerdRequestScope(scopeDefinition, params) {
const makeRequestAPISetup = (request, _env, ctx) => ({
origin: request.headers.get('Origin') || 'null',
environment: params.environment ?? null,
waitUntil: ctx.waitUntil?.bind(ctx),
});
return (0, runtime_1.createRequestScope)(scopeDefinition, makeRequestAPISetup);
}
//# sourceMappingURL=workerd.js.map
@@ -0,0 +1 @@
{"version":3,"file":"workerd.js","sourceRoot":"","sources":["../../../../src/vendor/environment/workerd.ts"],"names":[],"mappings":";;AA6BA,4CAoCC;AAOD,8DAUC;AAlFD,qCAA6C;AAC7C,2CAAmD;AAGnD,MAAM,kBAAkB,GAAG,GAAG,EAAE;IAC9B,MAAM,WAAW,GAAG,IAAI,GAAG,EAAyD,CAAC;IACrF,OAAO,KAAK,UAAU,YAAY,CAAU,OAAe;QACzD,IAAI,MAAM,GAAG,WAAW,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QACtC,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,IAAI,CAAC;gBACH,MAAM,GAAG,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC;YAC7D,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;YAC3C,CAAC;YACD,WAAW,CAAC,GAAG,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QACnC,CAAC;QACD,IAAI,MAAM,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YAC9B,OAAO,MAAM,CAAC,KAAU,CAAC;QAC3B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AC;AAOD,SAAgB,yBAAyB,CACvC,eAAgC,EAChC,MAAwB;IAExB,MAAM,mBAAmB,GAAG,CAAC,OAAgB,EAAE,IAAS,EAAE,GAAqB,EAAE,EAAE,CAAC,CAAC;QACnF,MAAM,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,MAAM;QAC/C,WAAW,EAAE,MAAM,CAAC,WAAW,IAAI,IAAI;QACvC,SAAS,EAAE,GAAG,CAAC,SAAS,EAAE,IAAI,CAAC,GAAG,CAAC;KACpC,CAAC,CAAC;IACH,OAAO,IAAA,4BAAkB,EAAC,eAAe,EAAE,mBAAmB,CAAC,CAAC;AAClE,CAAC"}
+17
View File
@@ -0,0 +1,17 @@
import type * as express from 'express';
import { type RequestHandlerInput as ExpoRequestHandlerInput, type RequestHandlerParams as ExpoRequestHandlerParams } from './abstract';
export { ExpoError } from './abstract';
export type RequestHandler = (req: express.Request, res: express.Response, next: express.NextFunction) => Promise<void>;
export interface RequestHandlerParams extends ExpoRequestHandlerParams, Partial<ExpoRequestHandlerInput> {
handleRouteError?(error: Error): Promise<Response>;
}
/**
* Returns a request handler for Express that serves the response using Remix.
*/
export declare function createRequestHandler(params: {
build: string;
environment?: string | null;
}, setup?: RequestHandlerParams): RequestHandler;
export declare function convertHeaders(requestHeaders: express.Request['headers']): Headers;
export declare function convertRequest(req: express.Request, res: express.Response): Request;
export declare function respond(res: express.Response, expoRes: Response): Promise<void>;
+117
View File
@@ -0,0 +1,117 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExpoError = void 0;
exports.createRequestHandler = createRequestHandler;
exports.convertHeaders = convertHeaders;
exports.convertRequest = convertRequest;
exports.respond = respond;
const node_async_hooks_1 = require("node:async_hooks");
const node_stream_1 = require("node:stream");
const promises_1 = require("node:stream/promises");
const abstract_1 = require("./abstract");
const node_1 = require("./environment/node");
var abstract_2 = require("./abstract");
Object.defineProperty(exports, "ExpoError", { enumerable: true, get: function () { return abstract_2.ExpoError; } });
const STORE = new node_async_hooks_1.AsyncLocalStorage();
/**
* Returns a request handler for Express that serves the response using Remix.
*/
function createRequestHandler(params, setup) {
const run = (0, node_1.createNodeRequestScope)(STORE, params);
const onRequest = (0, abstract_1.createRequestHandler)({
...(0, node_1.createNodeEnv)(params),
...setup,
});
async function requestHandler(request) {
try {
return await run(onRequest, request);
}
catch (error) {
const handleRouteError = setup?.handleRouteError;
if (handleRouteError && error != null && typeof error === 'object') {
try {
return await handleRouteError(error);
}
catch {
// Rethrow original error below
}
}
throw error;
}
}
return async (req, res, next) => {
if (!req?.url || !req.method) {
return next();
}
try {
const request = convertRequest(req, res);
const response = await requestHandler(request);
await respond(res, response);
}
catch (error) {
// Express doesn't support async functions, so we have to pass along the
// error manually using next().
next(error);
}
};
}
function convertHeaders(requestHeaders) {
const headers = new Headers();
for (const [key, values] of Object.entries(requestHeaders)) {
if (values) {
if (Array.isArray(values)) {
for (const value of values) {
headers.append(key, value);
}
}
else {
headers.set(key, values);
}
}
}
return headers;
}
function convertRawHeaders(requestHeaders) {
const headers = new Headers();
for (let index = 0; index < requestHeaders.length; index += 2) {
headers.append(requestHeaders[index], requestHeaders[index + 1]);
}
return headers;
}
function convertRequest(req, res) {
const url = new URL(`${req.protocol}://${req.get('host')}${req.url}`);
// Abort action/loaders once we can no longer write a response
const controller = new AbortController();
res.on('close', () => controller.abort());
const init = {
method: req.method,
headers: convertRawHeaders(req.rawHeaders),
// Cast until reason/throwIfAborted added
// https://github.com/mysticatea/abort-controller/issues/36
signal: controller.signal,
};
if (req.method !== 'GET' && req.method !== 'HEAD') {
init.body = node_stream_1.Readable.toWeb(req);
init.duplex = 'half';
}
return new Request(url.href, init);
}
async function respond(res, expoRes) {
res.statusMessage = expoRes.statusText;
res.status(expoRes.status);
if (typeof res.setHeaders === 'function') {
res.setHeaders(expoRes.headers);
}
else {
for (const [key, value] of expoRes.headers.entries()) {
res.appendHeader(key, value);
}
}
if (expoRes.body) {
await (0, promises_1.pipeline)(node_stream_1.Readable.fromWeb(expoRes.body), res);
}
else {
res.end();
}
}
//# sourceMappingURL=express.js.map
@@ -0,0 +1 @@
{"version":3,"file":"express.js","sourceRoot":"","sources":["../../../src/vendor/express.ts"],"names":[],"mappings":";;;AAgCA,oDAwCC;AAED,wCAcC;AAUD,wCAqBC;AAED,0BAiBC;AAzID,uDAAqD;AACrD,6CAAuC;AACvC,mDAAgD;AAGhD,yCAIoB;AACpB,6CAA2E;AAE3E,uCAAuC;AAA9B,qGAAA,SAAS,OAAA;AAQlB,MAAM,KAAK,GAAG,IAAI,oCAAiB,EAAE,CAAC;AAQtC;;GAEG;AACH,SAAgB,oBAAoB,CAClC,MAAsD,EACtD,KAA4B;IAE5B,MAAM,GAAG,GAAG,IAAA,6BAAsB,EAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAClD,MAAM,SAAS,GAAG,IAAA,+BAAiB,EAAC;QAClC,GAAG,IAAA,oBAAa,EAAC,MAAM,CAAC;QACxB,GAAG,KAAK;KACT,CAAC,CAAC;IAEH,KAAK,UAAU,cAAc,CAAC,OAAgB;QAC5C,IAAI,CAAC;YACH,OAAO,MAAM,GAAG,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QACvC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,gBAAgB,GAAG,KAAK,EAAE,gBAAgB,CAAC;YACjD,IAAI,gBAAgB,IAAI,KAAK,IAAI,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;gBACnE,IAAI,CAAC;oBACH,OAAO,MAAM,gBAAgB,CAAC,KAAc,CAAC,CAAC;gBAChD,CAAC;gBAAC,MAAM,CAAC;oBACP,+BAA+B;gBACjC,CAAC;YACH,CAAC;YACD,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;IAED,OAAO,KAAK,EAAE,GAAoB,EAAE,GAAqB,EAAE,IAA0B,EAAE,EAAE;QACvF,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,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CAAC,CAAC;IAClC,CAAC;SAAM,CAAC;QACN,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,OAAO,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC;YACrD,GAAG,CAAC,YAAY,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QAC/B,CAAC;IACH,CAAC;IAED,IAAI,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,MAAM,IAAA,mBAAQ,EAAC,sBAAQ,CAAC,OAAO,CAAC,OAAO,CAAC,IAA0B,CAAC,EAAE,GAAG,CAAC,CAAC;IAC5E,CAAC;SAAM,CAAC;QACN,GAAG,CAAC,GAAG,EAAE,CAAC;IACZ,CAAC;AACH,CAAC"}
+18
View File
@@ -0,0 +1,18 @@
import * as http from 'http';
import { type RequestHandlerInput as ExpoRequestHandlerInput, type RequestHandlerParams as ExpoRequestHandlerParams } from './abstract';
export { ExpoError } from './abstract';
type NextFunction = (err?: any) => void;
export type RequestHandler = (req: http.IncomingMessage, res: http.ServerResponse, next: NextFunction) => Promise<void>;
export interface RequestHandlerParams extends ExpoRequestHandlerParams, Partial<ExpoRequestHandlerInput> {
handleRouteError?(error: Error): Promise<Response>;
}
/**
* Returns a request handler for http that serves the response using Remix.
*/
export declare function createRequestHandler(params: {
build: string;
environment?: string | null;
}, setup?: Partial<RequestHandlerParams>): RequestHandler;
export declare function convertRequest(req: http.IncomingMessage, res: http.ServerResponse): Request;
export declare function convertHeaders(requestHeaders: http.IncomingHttpHeaders): Headers;
export declare function respond(res: http.ServerResponse, expoRes: Response): Promise<void>;
+118
View File
@@ -0,0 +1,118 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExpoError = void 0;
exports.createRequestHandler = createRequestHandler;
exports.convertRequest = convertRequest;
exports.convertHeaders = convertHeaders;
exports.respond = respond;
const node_async_hooks_1 = require("node:async_hooks");
const node_stream_1 = require("node:stream");
const promises_1 = require("node:stream/promises");
const abstract_1 = require("./abstract");
const node_1 = require("./environment/node");
var abstract_2 = require("./abstract");
Object.defineProperty(exports, "ExpoError", { enumerable: true, get: function () { return abstract_2.ExpoError; } });
const STORE = new node_async_hooks_1.AsyncLocalStorage();
/**
* Returns a request handler for http that serves the response using Remix.
*/
function createRequestHandler(params, setup) {
const run = (0, node_1.createNodeRequestScope)(STORE, params);
const onRequest = (0, abstract_1.createRequestHandler)({
...(0, node_1.createNodeEnv)(params),
...setup,
});
async function requestHandler(request) {
try {
return await run(onRequest, request);
}
catch (error) {
const handleRouteError = setup?.handleRouteError;
if (handleRouteError && error != null && typeof error === 'object') {
try {
return await handleRouteError(error);
}
catch {
// Rethrow original error below
}
}
throw error;
}
}
return async (req, res, next) => {
if (!req?.url || !req.method) {
return next();
}
try {
const request = convertRequest(req, res);
const response = await requestHandler(request);
await respond(res, response);
}
catch (error) {
// http doesn't support async functions, so we have to pass along the
// error manually using next().
next(error);
}
};
}
function convertRawHeaders(requestHeaders) {
const headers = new Headers();
for (let index = 0; index < requestHeaders.length; index += 2) {
headers.append(requestHeaders[index], requestHeaders[index + 1]);
}
return headers;
}
// Convert an http request to an expo request
function convertRequest(req, res) {
const url = new URL(req.url, `http://${req.headers.host}`);
// Abort action/loaders once we can no longer write a response
const controller = new AbortController();
res.on('close', () => controller.abort());
const init = {
method: req.method,
headers: convertRawHeaders(req.rawHeaders),
// Cast until reason/throwIfAborted added
// https://github.com/mysticatea/abort-controller/issues/36
signal: controller.signal,
};
if (req.method !== 'GET' && req.method !== 'HEAD') {
init.body = node_stream_1.Readable.toWeb(req);
init.duplex = 'half';
}
return new Request(url.href, init);
}
function convertHeaders(requestHeaders) {
const headers = new Headers();
for (const [key, values] of Object.entries(requestHeaders)) {
if (values) {
if (Array.isArray(values)) {
for (const value of values) {
headers.append(key, value);
}
}
else {
headers.set(key, values);
}
}
}
return headers;
}
async function respond(res, expoRes) {
res.statusMessage = expoRes.statusText;
res.statusCode = expoRes.status;
if (typeof res.setHeaders === 'function') {
res.setHeaders(expoRes.headers);
}
else {
for (const [key, value] of expoRes.headers.entries()) {
res.appendHeader(key, value);
}
}
if (expoRes.body) {
await (0, promises_1.pipeline)(node_stream_1.Readable.fromWeb(expoRes.body), res);
}
else {
res.end();
}
}
//# sourceMappingURL=http.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"http.js","sourceRoot":"","sources":["../../../src/vendor/http.ts"],"names":[],"mappings":";;;AAkCA,oDAwCC;AAWD,wCAqBC;AAED,wCAcC;AAED,0BAiBC;AA5ID,uDAAqD;AACrD,6CAAuC;AACvC,mDAAgD;AAGhD,yCAIoB;AACpB,6CAA2E;AAE3E,uCAAuC;AAA9B,qGAAA,SAAS,OAAA;AAUlB,MAAM,KAAK,GAAG,IAAI,oCAAiB,EAAE,CAAC;AAQtC;;GAEG;AACH,SAAgB,oBAAoB,CAClC,MAAsD,EACtD,KAAqC;IAErC,MAAM,GAAG,GAAG,IAAA,6BAAsB,EAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAClD,MAAM,SAAS,GAAG,IAAA,+BAAiB,EAAC;QAClC,GAAG,IAAA,oBAAa,EAAC,MAAM,CAAC;QACxB,GAAG,KAAK;KACT,CAAC,CAAC;IAEH,KAAK,UAAU,cAAc,CAAC,OAAgB;QAC5C,IAAI,CAAC;YACH,OAAO,MAAM,GAAG,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QACvC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,gBAAgB,GAAG,KAAK,EAAE,gBAAgB,CAAC;YACjD,IAAI,gBAAgB,IAAI,KAAK,IAAI,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;gBACnE,IAAI,CAAC;oBACH,OAAO,MAAM,gBAAgB,CAAC,KAAc,CAAC,CAAC;gBAChD,CAAC;gBAAC,MAAM,CAAC;oBACP,+BAA+B;gBACjC,CAAC;YACH,CAAC;YACD,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;IAED,OAAO,KAAK,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,KAAK,UAAU,EAAE,CAAC;QACzC,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IAClC,CAAC;SAAM,CAAC;QACN,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,OAAO,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC;YACrD,GAAG,CAAC,YAAY,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QAC/B,CAAC;IACH,CAAC;IAED,IAAI,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,MAAM,IAAA,mBAAQ,EAAC,sBAAQ,CAAC,OAAO,CAAC,OAAO,CAAC,IAA0B,CAAC,EAAE,GAAG,CAAC,CAAC;IAC5E,CAAC;SAAM,CAAC;QACN,GAAG,CAAC,GAAG,EAAE,CAAC;IACZ,CAAC;AACH,CAAC"}
+15
View File
@@ -0,0 +1,15 @@
export { ExpoError } from './abstract';
declare const scopeSymbol: unique symbol;
interface NetlifyContext {
deploy?: {
context?: string | null;
};
site?: {
url?: string | null;
};
waitUntil?: (promise: Promise<unknown>) => void;
[scopeSymbol]?: unknown;
}
export declare function createRequestHandler(params: {
build: string;
}): (req: Request, ctx?: NetlifyContext) => Promise<Response>;
+46
View File
@@ -0,0 +1,46 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExpoError = void 0;
exports.createRequestHandler = createRequestHandler;
const abstract_1 = require("./abstract");
const runtime_1 = require("../runtime");
const node_1 = require("./environment/node");
var abstract_2 = require("./abstract");
Object.defineProperty(exports, "ExpoError", { enumerable: true, get: function () { return abstract_2.ExpoError; } });
const scopeSymbol = Symbol.for('expoServerScope');
/** @see https://docs.netlify.com/build/functions/api/#netlify-specific-context-object */
function getContext() {
const fromGlobal = globalThis;
if (!fromGlobal.Netlify) {
throw new Error('"globalThis.Netlify" is missing but expected.\n' +
'- Are you using Netlify Server Functions 1.0 instead of 2.0?\n' +
'- Make sure your Netlify function has a default export instead of exporting "handler".');
}
return fromGlobal.Netlify?.context ?? {};
}
// Netlify already has an async-scoped context in NetlifyContext, so we can attach
// our scope context to this object
const STORE = {
getStore: () => getContext()[scopeSymbol],
run(scope, runner, ...args) {
getContext()[scopeSymbol] = scope;
return runner(...args);
},
};
function createRequestHandler(params) {
const makeRequestAPISetup = (request, context) => ({
origin: (context ?? getContext()).site?.url || request.headers.get('Origin') || 'null',
environment: (context ?? getContext()).deploy?.context || null,
waitUntil: (context ?? getContext()).waitUntil,
});
const run = (0, runtime_1.createRequestScope)(STORE, makeRequestAPISetup);
const onRequest = (0, abstract_1.createRequestHandler)((0, node_1.createNodeEnv)(params));
return async (req, ctx) => {
if ('multiValueHeaders' in req) {
throw new Error('Unexpected Request object. API was called by Netlify Server Functions 1.0\n' +
'- Make sure your Netlify function has a default export instead of exporting "handler".');
}
return await run(onRequest, req, ctx);
};
}
//# sourceMappingURL=netlify.js.map
@@ -0,0 +1 @@
{"version":3,"file":"netlify.js","sourceRoot":"","sources":["../../../src/vendor/netlify.ts"],"names":[],"mappings":";;;AAyCA,oDAiBC;AA1DD,yCAAuE;AACvE,wCAAgD;AAChD,6CAAmD;AAGnD,uCAAuC;AAA9B,qGAAA,SAAS,OAAA;AAElB,MAAM,WAAW,GAAG,MAAM,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;AASlD,yFAAyF;AACzF,SAAS,UAAU;IACjB,MAAM,UAAU,GAEZ,UAAU,CAAC;IACf,IAAI,CAAC,UAAU,CAAC,OAAO,EAAE,CAAC;QACxB,MAAM,IAAI,KAAK,CACb,iDAAiD;YAC/C,gEAAgE;YAChE,wFAAwF,CAC3F,CAAC;IACJ,CAAC;IACD,OAAO,UAAU,CAAC,OAAO,EAAE,OAAO,IAAI,EAAE,CAAC;AAC3C,CAAC;AAED,kFAAkF;AAClF,mCAAmC;AACnC,MAAM,KAAK,GAAoB;IAC7B,QAAQ,EAAE,GAAG,EAAE,CAAC,UAAU,EAAE,CAAC,WAAW,CAAC;IACzC,GAAG,CAAC,KAAU,EAAE,MAA+B,EAAE,GAAG,IAAW;QAC7D,UAAU,EAAE,CAAC,WAAW,CAAC,GAAG,KAAK,CAAC;QAClC,OAAO,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC;IACzB,CAAC;CACF,CAAC;AAEF,SAAgB,oBAAoB,CAAC,MAAyB;IAC5D,MAAM,mBAAmB,GAAG,CAAC,OAAgB,EAAE,OAAwB,EAAE,EAAE,CAAC,CAAC;QAC3E,MAAM,EAAE,CAAC,OAAO,IAAI,UAAU,EAAE,CAAC,CAAC,IAAI,EAAE,GAAG,IAAI,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,MAAM;QACtF,WAAW,EAAE,CAAC,OAAO,IAAI,UAAU,EAAE,CAAC,CAAC,MAAM,EAAE,OAAO,IAAI,IAAI;QAC9D,SAAS,EAAE,CAAC,OAAO,IAAI,UAAU,EAAE,CAAC,CAAC,SAAS;KAC/C,CAAC,CAAC;IACH,MAAM,GAAG,GAAG,IAAA,4BAAkB,EAAC,KAAK,EAAE,mBAAmB,CAAC,CAAC;IAC3D,MAAM,SAAS,GAAG,IAAA,+BAAiB,EAAC,IAAA,oBAAa,EAAC,MAAM,CAAC,CAAC,CAAC;IAC3D,OAAO,KAAK,EAAE,GAAY,EAAE,GAAoB,EAAE,EAAE;QAClD,IAAI,mBAAmB,IAAI,GAAG,EAAE,CAAC;YAC/B,MAAM,IAAI,KAAK,CACb,6EAA6E;gBAC3E,wFAAwF,CAC3F,CAAC;QACJ,CAAC;QACD,OAAO,MAAM,GAAG,CAAC,SAAS,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;IACxC,CAAC,CAAC;AACJ,CAAC"}
+13
View File
@@ -0,0 +1,13 @@
import * as http from 'http';
export { ExpoError } from './abstract';
export type RequestHandler = (req: http.IncomingMessage, res: http.ServerResponse) => Promise<void>;
/**
* Returns a request handler for Vercel's Node.js runtime that serves the
* response using Remix.
*/
export declare function createRequestHandler(params: {
build: string;
}): RequestHandler;
export declare function convertHeaders(requestHeaders: http.IncomingMessage['headers']): Headers;
export declare function convertRequest(req: http.IncomingMessage, res: http.ServerResponse): Request;
export declare function respond(res: http.ServerResponse, expoRes: Response): Promise<void>;
+109
View File
@@ -0,0 +1,109 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExpoError = void 0;
exports.createRequestHandler = createRequestHandler;
exports.convertHeaders = convertHeaders;
exports.convertRequest = convertRequest;
exports.respond = respond;
const node_stream_1 = require("node:stream");
const promises_1 = require("node:stream/promises");
const abstract_1 = require("./abstract");
const runtime_1 = require("../runtime");
const node_1 = require("./environment/node");
const createReadableStreamFromReadable_1 = require("../utils/createReadableStreamFromReadable");
var abstract_2 = require("./abstract");
Object.defineProperty(exports, "ExpoError", { enumerable: true, get: function () { return abstract_2.ExpoError; } });
const scopeSymbol = Symbol.for('expoServerScope');
const SYMBOL_FOR_REQ_CONTEXT = Symbol.for('@vercel/request-context');
/** @see https://github.com/vercel/vercel/blob/b189b39/packages/functions/src/get-context.ts */
function getContext() {
const fromSymbol = globalThis;
return fromSymbol[SYMBOL_FOR_REQ_CONTEXT]?.get?.() ?? {};
}
// Vercel already has an async-scoped context in VercelContext, so we can attach
// our scope context to this object
const STORE = {
getStore: () => getContext()[scopeSymbol],
run(scope, runner, ...args) {
getContext()[scopeSymbol] = scope;
return runner(...args);
},
};
/**
* Returns a request handler for Vercel's Node.js runtime that serves the
* response using Remix.
*/
function createRequestHandler(params) {
const makeRequestAPISetup = (request) => {
const host = request.headers.get('host');
const proto = request.headers.get('x-forwarded-proto') || 'https';
return {
origin: host ? `${proto}://${host}` : 'null',
// See: https://github.com/vercel/vercel/blob/b189b39/packages/functions/src/get-env.ts#L25C3-L25C13
environment: process.env.VERCEL_ENV ?? process.env.NODE_ENV,
waitUntil: getContext().waitUntil,
};
};
const run = (0, runtime_1.createRequestScope)(STORE, makeRequestAPISetup);
const onRequest = (0, abstract_1.createRequestHandler)((0, node_1.createNodeEnv)(params));
return async (req, res) => {
return respond(res, await run(onRequest, convertRequest(req, res)));
};
}
function convertHeaders(requestHeaders) {
const headers = new Headers();
for (const [key, values] of Object.entries(requestHeaders)) {
if (values) {
if (Array.isArray(values)) {
for (const value of values) {
headers.append(key, value);
}
}
else {
headers.set(key, values);
}
}
}
return headers;
}
function convertRawHeaders(requestHeaders) {
const headers = new Headers();
for (let index = 0; index < requestHeaders.length; index += 2) {
headers.append(requestHeaders[index], requestHeaders[index + 1]);
}
return headers;
}
function convertRequest(req, res) {
const host = req.headers['x-forwarded-host'] || req.headers['host'];
// doesn't seem to be available on their req object!
const protocol = req.headers['x-forwarded-proto'] || 'https';
const url = new URL(`${protocol}://${host}${req.url}`);
// Abort action/loaders once we can no longer write a response
const controller = new AbortController();
res.on('close', () => controller.abort());
const init = {
method: req.method,
headers: convertRawHeaders(req.rawHeaders),
// Cast until reason/throwIfAborted added
// https://github.com/mysticatea/abort-controller/issues/36
signal: controller.signal,
};
if (req.method !== 'GET' && req.method !== 'HEAD') {
// NOTE(@krystofwoldrich) Readable.toWeb breaks the stream in Vercel Functions, unknown why.
// No error is thrown, but reading the stream like `await req.json()` never resolves.
init.body = (0, createReadableStreamFromReadable_1.createReadableStreamFromReadable)(req);
init.duplex = 'half';
}
return new Request(url.href, init);
}
async function respond(res, expoRes) {
res.statusMessage = expoRes.statusText;
res.writeHead(expoRes.status, expoRes.statusText, [...expoRes.headers.entries()].flat());
if (expoRes.body) {
await (0, promises_1.pipeline)(node_stream_1.Readable.fromWeb(expoRes.body), res);
}
else {
res.end();
}
}
//# sourceMappingURL=vercel.js.map
@@ -0,0 +1 @@
{"version":3,"file":"vercel.js","sourceRoot":"","sources":["../../../src/vendor/vercel.ts"],"names":[],"mappings":";;;AAiDA,oDAgBC;AAED,wCAcC;AAUD,wCA0BC;AAED,0BAQC;AA3HD,6CAAuC;AACvC,mDAAgD;AAGhD,yCAAuE;AACvE,wCAAgD;AAChD,6CAAmD;AAEnD,gGAA6F;AAE7F,uCAAuC;A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AAC,GAAG,OAAO,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;IACzF,IAAI,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,MAAM,IAAA,mBAAQ,EAAC,sBAAQ,CAAC,OAAO,CAAC,OAAO,CAAC,IAA0B,CAAC,EAAE,GAAG,CAAC,CAAC;IAC5E,CAAC;SAAM,CAAC;QACN,GAAG,CAAC,GAAG,EAAE,CAAC;IACZ,CAAC;AACH,CAAC"}
+11
View File
@@ -0,0 +1,11 @@
import { type RequestHandlerParams } from './abstract';
import { ExecutionContext } from './environment/workerd';
export { ExpoError } from './abstract';
export type RequestHandler<Env = unknown> = (req: Request, env: Env, ctx: ExecutionContext) => Promise<Response>;
/**
* Returns a request handler for Workerd deployments.
*/
export declare function createRequestHandler<Env = unknown>(params: {
build: string;
environment?: string | null;
}, setup?: RequestHandlerParams): RequestHandler<Env>;
+22
View File
@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExpoError = void 0;
exports.createRequestHandler = createRequestHandler;
const node_async_hooks_1 = require("node:async_hooks");
const abstract_1 = require("./abstract");
const workerd_1 = require("./environment/workerd");
var abstract_2 = require("./abstract");
Object.defineProperty(exports, "ExpoError", { enumerable: true, get: function () { return abstract_2.ExpoError; } });
const STORE = new node_async_hooks_1.AsyncLocalStorage();
/**
* Returns a request handler for Workerd deployments.
*/
function createRequestHandler(params, setup) {
const run = (0, workerd_1.createWorkerdRequestScope)(STORE, params);
const onRequest = (0, abstract_1.createRequestHandler)({
...(0, workerd_1.createWorkerdEnv)(params),
...setup,
});
return (request, env, ctx) => run(onRequest, request, env, ctx);
}
//# sourceMappingURL=workerd.js.map
@@ -0,0 +1 @@
{"version":3,"file":"workerd.js","sourceRoot":"","sources":["../../../src/vendor/workerd.ts"],"names":[],"mappings":";;;AAsBA,oDAUC;AAhCD,uDAAqD;AAErD,yCAAkG;AAClG,mDAI+B;AAE/B,uCAAuC;AAA9B,qGAAA,SAAS,OAAA;AAQlB,MAAM,KAAK,GAAG,IAAI,oCAAiB,EAAE,CAAC;AAEtC;;GAEG;AACH,SAAgB,oBAAoB,CAClC,MAAsD,EACtD,KAA4B;IAE5B,MAAM,GAAG,GAAG,IAAA,mCAAyB,EAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IACrD,MAAM,SAAS,GAAG,IAAA,+BAAiB,EAAC;QAClC,GAAG,IAAA,0BAAgB,EAAC,MAAM,CAAC;QAC3B,GAAG,KAAK;KACT,CAAC,CAAC;IACH,OAAO,CAAC,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,SAAS,EAAE,OAAO,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;AAClE,CAAC"}