@adep/runtime 0.2.6 → 0.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,8 +11,66 @@ export declare const FUNCTION_NAME_RULE = "\u51FD\u6570\u540D\u9700\u4EE5\u5C0F\
11
11
  export declare const MAX_TOTAL_SOURCE_BYTES: number;
12
12
  /** 文件数上限:草稿是 IDE 工作集,不是文件托管。 */
13
13
  export declare const MAX_FILES = 50;
14
- /** 入口文件(FN-002 执行器按此触发)。 */
14
+ /**
15
+ * **目录形态**的入口文件名(FN-002 执行器按此触发)。
16
+ *
17
+ * ⚠️ 不要把它当成"入口恒等于 `index.ts`"的依据:扁平形态(仓库 `functions/<name>.ts`)
18
+ * 的入口就是它自己,文件名随函数名变。入口一律走 `resolveDraftEntry` 解析。
19
+ */
15
20
  export declare const ENTRY_FILE = "index.ts";
21
+ /**
22
+ * 解析一份函数草稿的**入口文件路径**(相对函数根);没有入口返回 null。
23
+ *
24
+ * ## 两种形态(结构规范 §2.3:双形态一等公民)
25
+ *
26
+ * - **目录形态**:草稿含 `index.ts` → 入口就是它,目录内其余文件是该函数私有文件;
27
+ * - **扁平形态**:草稿里有**与函数同名**的根级源码文件(`functions/auth.ts` → 键 `auth.ts`)
28
+ * → 入口就是那个文件,**文件名原样保留**。
29
+ *
30
+ * ## 为什么扁平形态不折算成 `index.ts`(一条被真实项目打出来的结论)
31
+ *
32
+ * 折算的代价不在执行侧(入口是哪个文件本来就能算),而在**结构的保真度**:仓库里是
33
+ * `functions/auth.ts`,平台草稿折算成 `{ 'index.ts' }` 后,Web IDE 只能把它画成
34
+ * `functions/auth/index.ts`——用户看到的是"导入之后凭空多了一层目录",且仓库里删掉
35
+ * 那个文件、平台上那一层结构依然在。草稿键**就是**仓库里的文件名,往返才无损:
36
+ * git 导入(`gitsync/git-client.ts`)、CLI `deploy`、IDE 工作区投影三处按同一份判据对齐。
37
+ *
38
+ * ## 「与函数同名」这条约束不能省
39
+ *
40
+ * 放宽成"根级恰一个源码文件"看似更宽容,实则把**没有入口**的草稿也放行了:
41
+ * `{ 'main.ts' }`(目录形态但入口不叫 `index.ts`)、`{ 'only-lib.ts' }`
42
+ * 都会被当成可执行函数——它们本来是被 `validateDraftFiles` 响亮拒掉的。
43
+ * 入口的合法形状只有两种,判据就必须只认这两种。
44
+ *
45
+ * ⚠️ 别与 `packages/cli/src/sim/invoke.ts::resolveFunctionEntry` 混为一谈:那个吃的是
46
+ * **全量文件表**(键含函数名段,如 `hello.ts` / `hello/index.ts`),回答"某个函数名对应哪个入口";
47
+ * 本函数吃的是**单个函数自己的草稿**(键相对函数根),回答"这份草稿的入口是哪个文件"。
48
+ * 两者键空间不同,所以名字也不同——重名会让"该调哪个"只能靠读实现来猜。
49
+ */
50
+ export declare function resolveDraftEntry(name: string, files: Readonly<Record<string, string>>): string | null;
51
+ /**
52
+ * 取函数草稿的**入口源码**;没有入口返回空串。
53
+ *
54
+ * 给"要读入口源码"的消费方(OpenAPI 推导、MCP 工具 schema 推导)用——它们不该各自
55
+ * 再写一遍 `files['index.ts']`:那正是扁平形态函数在文档面上静默变成空 schema 的原因
56
+ * (不报错、只是没内容,最难被发现的一类失效)。
57
+ */
58
+ export declare function resolveDraftEntrySource(name: string, files: Readonly<Record<string, string>>): string;
59
+ /**
60
+ * 扁平形态的**显示**判据:返回该函数在仓库 / 工作区里的扁平源文件名(`auth.ts`),
61
+ * 不是扁平形态返回 null。
62
+ *
63
+ * 比 `resolveDraftEntry` **更严**,因为它要回答的是另一个问题:不是"跑哪个文件",
64
+ * 而是"**它在树里叫什么**"。工作区路径 `functions/<函数名>.ts` 必须能反推回函数名,
65
+ * 所以判据是「草稿里**只有**这一个源文件(不含 `_shared/**` 物化副本)」——
66
+ * 一旦草稿多了别的文件(如 `package.json`),树里就会出现"同名文件与同名目录并排",
67
+ * 那时退回目录形态画 `functions/<名>/…` 才是自洽的。
68
+ *
69
+ * 消费者:Web IDE 工作区投影(`app/ide/project.ts`,两种形态画成两条路径)、
70
+ * 导出包落盘(`appexport/build/collector.ts` 还原成 `functions/<name>.ts`)与导出 README 的
71
+ * 函数清单。两处产源(gitsync / CLI deploy)按同一形状**产出**草稿,单测里用它反向自检。
72
+ */
73
+ export declare function resolveFlatDraftFile(name: string, files: Readonly<Record<string, string>>): string | null;
16
74
  /** FN_* 域错误:路由层把它转成统一信封响应。 */
17
75
  export declare class FnError extends Error {
18
76
  readonly status: number;
@@ -24,5 +82,10 @@ export interface DraftFile {
24
82
  path: string;
25
83
  content: string;
26
84
  }
27
- /** 校验草稿文件组:路径形态、数量、总量、入口文件存在。 */
28
- export declare function validateDraftFiles(files: Readonly<Record<string, string>>): DraftFile[];
85
+ /** 校验草稿文件组:路径形态、数量、总量、入口文件存在(双形态,见 `resolveDraftEntry`)。
86
+ *
87
+ * 收 `name` 是因为**入口的形状取决于函数名**:扁平形态的入口是与函数同名的那个源文件
88
+ * (`functions/auth.ts`)。少了它就只能退化成"根级恰一个源码文件都算入口",
89
+ * 把 `{ 'main.ts' }` 这类无入口草稿静默放行。
90
+ */
91
+ export declare function validateDraftFiles(name: string, files: Readonly<Record<string, string>>): DraftFile[];
package/dist/index.d.ts CHANGED
@@ -43,3 +43,5 @@ export { resolveFunctionSource, parseSnapshot, resolveExecutableFiles, mergeShar
43
43
  export { StateObjectRuntime, StateObject, StateObjectError, createProjectDriverStateBackend, STATE_OBJECTS_TABLE, DemoCounter, DemoChatRoom, } from './state-objects';
44
44
  export type { StateObjectBackend, StateObjectClass, StateObjectErrorCode, DemoCounterState, DemoChatRoomState, } from './state-objects';
45
45
  export { STATE_PATH, parseStatePath, parseStateBody } from './state-objects/http';
46
+ export { createRouter, stripRoutePrefix } from './route';
47
+ export type { HttpMethod, RouteHandler, RouteMiddleware, RouteRequest, RouteResult, Router, RouterContext, RouterOptions, } from './route';
package/dist/index.js CHANGED
@@ -66,6 +66,18 @@ import { createHash } from "node:crypto";
66
66
 
67
67
  // packages/runtime/src/functions/domain.ts
68
68
  var MAX_TOTAL_SOURCE_BYTES = 256 * 1024;
69
+ var ENTRY_FILE = "index.ts";
70
+ var ENTRY_SOURCE_EXTS = [".ts", ".js", ".mjs", ".cjs"];
71
+ function flatEntryCandidates(name) {
72
+ return ENTRY_SOURCE_EXTS.map((ext) => `${name}${ext}`);
73
+ }
74
+ function resolveDraftEntry(name, files) {
75
+ if (files[ENTRY_FILE] !== void 0) return ENTRY_FILE;
76
+ for (const candidate of flatEntryCandidates(name)) {
77
+ if (files[candidate] !== void 0) return candidate;
78
+ }
79
+ return null;
80
+ }
69
81
  var FnError = class extends Error {
70
82
  status;
71
83
  code;
@@ -219,7 +231,7 @@ var WorkerFunctionExecutor = class {
219
231
  async execute(input) {
220
232
  const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
221
233
  const memoryLimitMb = input.memoryLimitMb ?? DEFAULT_MEMORY_LIMIT_MB;
222
- const entry = input.entry ?? "index.ts";
234
+ const entry = input.entry ?? resolveDraftEntry(input.fn.name, input.files) ?? "index.ts";
223
235
  const deps = this.depsConfig === void 0 ? void 0 : resolveExecutionDeps(this.depsConfig, input.project.id, input.files["package.json"]);
224
236
  const logs = [];
225
237
  return new Promise((resolve2, reject) => {
@@ -3125,6 +3137,152 @@ var DemoChatRoom = class extends StateObject {
3125
3137
  return { seq };
3126
3138
  }
3127
3139
  };
3140
+
3141
+ // packages/runtime/src/route.ts
3142
+ function stripRoutePrefix(path, prefix) {
3143
+ if (prefix.length === 0) return path.length === 0 ? "/" : path;
3144
+ if (path === prefix) return "/";
3145
+ if (path.startsWith(`${prefix}/`)) {
3146
+ const rest = path.slice(prefix.length);
3147
+ return rest.length === 0 ? "/" : rest;
3148
+ }
3149
+ return path;
3150
+ }
3151
+ function splitPath(path) {
3152
+ return path.split("/").filter((segment) => segment.length > 0);
3153
+ }
3154
+ function parseSegment(raw, path) {
3155
+ if (raw.startsWith(":")) {
3156
+ const name = raw.slice(1);
3157
+ if (name.length === 0) throw new Error(`\u8DEF\u7531 ${path} \u7684\u53C2\u6570\u6BB5\u7F3A\u5C11\u540D\u5B57\uFF08\u5199\u4F5C ':'\uFF09`);
3158
+ return { kind: "param", name };
3159
+ }
3160
+ if (raw === "*" || raw.startsWith("*")) {
3161
+ const name = raw.slice(1).length === 0 ? "rest" : raw.slice(1);
3162
+ return { kind: "wildcard", name };
3163
+ }
3164
+ return { kind: "literal", value: raw };
3165
+ }
3166
+ function scoreSegments(segments) {
3167
+ let score = 0;
3168
+ for (const segment of segments) {
3169
+ const weight = segment.kind === "literal" ? 2 : segment.kind === "param" ? 1 : 0;
3170
+ score = score * 3 + weight;
3171
+ }
3172
+ return score;
3173
+ }
3174
+ function matchSegments(pattern, actual) {
3175
+ const params = {};
3176
+ for (let i = 0; i < pattern.length; i += 1) {
3177
+ const segment = pattern[i];
3178
+ if (segment.kind === "wildcard") {
3179
+ params[segment.name] = actual.slice(i).join("/");
3180
+ return params;
3181
+ }
3182
+ const value = actual[i];
3183
+ if (value === void 0) return null;
3184
+ if (segment.kind === "literal") {
3185
+ if (segment.value !== value) return null;
3186
+ } else {
3187
+ params[segment.name] = decodeURIComponent(value);
3188
+ }
3189
+ }
3190
+ return pattern.length === actual.length ? params : null;
3191
+ }
3192
+ function createRouter(options = {}) {
3193
+ const prefix = options.prefix ?? "/api";
3194
+ const entries = [];
3195
+ const middlewares = [];
3196
+ const register = (method, path, handler) => {
3197
+ const normalized = path.startsWith("/") ? path : `/${path}`;
3198
+ const segments = splitPath(normalized).map((segment) => parseSegment(segment, normalized));
3199
+ if (segments.some((segment) => segment.kind === "wildcard")) {
3200
+ const wildcardIndex = segments.findIndex((segment) => segment.kind === "wildcard");
3201
+ if (wildcardIndex !== segments.length - 1) {
3202
+ throw new Error(`\u8DEF\u7531 ${normalized} \u7684\u901A\u914D\u6BB5\u5FC5\u987B\u4F4D\u4E8E\u672B\u5C3E\uFF08\u5F53\u524D\u5728\u7B2C ${wildcardIndex + 1} \u6BB5\uFF09`);
3203
+ }
3204
+ }
3205
+ entries.push({ method, path: normalized, segments, score: scoreSegments(segments), handler });
3206
+ return router;
3207
+ };
3208
+ const router = {
3209
+ get: (path, handler) => register("GET", path, handler),
3210
+ post: (path, handler) => register("POST", path, handler),
3211
+ put: (path, handler) => register("PUT", path, handler),
3212
+ patch: (path, handler) => register("PATCH", path, handler),
3213
+ delete: (path, handler) => register("DELETE", path, handler),
3214
+ head: (path, handler) => register("HEAD", path, handler),
3215
+ options: (path, handler) => register("OPTIONS", path, handler),
3216
+ use(middleware) {
3217
+ middlewares.push(middleware);
3218
+ return router;
3219
+ },
3220
+ routes: () => entries.map((entry) => ({ method: entry.method, path: entry.path })),
3221
+ stripPrefix: (path) => stripRoutePrefix(path, prefix),
3222
+ async handle(context) {
3223
+ const path = stripRoutePrefix(context.path, prefix);
3224
+ const actual = splitPath(path);
3225
+ const query = context.query ?? {};
3226
+ const method = methodOf(context.method);
3227
+ const pathMatches = entries.filter((entry2) => matchSegments(entry2.segments, actual) !== null);
3228
+ const entry = pickBest(pathMatches, method);
3229
+ if (entry === null) {
3230
+ if (pathMatches.length === 0) {
3231
+ return options.onNotFound?.({
3232
+ method,
3233
+ path,
3234
+ params: {},
3235
+ query,
3236
+ raw: context.raw
3237
+ }) ?? { status: 404, body: { error: "NOT_FOUND", path } };
3238
+ }
3239
+ const allowed = [...new Set(pathMatches.map((item) => item.method))].toSorted();
3240
+ return options.onMethodNotAllowed?.(
3241
+ { method, path, params: {}, query, raw: context.raw },
3242
+ allowed
3243
+ ) ?? {
3244
+ status: 405,
3245
+ body: { error: "METHOD_NOT_ALLOWED", allowed },
3246
+ headers: { allow: allowed.join(", ") }
3247
+ };
3248
+ }
3249
+ const params = matchSegments(entry.segments, actual) ?? {};
3250
+ const request = {
3251
+ method,
3252
+ path,
3253
+ params,
3254
+ query,
3255
+ raw: context.raw
3256
+ };
3257
+ for (const middleware of middlewares) {
3258
+ const short = await middleware(request);
3259
+ if (short !== void 0) return normalizeResult(short);
3260
+ }
3261
+ return normalizeResult(await entry.handler(request));
3262
+ }
3263
+ };
3264
+ return router;
3265
+ }
3266
+ function methodOf(raw) {
3267
+ return raw.toUpperCase();
3268
+ }
3269
+ function pickBest(candidates, method) {
3270
+ const forMethod = candidates.filter((entry) => entry.method === method);
3271
+ if (forMethod.length === 0) return null;
3272
+ const sorted = [...forMethod].toSorted(
3273
+ (a, b) => b.score - a.score || b.segments.length - a.segments.length
3274
+ );
3275
+ return sorted[0] ?? null;
3276
+ }
3277
+ function normalizeResult(value) {
3278
+ if (value === void 0 || value === null) return { status: 204 };
3279
+ if (typeof value === "object" && !Array.isArray(value) && ("status" in value || "body" in value || "headers" in value) && Object.keys(value).every(
3280
+ (key) => key === "status" || key === "body" || key === "headers"
3281
+ )) {
3282
+ return value;
3283
+ }
3284
+ return { body: value };
3285
+ }
3128
3286
  export {
3129
3287
  CHAIN_CAPABILITY_KEY,
3130
3288
  DB_RPC,
@@ -3157,6 +3315,7 @@ export {
3157
3315
  createKvCapability,
3158
3316
  createLocalStorageDriver,
3159
3317
  createProjectDriverStateBackend,
3318
+ createRouter,
3160
3319
  createS3StorageDriver,
3161
3320
  createSimRealtimeCapability,
3162
3321
  createStorageCapability,
@@ -3170,6 +3329,7 @@ export {
3170
3329
  resolveFunctionSource,
3171
3330
  sha256,
3172
3331
  signDownloadUrl,
3332
+ stripRoutePrefix,
3173
3333
  verifyDownloadSignature,
3174
3334
  withProjectSharedSource
3175
3335
  };
@@ -0,0 +1,109 @@
1
+ /**
2
+ * 云函数内部的路由助手(`@adep/runtime/route`)。
3
+ *
4
+ * 存在理由:平台一台函数一个入口(`functions/<name>.ts`),一个入口要承载多个端点时,
5
+ * 每个项目都在手写同一套东西——剥 `functions_prefix`、按 `ctx.method` 分支、自己切 `:id`、
6
+ * 自己拼 404。既有应用已经各写了一份(`apps/countdown/functions/_shared/route.ts` 只有剥前缀,
7
+ * `apps/dgc/functions/_shared/route.ts` 同),端点一多就是一张巨型 if/switch。
8
+ * 这里是**同一算法的唯一实现**,回填给所有项目用(先例教训:DB-010 的 `splitSqlStatements`
9
+ * 两份拷贝,改一侧不改另一侧 = 静默分叉)。
10
+ *
11
+ * 设计约束(都来自函数沙箱的实际情况):
12
+ * - **零依赖**:不引 `path-to-regexp` / `express`,也不用 `node:*`——沙箱里都没有;
13
+ * - **框架无关**:不碰 `Request` / `Response`,只吃 `{ method, path, query }` 这类朴素结构,
14
+ * 宿主(平台网关 / `adep dev` / 自定义 HTTP 壳)各自把 ctx 适配进来;
15
+ * - **匹配优先级显式**:字面量 > 参数 > 通配,**与注册顺序无关**。
16
+ * 靠注册顺序决定匹配是最常见的路由 bug,且只在「两个模式都能匹配」时才暴露。
17
+ *
18
+ * ⚠️ 前缀剥离的口径:平台网关与 `adep dev` 传给函数的 `ctx.path` 是**含前缀的完整 pathname**
19
+ * (`/api/events`),本模块默认剥掉 `/api`。前缀可由 `prefix` 覆盖,传 `''` 表示不剥。
20
+ */
21
+ /** 路由收到的请求(宿主适配后的朴素形态)。 */
22
+ export interface RouteRequest<TRaw = unknown> {
23
+ /** HTTP 方法,大小写不敏感(内部统一转大写比较)。 */
24
+ method: string;
25
+ /** **已剥前缀**的路径,如 `/auth/login`。 */
26
+ path: string;
27
+ /** 路径参数。 */
28
+ params: Readonly<Record<string, string>>;
29
+ /** 查询参数(同名多值取最后一个,与多数框架一致)。 */
30
+ query: Readonly<Record<string, string>>;
31
+ /** 宿主原始上下文(各平台形状不同,原样透传,路由不解读)。 */
32
+ raw: TRaw;
33
+ }
34
+ /** 路由处理结果。`undefined` 视为 204。 */
35
+ export interface RouteResult {
36
+ status?: number;
37
+ body?: unknown;
38
+ headers?: Record<string, string>;
39
+ }
40
+ /** 处理函数:返回 `RouteResult`,或直接返回一个值(自动包成 `{ body }`)。 */
41
+ export type RouteHandler<TRaw = unknown> = (request: RouteRequest<TRaw>) => RouteResult | unknown | Promise<RouteResult | unknown>;
42
+ /** 中间件:返回 `RouteResult` 即短路(不再进处理函数);返回 `undefined` 继续。 */
43
+ export type RouteMiddleware<TRaw = unknown> = (request: RouteRequest<TRaw>) => RouteResult | undefined | Promise<RouteResult | undefined>;
44
+ /** 支持的 HTTP 方法。 */
45
+ export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';
46
+ /** 各方法的注册函数签名。 */
47
+ export type MethodRegistrar<TRaw> = (path: string, handler: RouteHandler<TRaw>) => Router<TRaw>;
48
+ /** `createRouter` 选项。 */
49
+ export interface RouterOptions {
50
+ /**
51
+ * 要剥掉的路由前缀。缺省 `'/api'`(与 `adep.config.ts` 的 `functions_prefix` 默认值一致)。
52
+ * 传空串表示不剥。
53
+ */
54
+ prefix?: string;
55
+ /** 未命中任何路由时的响应;缺省 404 + `{ error: 'NOT_FOUND' }`。 */
56
+ onNotFound?: (request: RouteRequest) => RouteResult;
57
+ /** 路径命中但方法不匹配时的响应;缺省 405 + `Allow` 头 + `{ error: 'METHOD_NOT_ALLOWED' }`。 */
58
+ onMethodNotAllowed?: (request: RouteRequest, allowed: readonly HttpMethod[]) => RouteResult;
59
+ }
60
+ /** 路由器。 */
61
+ export interface Router<TRaw = unknown> {
62
+ get: MethodRegistrar<TRaw>;
63
+ post: MethodRegistrar<TRaw>;
64
+ put: MethodRegistrar<TRaw>;
65
+ patch: MethodRegistrar<TRaw>;
66
+ delete: MethodRegistrar<TRaw>;
67
+ head: MethodRegistrar<TRaw>;
68
+ options: MethodRegistrar<TRaw>;
69
+ /** 注册中间件(按注册顺序执行)。 */
70
+ use: (middleware: RouteMiddleware<TRaw>) => Router<TRaw>;
71
+ /** 已注册的路由(只读,诊断用)。 */
72
+ routes: () => ReadonlyArray<{
73
+ method: HttpMethod;
74
+ path: string;
75
+ }>;
76
+ /** 剥前缀(导出以便宿主在别处复用同一口径)。 */
77
+ stripPrefix: (path: string) => string;
78
+ /** 派发。 */
79
+ handle: (context: RouterContext<TRaw>) => Promise<RouteResult>;
80
+ }
81
+ /** `handle` 的入参:宿主能提供的最小集合。 */
82
+ export interface RouterContext<TRaw = unknown> {
83
+ method: string;
84
+ path: string;
85
+ query?: Record<string, string> | undefined;
86
+ raw?: TRaw;
87
+ }
88
+ /**
89
+ * 剥掉前缀。
90
+ *
91
+ * 三个边界都是实测来的:
92
+ * - `/api` 本身 → `/`(不然会得到一个空串,路由表里没人匹配得上);
93
+ * - `/api/` → `/`;
94
+ * - `/apix` **不能**被剥成 `x`(必须要求前缀后紧跟 `/` 或结束)——朴素 `startsWith` 会把它吃掉。
95
+ */
96
+ export declare function stripRoutePrefix(path: string, prefix: string): string;
97
+ /**
98
+ * 创建路由器。
99
+ *
100
+ * ```ts
101
+ * const router = createRouter()
102
+ * .get('/events', () => listEvents())
103
+ * .get('/events/:id', (req) => getEvent(req.params.id!))
104
+ * .post('/events', (req) => createEvent(req.body))
105
+ *
106
+ * export default (ctx) => router.handle(ctx)
107
+ * ```
108
+ */
109
+ export declare function createRouter<TRaw = unknown>(options?: RouterOptions): Router<TRaw>;
package/dist/route.js ADDED
@@ -0,0 +1,149 @@
1
+ // packages/runtime/src/route.ts
2
+ function stripRoutePrefix(path, prefix) {
3
+ if (prefix.length === 0) return path.length === 0 ? "/" : path;
4
+ if (path === prefix) return "/";
5
+ if (path.startsWith(`${prefix}/`)) {
6
+ const rest = path.slice(prefix.length);
7
+ return rest.length === 0 ? "/" : rest;
8
+ }
9
+ return path;
10
+ }
11
+ function splitPath(path) {
12
+ return path.split("/").filter((segment) => segment.length > 0);
13
+ }
14
+ function parseSegment(raw, path) {
15
+ if (raw.startsWith(":")) {
16
+ const name = raw.slice(1);
17
+ if (name.length === 0) throw new Error(`\u8DEF\u7531 ${path} \u7684\u53C2\u6570\u6BB5\u7F3A\u5C11\u540D\u5B57\uFF08\u5199\u4F5C ':'\uFF09`);
18
+ return { kind: "param", name };
19
+ }
20
+ if (raw === "*" || raw.startsWith("*")) {
21
+ const name = raw.slice(1).length === 0 ? "rest" : raw.slice(1);
22
+ return { kind: "wildcard", name };
23
+ }
24
+ return { kind: "literal", value: raw };
25
+ }
26
+ function scoreSegments(segments) {
27
+ let score = 0;
28
+ for (const segment of segments) {
29
+ const weight = segment.kind === "literal" ? 2 : segment.kind === "param" ? 1 : 0;
30
+ score = score * 3 + weight;
31
+ }
32
+ return score;
33
+ }
34
+ function matchSegments(pattern, actual) {
35
+ const params = {};
36
+ for (let i = 0; i < pattern.length; i += 1) {
37
+ const segment = pattern[i];
38
+ if (segment.kind === "wildcard") {
39
+ params[segment.name] = actual.slice(i).join("/");
40
+ return params;
41
+ }
42
+ const value = actual[i];
43
+ if (value === void 0) return null;
44
+ if (segment.kind === "literal") {
45
+ if (segment.value !== value) return null;
46
+ } else {
47
+ params[segment.name] = decodeURIComponent(value);
48
+ }
49
+ }
50
+ return pattern.length === actual.length ? params : null;
51
+ }
52
+ function createRouter(options = {}) {
53
+ const prefix = options.prefix ?? "/api";
54
+ const entries = [];
55
+ const middlewares = [];
56
+ const register = (method, path, handler) => {
57
+ const normalized = path.startsWith("/") ? path : `/${path}`;
58
+ const segments = splitPath(normalized).map((segment) => parseSegment(segment, normalized));
59
+ if (segments.some((segment) => segment.kind === "wildcard")) {
60
+ const wildcardIndex = segments.findIndex((segment) => segment.kind === "wildcard");
61
+ if (wildcardIndex !== segments.length - 1) {
62
+ throw new Error(`\u8DEF\u7531 ${normalized} \u7684\u901A\u914D\u6BB5\u5FC5\u987B\u4F4D\u4E8E\u672B\u5C3E\uFF08\u5F53\u524D\u5728\u7B2C ${wildcardIndex + 1} \u6BB5\uFF09`);
63
+ }
64
+ }
65
+ entries.push({ method, path: normalized, segments, score: scoreSegments(segments), handler });
66
+ return router;
67
+ };
68
+ const router = {
69
+ get: (path, handler) => register("GET", path, handler),
70
+ post: (path, handler) => register("POST", path, handler),
71
+ put: (path, handler) => register("PUT", path, handler),
72
+ patch: (path, handler) => register("PATCH", path, handler),
73
+ delete: (path, handler) => register("DELETE", path, handler),
74
+ head: (path, handler) => register("HEAD", path, handler),
75
+ options: (path, handler) => register("OPTIONS", path, handler),
76
+ use(middleware) {
77
+ middlewares.push(middleware);
78
+ return router;
79
+ },
80
+ routes: () => entries.map((entry) => ({ method: entry.method, path: entry.path })),
81
+ stripPrefix: (path) => stripRoutePrefix(path, prefix),
82
+ async handle(context) {
83
+ const path = stripRoutePrefix(context.path, prefix);
84
+ const actual = splitPath(path);
85
+ const query = context.query ?? {};
86
+ const method = methodOf(context.method);
87
+ const pathMatches = entries.filter((entry2) => matchSegments(entry2.segments, actual) !== null);
88
+ const entry = pickBest(pathMatches, method);
89
+ if (entry === null) {
90
+ if (pathMatches.length === 0) {
91
+ return options.onNotFound?.({
92
+ method,
93
+ path,
94
+ params: {},
95
+ query,
96
+ raw: context.raw
97
+ }) ?? { status: 404, body: { error: "NOT_FOUND", path } };
98
+ }
99
+ const allowed = [...new Set(pathMatches.map((item) => item.method))].toSorted();
100
+ return options.onMethodNotAllowed?.(
101
+ { method, path, params: {}, query, raw: context.raw },
102
+ allowed
103
+ ) ?? {
104
+ status: 405,
105
+ body: { error: "METHOD_NOT_ALLOWED", allowed },
106
+ headers: { allow: allowed.join(", ") }
107
+ };
108
+ }
109
+ const params = matchSegments(entry.segments, actual) ?? {};
110
+ const request = {
111
+ method,
112
+ path,
113
+ params,
114
+ query,
115
+ raw: context.raw
116
+ };
117
+ for (const middleware of middlewares) {
118
+ const short = await middleware(request);
119
+ if (short !== void 0) return normalizeResult(short);
120
+ }
121
+ return normalizeResult(await entry.handler(request));
122
+ }
123
+ };
124
+ return router;
125
+ }
126
+ function methodOf(raw) {
127
+ return raw.toUpperCase();
128
+ }
129
+ function pickBest(candidates, method) {
130
+ const forMethod = candidates.filter((entry) => entry.method === method);
131
+ if (forMethod.length === 0) return null;
132
+ const sorted = [...forMethod].toSorted(
133
+ (a, b) => b.score - a.score || b.segments.length - a.segments.length
134
+ );
135
+ return sorted[0] ?? null;
136
+ }
137
+ function normalizeResult(value) {
138
+ if (value === void 0 || value === null) return { status: 204 };
139
+ if (typeof value === "object" && !Array.isArray(value) && ("status" in value || "body" in value || "headers" in value) && Object.keys(value).every(
140
+ (key) => key === "status" || key === "body" || key === "headers"
141
+ )) {
142
+ return value;
143
+ }
144
+ return { body: value };
145
+ }
146
+ export {
147
+ createRouter,
148
+ stripRoutePrefix
149
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adep/runtime",
3
- "version": "0.2.6",
3
+ "version": "0.2.7",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "sideEffects": false,