@sleepy-hollow/framework 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -0
- package/LICENSE +373 -0
- package/README.md +95 -0
- package/dist/chunk-53TZY5YP.js +470 -0
- package/dist/chunk-53TZY5YP.js.map +1 -0
- package/dist/chunk-5WRI5ZAA.js +31 -0
- package/dist/chunk-5WRI5ZAA.js.map +1 -0
- package/dist/chunk-BAKXP7IR.js +85 -0
- package/dist/chunk-BAKXP7IR.js.map +1 -0
- package/dist/chunk-BJONRVDG.js +429 -0
- package/dist/chunk-BJONRVDG.js.map +1 -0
- package/dist/chunk-CAPFDC25.js +598 -0
- package/dist/chunk-CAPFDC25.js.map +1 -0
- package/dist/chunk-D4U3ZY4O.js +4585 -0
- package/dist/chunk-D4U3ZY4O.js.map +1 -0
- package/dist/chunk-DGTHFZPZ.js +830 -0
- package/dist/chunk-DGTHFZPZ.js.map +1 -0
- package/dist/chunk-LNJDFJGT.js +47 -0
- package/dist/chunk-LNJDFJGT.js.map +1 -0
- package/dist/cli.d.ts +427 -0
- package/dist/cli.js +5910 -0
- package/dist/cli.js.map +1 -0
- package/dist/database.d.ts +25 -0
- package/dist/database.js +16 -0
- package/dist/database.js.map +1 -0
- package/dist/dist-DUSC2237.js +546 -0
- package/dist/dist-DUSC2237.js.map +1 -0
- package/dist/index.d.ts +241 -0
- package/dist/index.js +71 -0
- package/dist/index.js.map +1 -0
- package/dist/magic-string.es-GTFBNHZR.js +1309 -0
- package/dist/magic-string.es-GTFBNHZR.js.map +1 -0
- package/dist/routing.d.ts +89 -0
- package/dist/routing.js +17 -0
- package/dist/routing.js.map +1 -0
- package/dist/security.d.ts +319 -0
- package/dist/security.js +21 -0
- package/dist/security.js.map +1 -0
- package/dist/server.d.ts +10 -0
- package/dist/server.js +8 -0
- package/dist/server.js.map +1 -0
- package/dist/testing.d.ts +157 -0
- package/dist/testing.js +29 -0
- package/dist/testing.js.map +1 -0
- package/dist/types-BC7LJJ6G.d.ts +131 -0
- package/dist/types-BUXw3UwN.d.ts +54 -0
- package/dist/types-Bet36nZS.d.ts +390 -0
- package/dist/types-DmzdxsaA.d.ts +113 -0
- package/dist/validation.d.ts +57 -0
- package/dist/validation.js +20 -0
- package/dist/validation.js.map +1 -0
- package/package.json +84 -0
|
@@ -0,0 +1,470 @@
|
|
|
1
|
+
import {
|
|
2
|
+
serve
|
|
3
|
+
} from "./chunk-LNJDFJGT.js";
|
|
4
|
+
|
|
5
|
+
// core/routing/define_route.ts
|
|
6
|
+
function defineRoute(route) {
|
|
7
|
+
return route;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
// runtime/platform.ts
|
|
11
|
+
import { spawn as spawnChild } from "child_process";
|
|
12
|
+
import {
|
|
13
|
+
copyFile,
|
|
14
|
+
lstat,
|
|
15
|
+
mkdir,
|
|
16
|
+
mkdtemp,
|
|
17
|
+
readFile,
|
|
18
|
+
readdir,
|
|
19
|
+
realpath,
|
|
20
|
+
rename,
|
|
21
|
+
rm,
|
|
22
|
+
stat,
|
|
23
|
+
writeFile
|
|
24
|
+
} from "fs/promises";
|
|
25
|
+
import { readdirSync, watch } from "fs";
|
|
26
|
+
import { symlink } from "fs/promises";
|
|
27
|
+
import { Readable } from "stream";
|
|
28
|
+
import { tmpdir } from "os";
|
|
29
|
+
import { join } from "path";
|
|
30
|
+
var NotFound = class extends Error {
|
|
31
|
+
constructor(path) {
|
|
32
|
+
super(path ? `Not found: ${path}` : "Not found");
|
|
33
|
+
this.name = "NotFound";
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
function normalizeFilesystemError(error, path) {
|
|
37
|
+
if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") {
|
|
38
|
+
throw new NotFound(path);
|
|
39
|
+
}
|
|
40
|
+
throw error;
|
|
41
|
+
}
|
|
42
|
+
async function filesystem(operation, path) {
|
|
43
|
+
try {
|
|
44
|
+
return await operation;
|
|
45
|
+
} catch (error) {
|
|
46
|
+
return normalizeFilesystemError(error, path);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
var Command = class {
|
|
50
|
+
#command;
|
|
51
|
+
#options;
|
|
52
|
+
constructor(command, options = {}) {
|
|
53
|
+
this.#command = command;
|
|
54
|
+
this.#options = options;
|
|
55
|
+
}
|
|
56
|
+
async output() {
|
|
57
|
+
const child = spawnChild(this.#command, this.#options.args ?? [], {
|
|
58
|
+
cwd: this.#options.cwd,
|
|
59
|
+
env: this.#options.clearEnv ? this.#options.env : { ...process.env, ...this.#options.env },
|
|
60
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
61
|
+
});
|
|
62
|
+
const stdout = [];
|
|
63
|
+
const stderr = [];
|
|
64
|
+
child.stdout.on("data", (chunk) => stdout.push(chunk));
|
|
65
|
+
child.stderr.on("data", (chunk) => stderr.push(chunk));
|
|
66
|
+
const code = await new Promise((resolve2, reject) => {
|
|
67
|
+
child.once("error", reject);
|
|
68
|
+
child.once("close", (status) => resolve2(status ?? 1));
|
|
69
|
+
});
|
|
70
|
+
return { code, success: code === 0, stdout: Buffer.concat(stdout), stderr: Buffer.concat(stderr) };
|
|
71
|
+
}
|
|
72
|
+
spawn() {
|
|
73
|
+
const child = spawnChild(this.#command, this.#options.args ?? [], {
|
|
74
|
+
cwd: this.#options.cwd,
|
|
75
|
+
env: this.#options.clearEnv ? this.#options.env : { ...process.env, ...this.#options.env },
|
|
76
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
77
|
+
});
|
|
78
|
+
return {
|
|
79
|
+
stdout: Readable.toWeb(child.stdout),
|
|
80
|
+
stderr: Readable.toWeb(child.stderr),
|
|
81
|
+
status: new Promise((resolve2, reject) => {
|
|
82
|
+
child.once("error", reject);
|
|
83
|
+
child.once("close", (code) => {
|
|
84
|
+
const resolved = code ?? 1;
|
|
85
|
+
resolve2({ code: resolved, success: resolved === 0 });
|
|
86
|
+
});
|
|
87
|
+
}),
|
|
88
|
+
kill: (signal) => child.kill(signal)
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
var Watcher = class {
|
|
93
|
+
#watcher;
|
|
94
|
+
#closed = false;
|
|
95
|
+
#pending = [];
|
|
96
|
+
#resolve;
|
|
97
|
+
#reject;
|
|
98
|
+
#failure;
|
|
99
|
+
constructor(root) {
|
|
100
|
+
this.#watcher = watch(root, { recursive: true }, (_event, filename) => {
|
|
101
|
+
const event = { paths: [join(root, String(filename ?? ""))] };
|
|
102
|
+
if (this.#resolve) {
|
|
103
|
+
this.#resolve({ done: false, value: event });
|
|
104
|
+
this.#resolve = void 0;
|
|
105
|
+
} else this.#pending.push(event);
|
|
106
|
+
});
|
|
107
|
+
this.#watcher.on("error", (error) => {
|
|
108
|
+
if (this.#closed) return;
|
|
109
|
+
this.#failure = error;
|
|
110
|
+
this.#closed = true;
|
|
111
|
+
this.#reject?.(error);
|
|
112
|
+
this.#resolve = void 0;
|
|
113
|
+
this.#reject = void 0;
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
close() {
|
|
117
|
+
this.#closed = true;
|
|
118
|
+
this.#watcher.close();
|
|
119
|
+
this.#resolve?.({ done: true, value: void 0 });
|
|
120
|
+
this.#resolve = void 0;
|
|
121
|
+
this.#reject = void 0;
|
|
122
|
+
}
|
|
123
|
+
[Symbol.asyncIterator]() {
|
|
124
|
+
return {
|
|
125
|
+
next: () => {
|
|
126
|
+
const value = this.#pending.shift();
|
|
127
|
+
if (value) return Promise.resolve({ done: false, value });
|
|
128
|
+
if (this.#failure) return Promise.reject(this.#failure);
|
|
129
|
+
if (this.#closed) return Promise.resolve({ done: true, value: void 0 });
|
|
130
|
+
return new Promise((resolve2, reject) => {
|
|
131
|
+
this.#resolve = resolve2;
|
|
132
|
+
this.#reject = reject;
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
var platform = Object.freeze({
|
|
139
|
+
args: process.argv.slice(2),
|
|
140
|
+
cwd: () => process.cwd(),
|
|
141
|
+
exit: (code) => process.exit(code),
|
|
142
|
+
execPath: () => process.execPath,
|
|
143
|
+
env: Object.freeze({
|
|
144
|
+
get: (name) => process.env[name],
|
|
145
|
+
toObject: () => ({ ...process.env })
|
|
146
|
+
}),
|
|
147
|
+
errors: Object.freeze({
|
|
148
|
+
NotFound,
|
|
149
|
+
AddrInUse: class AddrInUse extends Error {
|
|
150
|
+
},
|
|
151
|
+
PermissionDenied: class PermissionDenied extends Error {
|
|
152
|
+
}
|
|
153
|
+
}),
|
|
154
|
+
isNotFound: (error) => error instanceof NotFound || typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT",
|
|
155
|
+
readTextFile: async (path) => filesystem(readFile(path, "utf8"), path),
|
|
156
|
+
readFile: async (path) => filesystem(readFile(path), path),
|
|
157
|
+
writeTextFile: async (path, text, options) => writeFile(path, text, options?.createNew ? { flag: "wx" } : void 0),
|
|
158
|
+
stat: (path) => filesystem(stat(path), path),
|
|
159
|
+
lstat: (path) => filesystem(lstat(path), path),
|
|
160
|
+
mkdir,
|
|
161
|
+
rename,
|
|
162
|
+
remove: (path, options) => rm(path, { recursive: options?.recursive, force: true }),
|
|
163
|
+
realPath: (path) => filesystem(realpath(path), path),
|
|
164
|
+
copyFile: (source, target) => filesystem(copyFile(source, target), source),
|
|
165
|
+
symlink: (target, path) => filesystem(symlink(target, path), path),
|
|
166
|
+
readDirSync: (path) => readdirSync(path, { withFileTypes: true }).map((entry) => ({ name: entry.name, isFile: entry.isFile(), isDirectory: entry.isDirectory(), isSymlink: entry.isSymbolicLink() })),
|
|
167
|
+
makeTempDir: async (options) => mkdtemp(join(options?.dir ?? tmpdir(), options?.prefix ?? "sleepy-hollow-")),
|
|
168
|
+
async *readDir(path) {
|
|
169
|
+
for (const entry of await readdir(path, { withFileTypes: true })) {
|
|
170
|
+
yield { name: entry.name, isFile: entry.isFile(), isDirectory: entry.isDirectory(), isSymlink: entry.isSymbolicLink() };
|
|
171
|
+
}
|
|
172
|
+
},
|
|
173
|
+
watchFs: (root, _options) => new Watcher(root),
|
|
174
|
+
addSignalListener: (signal, listener) => process.on(signal, listener),
|
|
175
|
+
removeSignalListener: (signal, listener) => process.off(signal, listener),
|
|
176
|
+
serve: (options, handler) => serve(handler, options),
|
|
177
|
+
Command
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
// core/routing/discover.ts
|
|
181
|
+
import { dirname, relative, resolve, sep } from "path";
|
|
182
|
+
import { fileURLToPath, pathToFileURL } from "url";
|
|
183
|
+
|
|
184
|
+
// core/routing/types.ts
|
|
185
|
+
var HTTP_METHODS = [
|
|
186
|
+
"DELETE",
|
|
187
|
+
"GET",
|
|
188
|
+
"HEAD",
|
|
189
|
+
"OPTIONS",
|
|
190
|
+
"PATCH",
|
|
191
|
+
"POST",
|
|
192
|
+
"PUT"
|
|
193
|
+
];
|
|
194
|
+
var RouteDiscoveryError = class extends Error {
|
|
195
|
+
/**
|
|
196
|
+
* Builds an error whose message lists every diagnostic, one per line.
|
|
197
|
+
*
|
|
198
|
+
* @param diagnostics Every fault discovery found, in the order detected.
|
|
199
|
+
*/
|
|
200
|
+
constructor(diagnostics) {
|
|
201
|
+
super(
|
|
202
|
+
diagnostics.map(
|
|
203
|
+
(diagnostic) => `${diagnostic.code}: ${diagnostic.summary}`
|
|
204
|
+
).join("\n")
|
|
205
|
+
);
|
|
206
|
+
this.diagnostics = diagnostics;
|
|
207
|
+
this.name = "RouteDiscoveryError";
|
|
208
|
+
}
|
|
209
|
+
diagnostics;
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
// core/routing/discover.ts
|
|
213
|
+
var dynamicSegment = /^\[([^\]]+)\]$/;
|
|
214
|
+
var parameterName = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
215
|
+
var methods = new Set(HTTP_METHODS);
|
|
216
|
+
var portablePath = (path) => path.split(sep).join("/");
|
|
217
|
+
async function collectRouteFiles(directory) {
|
|
218
|
+
const files = [];
|
|
219
|
+
const entries = [];
|
|
220
|
+
for await (const entry of platform.readDir(directory)) entries.push(entry);
|
|
221
|
+
entries.sort((left, right) => left.name.localeCompare(right.name));
|
|
222
|
+
for (const entry of entries) {
|
|
223
|
+
const path = resolve(directory, entry.name);
|
|
224
|
+
if (entry.isDirectory) files.push(...await collectRouteFiles(path));
|
|
225
|
+
if (entry.isFile && entry.name === "route.ts") files.push(path);
|
|
226
|
+
}
|
|
227
|
+
return files;
|
|
228
|
+
}
|
|
229
|
+
function normalizeRouteFile(apiRoot, path) {
|
|
230
|
+
const segments = portablePath(relative(apiRoot, dirname(path))).split("/").filter(Boolean);
|
|
231
|
+
const routeSegments = [];
|
|
232
|
+
const conflictSegments = [];
|
|
233
|
+
const parameterNames = [];
|
|
234
|
+
for (const segment of segments) {
|
|
235
|
+
const match = segment.match(dynamicSegment);
|
|
236
|
+
if (!match) {
|
|
237
|
+
if (segment.includes("[") || segment.includes("]")) {
|
|
238
|
+
return invalidSegment(path, segment);
|
|
239
|
+
}
|
|
240
|
+
routeSegments.push(segment);
|
|
241
|
+
conflictSegments.push(segment);
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
const name = match[1];
|
|
245
|
+
if (!parameterName.test(name)) return invalidSegment(path, segment);
|
|
246
|
+
if (parameterNames.includes(name)) {
|
|
247
|
+
return {
|
|
248
|
+
code: "SH_ROUTE_INVALID_SEGMENT",
|
|
249
|
+
summary: `Dynamic parameter '${name}' is repeated in one route`,
|
|
250
|
+
files: [portablePath(path)],
|
|
251
|
+
correction: "Use a unique parameter name for every dynamic segment."
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
parameterNames.push(name);
|
|
255
|
+
routeSegments.push(`:${name}`);
|
|
256
|
+
conflictSegments.push(":parameter");
|
|
257
|
+
}
|
|
258
|
+
return {
|
|
259
|
+
path: portablePath(path),
|
|
260
|
+
segments,
|
|
261
|
+
routePath: `/${routeSegments.join("/")}`,
|
|
262
|
+
conflictPath: `/${conflictSegments.join("/")}`,
|
|
263
|
+
parameterNames
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
function invalidSegment(path, segment) {
|
|
267
|
+
return {
|
|
268
|
+
code: "SH_ROUTE_INVALID_SEGMENT",
|
|
269
|
+
summary: `Invalid dynamic route segment '${segment}'`,
|
|
270
|
+
files: [portablePath(path)],
|
|
271
|
+
correction: "Use [name] with a TypeScript identifier as the parameter name."
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
function validateModule(value, file) {
|
|
275
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
276
|
+
return invalidModule(
|
|
277
|
+
file.path,
|
|
278
|
+
"The default export must be created with defineRoute"
|
|
279
|
+
);
|
|
280
|
+
}
|
|
281
|
+
const entries = Object.entries(value);
|
|
282
|
+
if (entries.length === 0) {
|
|
283
|
+
return invalidModule(
|
|
284
|
+
file.path,
|
|
285
|
+
"The route must declare at least one HTTP method"
|
|
286
|
+
);
|
|
287
|
+
}
|
|
288
|
+
for (const [method, operation] of entries) {
|
|
289
|
+
if (!methods.has(method)) {
|
|
290
|
+
return invalidModule(file.path, `Unsupported HTTP method '${method}'`);
|
|
291
|
+
}
|
|
292
|
+
if (!isOperation(operation)) {
|
|
293
|
+
return invalidModule(
|
|
294
|
+
file.path,
|
|
295
|
+
`${method} must declare schemas, security, contract, and a handler`
|
|
296
|
+
);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
return value;
|
|
300
|
+
}
|
|
301
|
+
function isOperation(value) {
|
|
302
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
303
|
+
const operation = value;
|
|
304
|
+
return Object.hasOwn(operation, "schemas") && Object.hasOwn(operation, "security") && Object.hasOwn(operation, "contract") && typeof operation.handler === "function";
|
|
305
|
+
}
|
|
306
|
+
function invalidModule(path, summary) {
|
|
307
|
+
return {
|
|
308
|
+
code: "SH_ROUTE_INVALID_MODULE",
|
|
309
|
+
summary,
|
|
310
|
+
files: [portablePath(path)],
|
|
311
|
+
correction: "Default-export one defineRoute method map with complete operations."
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
function findConflicts(files) {
|
|
315
|
+
const groups = Map.groupBy(files, (file) => file.conflictPath);
|
|
316
|
+
const diagnostics = [];
|
|
317
|
+
for (const [route, group] of groups) {
|
|
318
|
+
if (group.length < 2) continue;
|
|
319
|
+
diagnostics.push({
|
|
320
|
+
code: "SH_ROUTE_CONFLICT",
|
|
321
|
+
summary: `Ambiguous route definitions normalize to '${route}'`,
|
|
322
|
+
files: group.map((file) => file.path).sort(),
|
|
323
|
+
route,
|
|
324
|
+
correction: "Keep only one dynamic sibling at each route depth."
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
return diagnostics.sort(
|
|
328
|
+
(left, right) => (left.route ?? "").localeCompare(right.route ?? "")
|
|
329
|
+
);
|
|
330
|
+
}
|
|
331
|
+
async function discoverRoutes(apiRoot) {
|
|
332
|
+
const root = resolve(
|
|
333
|
+
apiRoot instanceof URL ? fileURLToPath(apiRoot) : apiRoot
|
|
334
|
+
);
|
|
335
|
+
const diagnostics = [];
|
|
336
|
+
const routeFiles = [];
|
|
337
|
+
for (const path of await collectRouteFiles(root)) {
|
|
338
|
+
const normalized = normalizeRouteFile(root, path);
|
|
339
|
+
if ("code" in normalized) diagnostics.push(normalized);
|
|
340
|
+
else routeFiles.push(normalized);
|
|
341
|
+
}
|
|
342
|
+
diagnostics.push(...findConflicts(routeFiles));
|
|
343
|
+
const routes = [];
|
|
344
|
+
for (const file of routeFiles) {
|
|
345
|
+
try {
|
|
346
|
+
const imported = await import(pathToFileURL(file.path).href);
|
|
347
|
+
const routeModule = validateModule(imported.default, file);
|
|
348
|
+
if ("code" in routeModule) {
|
|
349
|
+
diagnostics.push(routeModule);
|
|
350
|
+
continue;
|
|
351
|
+
}
|
|
352
|
+
for (const [method, operation] of Object.entries(routeModule)) {
|
|
353
|
+
routes.push({
|
|
354
|
+
method,
|
|
355
|
+
path: file.routePath,
|
|
356
|
+
source: file.path,
|
|
357
|
+
parameterNames: file.parameterNames,
|
|
358
|
+
operation
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
} catch (error) {
|
|
362
|
+
diagnostics.push(invalidModule(
|
|
363
|
+
file.path,
|
|
364
|
+
`Route module could not be loaded: ${error instanceof Error ? error.message : String(error)}`
|
|
365
|
+
));
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
if (diagnostics.length > 0) {
|
|
369
|
+
diagnostics.sort(
|
|
370
|
+
(left, right) => `${left.code}:${left.files.join(":")}`.localeCompare(
|
|
371
|
+
`${right.code}:${right.files.join(":")}`
|
|
372
|
+
)
|
|
373
|
+
);
|
|
374
|
+
throw new RouteDiscoveryError(diagnostics);
|
|
375
|
+
}
|
|
376
|
+
return routes.sort(
|
|
377
|
+
(left, right) => left.path.localeCompare(right.path) || left.method.localeCompare(right.method)
|
|
378
|
+
);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
// core/routing/router.ts
|
|
382
|
+
function splitPath(path) {
|
|
383
|
+
try {
|
|
384
|
+
return path.split("/").filter(Boolean).map(decodeURIComponent);
|
|
385
|
+
} catch {
|
|
386
|
+
return void 0;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
function matchRoute(route, requestSegments) {
|
|
390
|
+
const routeSegments = route.path.split("/").filter(Boolean);
|
|
391
|
+
if (routeSegments.length !== requestSegments.length) return void 0;
|
|
392
|
+
const params = {};
|
|
393
|
+
for (let index = 0; index < routeSegments.length; index += 1) {
|
|
394
|
+
const expected = routeSegments[index];
|
|
395
|
+
const actual = requestSegments[index];
|
|
396
|
+
if (expected.startsWith(":")) params[expected.slice(1)] = actual;
|
|
397
|
+
else if (expected !== actual) return void 0;
|
|
398
|
+
}
|
|
399
|
+
return { route, params };
|
|
400
|
+
}
|
|
401
|
+
function compareSpecificity(left, right) {
|
|
402
|
+
const leftSegments = left.route.path.split("/").filter(Boolean);
|
|
403
|
+
const rightSegments = right.route.path.split("/").filter(Boolean);
|
|
404
|
+
for (let index = 0; index < leftSegments.length; index += 1) {
|
|
405
|
+
const leftDynamic = leftSegments[index].startsWith(":");
|
|
406
|
+
const rightDynamic = rightSegments[index].startsWith(":");
|
|
407
|
+
if (leftDynamic !== rightDynamic) return leftDynamic ? 1 : -1;
|
|
408
|
+
}
|
|
409
|
+
return left.route.path.localeCompare(right.route.path);
|
|
410
|
+
}
|
|
411
|
+
function problem(status, title, instance, headers) {
|
|
412
|
+
return new Response(
|
|
413
|
+
JSON.stringify({ type: "about:blank", title, status, instance }),
|
|
414
|
+
{
|
|
415
|
+
status,
|
|
416
|
+
headers: {
|
|
417
|
+
"content-type": "application/problem+json",
|
|
418
|
+
...headers
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
);
|
|
422
|
+
}
|
|
423
|
+
function createRouter(routes) {
|
|
424
|
+
const inventory = [...routes];
|
|
425
|
+
return {
|
|
426
|
+
async fetch(request) {
|
|
427
|
+
const url = new URL(request.url);
|
|
428
|
+
const requestSegments = splitPath(url.pathname);
|
|
429
|
+
if (!requestSegments) return problem(404, "Not Found", url.pathname);
|
|
430
|
+
const matches = inventory.map((route) => matchRoute(route, requestSegments)).filter((match) => match !== void 0).sort(compareSpecificity);
|
|
431
|
+
if (matches.length === 0) return problem(404, "Not Found", url.pathname);
|
|
432
|
+
const selectedPath = matches[0].route.path;
|
|
433
|
+
const pathMatches = matches.filter(
|
|
434
|
+
(match) => match.route.path === selectedPath
|
|
435
|
+
);
|
|
436
|
+
const method = request.method.toUpperCase();
|
|
437
|
+
const selected = pathMatches.find(
|
|
438
|
+
(match) => match.route.method === method
|
|
439
|
+
);
|
|
440
|
+
if (!selected) {
|
|
441
|
+
const allowed = [
|
|
442
|
+
...new Set(pathMatches.map((match) => match.route.method))
|
|
443
|
+
].sort();
|
|
444
|
+
return problem(405, "Method Not Allowed", url.pathname, {
|
|
445
|
+
allow: allowed.join(", ")
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
return await selected.route.operation.handler({
|
|
449
|
+
request,
|
|
450
|
+
params: selected.params,
|
|
451
|
+
query: Object.freeze({}),
|
|
452
|
+
headers: Object.freeze({}),
|
|
453
|
+
body: void 0,
|
|
454
|
+
signal: request.signal,
|
|
455
|
+
principal: null,
|
|
456
|
+
requestId: ""
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
export {
|
|
463
|
+
defineRoute,
|
|
464
|
+
platform,
|
|
465
|
+
HTTP_METHODS,
|
|
466
|
+
RouteDiscoveryError,
|
|
467
|
+
discoverRoutes,
|
|
468
|
+
createRouter
|
|
469
|
+
};
|
|
470
|
+
//# sourceMappingURL=chunk-53TZY5YP.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../core/routing/define_route.ts","../runtime/platform.ts","../core/routing/discover.ts","../core/routing/types.ts","../core/routing/router.ts"],"sourcesContent":["import type {\n HttpMethod,\n RouteHandlerContext,\n RouteOperation,\n} from \"./types.ts\";\n\ntype MethodMap = Partial<Record<HttpMethod, unknown>>;\n\ntype DefinedRoute<\n Schemas extends MethodMap,\n Security extends { readonly [Method in keyof Schemas]: unknown },\n Contract extends { readonly [Method in keyof Schemas]: unknown },\n> = {\n readonly [Method in keyof Schemas]: RouteOperation<\n Schemas[Method],\n Security[Method],\n Contract[Method]\n >;\n};\n\n/**\n * Declares the operations a route file answers, one per HTTP method.\n *\n * The call is an identity function at runtime; its work is done in the type\n * system, where the schemas you pass become the types of `params`, `query`,\n * `headers`, and `body` inside each handler, and the declared authentication\n * mode determines whether `principal` can be `null`.\n *\n * ```ts\n * import { defineRoute } from \"@sleepy-hollow/framework/routing\";\n * import { z } from \"@sleepy-hollow/framework/validation\";\n *\n * export default defineRoute({\n * GET: {\n * schemas: {\n * params: z.object({ id: z.string() }).strict(),\n * responses: { 200: z.object({ id: z.string() }).strict() },\n * },\n * security: { authentication: \"none\" },\n * contract: { summary: \"Return one widget\" },\n * handler: ({ params }) => Response.json({ id: params.id }),\n * },\n * });\n * ```\n *\n * @param route The operations this file answers, keyed by HTTP method.\n * @returns The same declaration, typed so handlers infer their inputs.\n */\nexport function defineRoute<\n const Schemas extends MethodMap,\n const Security extends { readonly [Method in keyof Schemas]: unknown },\n const Contract extends { readonly [Method in keyof Schemas]: unknown },\n>(\n route: {\n readonly [Method in keyof Schemas]: {\n readonly schemas: Schemas[Method];\n readonly security: Security[Method];\n readonly contract: Contract[Method];\n readonly handler: (\n context: RouteHandlerContext<Schemas[Method], Security[Method]>,\n ) => Response | Promise<Response>;\n };\n },\n): DefinedRoute<Schemas, Security, Contract> {\n return route;\n}\n","import { spawn as spawnChild } from \"child_process\";\nimport {\n copyFile,\n lstat,\n mkdir,\n mkdtemp,\n readFile,\n readdir,\n realpath,\n rename,\n rm,\n stat,\n writeFile,\n} from \"fs/promises\";\nimport { readdirSync, watch, type FSWatcher } from \"fs\";\nimport { symlink } from \"fs/promises\";\nimport { Readable } from \"stream\";\nimport { tmpdir } from \"os\";\nimport { join } from \"path\";\nimport { serve as nodeServe, type FetchHandler } from \"./server.ts\";\n\nexport interface PlatformDirEntry {\n readonly name: string;\n readonly isFile: boolean;\n readonly isDirectory: boolean;\n readonly isSymlink: boolean;\n}\n\nexport interface PlatformCommandOutput {\n readonly code: number;\n readonly success: boolean;\n readonly stdout: Uint8Array;\n readonly stderr: Uint8Array;\n}\n\nclass NotFound extends Error {\n constructor(path?: string) {\n super(path ? `Not found: ${path}` : \"Not found\");\n this.name = \"NotFound\";\n }\n}\n\nfunction normalizeFilesystemError(error: unknown, path?: string): never {\n if (typeof error === \"object\" && error !== null && \"code\" in error &&\n (error as { readonly code?: unknown }).code === \"ENOENT\") {\n throw new NotFound(path);\n }\n throw error;\n}\n\nasync function filesystem<T>(operation: Promise<T>, path?: string): Promise<T> {\n try {\n return await operation;\n } catch (error) {\n return normalizeFilesystemError(error, path);\n }\n}\n\ninterface CommandOptions {\n readonly args?: readonly string[];\n readonly cwd?: string;\n readonly env?: Readonly<Record<string, string>>;\n readonly clearEnv?: boolean;\n readonly stdin?: \"null\" | \"piped\";\n readonly stdout?: \"piped\" | \"null\";\n readonly stderr?: \"piped\" | \"null\";\n}\n\nexport class Command {\n readonly #command: string;\n readonly #options: CommandOptions;\n\n constructor(command: string, options: CommandOptions = {}) {\n this.#command = command;\n this.#options = options;\n }\n\n async output(): Promise<PlatformCommandOutput> {\n const child = spawnChild(this.#command, this.#options.args ?? [], {\n cwd: this.#options.cwd,\n env: this.#options.clearEnv ? this.#options.env : { ...process.env, ...this.#options.env },\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n const stdout: Buffer[] = [];\n const stderr: Buffer[] = [];\n child.stdout.on(\"data\", (chunk: Buffer) => stdout.push(chunk));\n child.stderr.on(\"data\", (chunk: Buffer) => stderr.push(chunk));\n const code = await new Promise<number>((resolve, reject) => {\n child.once(\"error\", reject);\n child.once(\"close\", (status) => resolve(status ?? 1));\n });\n return { code, success: code === 0, stdout: Buffer.concat(stdout), stderr: Buffer.concat(stderr) };\n }\n\n spawn() {\n const child = spawnChild(this.#command, this.#options.args ?? [], {\n cwd: this.#options.cwd,\n env: this.#options.clearEnv ? this.#options.env : { ...process.env, ...this.#options.env },\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n return {\n stdout: Readable.toWeb(child.stdout) as ReadableStream<Uint8Array>,\n stderr: Readable.toWeb(child.stderr) as ReadableStream<Uint8Array>,\n status: new Promise<{ code: number; success: boolean }>((resolve, reject) => {\n child.once(\"error\", reject);\n child.once(\"close\", (code) => {\n const resolved = code ?? 1;\n resolve({ code: resolved, success: resolved === 0 });\n });\n }),\n kill: (signal?: NodeJS.Signals) => child.kill(signal),\n };\n }\n}\n\nclass Watcher implements AsyncIterable<{ readonly paths: readonly string[] }> {\n readonly #watcher: FSWatcher;\n #closed = false;\n #pending: Array<{ readonly paths: readonly string[] }> = [];\n #resolve?: (event: IteratorResult<{ readonly paths: readonly string[] }>) => void;\n #reject?: (reason: unknown) => void;\n #failure?: unknown;\n\n constructor(root: string) {\n this.#watcher = watch(root, { recursive: true }, (_event, filename) => {\n const event = { paths: [join(root, String(filename ?? \"\"))] };\n if (this.#resolve) {\n this.#resolve({ done: false, value: event });\n this.#resolve = undefined;\n } else this.#pending.push(event);\n });\n this.#watcher.on(\"error\", (error) => {\n if (this.#closed) return;\n this.#failure = error;\n this.#closed = true;\n this.#reject?.(error);\n this.#resolve = undefined;\n this.#reject = undefined;\n });\n }\n\n close(): void {\n this.#closed = true;\n this.#watcher.close();\n this.#resolve?.({ done: true, value: undefined });\n this.#resolve = undefined;\n this.#reject = undefined;\n }\n\n [Symbol.asyncIterator](): AsyncIterator<{ readonly paths: readonly string[] }> {\n return {\n next: () => {\n const value = this.#pending.shift();\n if (value) return Promise.resolve({ done: false, value });\n if (this.#failure) return Promise.reject(this.#failure);\n if (this.#closed) return Promise.resolve({ done: true, value: undefined });\n return new Promise((resolve, reject) => {\n this.#resolve = resolve;\n this.#reject = reject;\n });\n },\n };\n }\n}\n\nexport const platform = Object.freeze({\n args: process.argv.slice(2),\n cwd: () => process.cwd(),\n exit: (code?: number) => process.exit(code),\n execPath: () => process.execPath,\n env: Object.freeze({\n get: (name: string) => process.env[name],\n toObject: () => ({ ...process.env }),\n }),\n errors: Object.freeze({\n NotFound,\n AddrInUse: class AddrInUse extends Error {},\n PermissionDenied: class PermissionDenied extends Error {},\n }),\n isNotFound: (error: unknown) =>\n error instanceof NotFound ||\n (typeof error === \"object\" && error !== null &&\n \"code\" in error && (error as { readonly code?: unknown }).code === \"ENOENT\"),\n readTextFile: async (path: string) => filesystem(readFile(path, \"utf8\"), path),\n readFile: async (path: string) => filesystem(readFile(path), path),\n writeTextFile: async (path: string, text: string, options?: { readonly createNew?: boolean }) =>\n writeFile(path, text, options?.createNew ? { flag: \"wx\" } : undefined),\n stat: (path: string) => filesystem(stat(path), path),\n lstat: (path: string) => filesystem(lstat(path), path),\n mkdir,\n rename,\n remove: (path: string, options?: { readonly recursive?: boolean }) => rm(path, { recursive: options?.recursive, force: true }),\n realPath: (path: string) => filesystem(realpath(path), path),\n copyFile: (source: string, target: string) => filesystem(copyFile(source, target), source),\n symlink: (target: string, path: string) => filesystem(symlink(target, path), path),\n readDirSync: (path: string) => readdirSync(path, { withFileTypes: true }).map((entry) => ({ name: entry.name, isFile: entry.isFile(), isDirectory: entry.isDirectory(), isSymlink: entry.isSymbolicLink() })),\n makeTempDir: async (options?: { readonly prefix?: string; readonly dir?: string }) =>\n mkdtemp(join(options?.dir ?? tmpdir(), options?.prefix ?? \"sleepy-hollow-\")),\n async *readDir(path: string): AsyncIterable<PlatformDirEntry> {\n for (const entry of await readdir(path, { withFileTypes: true })) {\n yield { name: entry.name, isFile: entry.isFile(), isDirectory: entry.isDirectory(), isSymlink: entry.isSymbolicLink() };\n }\n },\n watchFs: (root: string, _options?: { readonly recursive?: boolean }) => new Watcher(root),\n addSignalListener: (signal: NodeJS.Signals, listener: () => void) => process.on(signal, listener),\n removeSignalListener: (signal: NodeJS.Signals, listener: () => void) => process.off(signal, listener),\n serve: (options: { readonly port?: number; readonly hostname?: string }, handler: FetchHandler) => nodeServe(handler, options),\n Command,\n});\n","import { platform, type PlatformDirEntry } from \"#platform\";\nimport { dirname, relative, resolve, sep } from \"path\";\nimport { fileURLToPath, pathToFileURL } from \"url\";\n\nimport {\n HTTP_METHODS,\n type HttpMethod,\n type NormalizedRoute,\n RouteDiscoveryError,\n type RouteModule,\n type RouteOperation,\n type RoutingDiagnostic,\n} from \"./types.ts\";\n\nconst dynamicSegment = /^\\[([^\\]]+)\\]$/;\nconst parameterName = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst methods = new Set<string>(HTTP_METHODS);\n\ninterface RouteFile {\n readonly path: string;\n readonly segments: readonly string[];\n readonly routePath: string;\n readonly conflictPath: string;\n readonly parameterNames: readonly string[];\n}\n\nconst portablePath = (path: string) => path.split(sep).join(\"/\");\n\nasync function collectRouteFiles(directory: string): Promise<string[]> {\n const files: string[] = [];\n const entries: PlatformDirEntry[] = [];\n\n for await (const entry of platform.readDir(directory)) entries.push(entry);\n entries.sort((left, right) => left.name.localeCompare(right.name));\n\n for (const entry of entries) {\n const path = resolve(directory, entry.name);\n if (entry.isDirectory) files.push(...await collectRouteFiles(path));\n if (entry.isFile && entry.name === \"route.ts\") files.push(path);\n }\n\n return files;\n}\n\nfunction normalizeRouteFile(\n apiRoot: string,\n path: string,\n): RouteFile | RoutingDiagnostic {\n const segments = portablePath(relative(apiRoot, dirname(path))).split(\"/\")\n .filter(Boolean);\n const routeSegments: string[] = [];\n const conflictSegments: string[] = [];\n const parameterNames: string[] = [];\n\n for (const segment of segments) {\n const match = segment.match(dynamicSegment);\n if (!match) {\n if (segment.includes(\"[\") || segment.includes(\"]\")) {\n return invalidSegment(path, segment);\n }\n routeSegments.push(segment);\n conflictSegments.push(segment);\n continue;\n }\n\n const name = match[1];\n if (!parameterName.test(name)) return invalidSegment(path, segment);\n if (parameterNames.includes(name)) {\n return {\n code: \"SH_ROUTE_INVALID_SEGMENT\",\n summary: `Dynamic parameter '${name}' is repeated in one route`,\n files: [portablePath(path)],\n correction: \"Use a unique parameter name for every dynamic segment.\",\n };\n }\n\n parameterNames.push(name);\n routeSegments.push(`:${name}`);\n conflictSegments.push(\":parameter\");\n }\n\n return {\n path: portablePath(path),\n segments,\n routePath: `/${routeSegments.join(\"/\")}`,\n conflictPath: `/${conflictSegments.join(\"/\")}`,\n parameterNames,\n };\n}\n\nfunction invalidSegment(path: string, segment: string): RoutingDiagnostic {\n return {\n code: \"SH_ROUTE_INVALID_SEGMENT\",\n summary: `Invalid dynamic route segment '${segment}'`,\n files: [portablePath(path)],\n correction:\n \"Use [name] with a TypeScript identifier as the parameter name.\",\n };\n}\n\nfunction validateModule(\n value: unknown,\n file: RouteFile,\n): RoutingDiagnostic | RouteModule {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return invalidModule(\n file.path,\n \"The default export must be created with defineRoute\",\n );\n }\n\n const entries = Object.entries(value);\n if (entries.length === 0) {\n return invalidModule(\n file.path,\n \"The route must declare at least one HTTP method\",\n );\n }\n\n for (const [method, operation] of entries) {\n if (!methods.has(method)) {\n return invalidModule(file.path, `Unsupported HTTP method '${method}'`);\n }\n if (!isOperation(operation)) {\n return invalidModule(\n file.path,\n `${method} must declare schemas, security, contract, and a handler`,\n );\n }\n }\n\n return value as RouteModule;\n}\n\nfunction isOperation(value: unknown): value is RouteOperation {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n const operation = value as Record<string, unknown>;\n return Object.hasOwn(operation, \"schemas\") &&\n Object.hasOwn(operation, \"security\") &&\n Object.hasOwn(operation, \"contract\") &&\n typeof operation.handler === \"function\";\n}\n\nfunction invalidModule(path: string, summary: string): RoutingDiagnostic {\n return {\n code: \"SH_ROUTE_INVALID_MODULE\",\n summary,\n files: [portablePath(path)],\n correction:\n \"Default-export one defineRoute method map with complete operations.\",\n };\n}\n\nfunction findConflicts(files: readonly RouteFile[]): RoutingDiagnostic[] {\n const groups = Map.groupBy(files, (file) => file.conflictPath);\n const diagnostics: RoutingDiagnostic[] = [];\n\n for (const [route, group] of groups) {\n if (group.length < 2) continue;\n diagnostics.push({\n code: \"SH_ROUTE_CONFLICT\",\n summary: `Ambiguous route definitions normalize to '${route}'`,\n files: group.map((file) => file.path).sort(),\n route,\n correction: \"Keep only one dynamic sibling at each route depth.\",\n });\n }\n\n return diagnostics.sort((left, right) =>\n (left.route ?? \"\").localeCompare(right.route ?? \"\")\n );\n}\n\n/**\n * Walks a directory and derives the route table from the file layout.\n *\n * Each `route.ts` becomes one route whose URL path is its position in the\n * tree, and each method it exports becomes one entry. Faults are collected\n * across the whole tree and thrown together as a\n * {@linkcode RouteDiscoveryError}, so one run reports every correction rather\n * than stopping at the first.\n *\n * @param apiRoot Directory to walk, as a path or a `file:` URL.\n * @returns Every discovered route, one entry per method.\n * @throws {RouteDiscoveryError} When any route in the tree is malformed.\n */\nexport async function discoverRoutes(\n apiRoot: URL | string,\n): Promise<readonly NormalizedRoute[]> {\n const root = resolve(\n apiRoot instanceof URL ? fileURLToPath(apiRoot) : apiRoot,\n );\n const diagnostics: RoutingDiagnostic[] = [];\n const routeFiles: RouteFile[] = [];\n\n for (const path of await collectRouteFiles(root)) {\n const normalized = normalizeRouteFile(root, path);\n if (\"code\" in normalized) diagnostics.push(normalized);\n else routeFiles.push(normalized);\n }\n\n diagnostics.push(...findConflicts(routeFiles));\n\n const routes: NormalizedRoute[] = [];\n for (const file of routeFiles) {\n try {\n const imported = await import(pathToFileURL(file.path).href);\n const routeModule = validateModule(imported.default, file);\n if (\"code\" in routeModule) {\n diagnostics.push(routeModule);\n continue;\n }\n\n for (const [method, operation] of Object.entries(routeModule)) {\n routes.push({\n method: method as HttpMethod,\n path: file.routePath,\n source: file.path,\n parameterNames: file.parameterNames,\n operation,\n });\n }\n } catch (error) {\n diagnostics.push(invalidModule(\n file.path,\n `Route module could not be loaded: ${\n error instanceof Error ? error.message : String(error)\n }`,\n ));\n }\n }\n\n if (diagnostics.length > 0) {\n diagnostics.sort((left, right) =>\n `${left.code}:${left.files.join(\":\")}`.localeCompare(\n `${right.code}:${right.files.join(\":\")}`,\n )\n );\n throw new RouteDiscoveryError(diagnostics);\n }\n\n return routes.sort((left, right) =>\n left.path.localeCompare(right.path) ||\n left.method.localeCompare(right.method)\n );\n}\n","/** The HTTP methods a route module may export an operation for. */\nexport const HTTP_METHODS = [\n \"DELETE\",\n \"GET\",\n \"HEAD\",\n \"OPTIONS\",\n \"PATCH\",\n \"POST\",\n \"PUT\",\n] as const;\n\n/** One of the {@linkcode HTTP_METHODS} a route operation may answer. */\nexport type HttpMethod = (typeof HTTP_METHODS)[number];\n\ntype SchemaOutput<Schema, Fallback> = Schema extends {\n readonly _zod: { readonly output: infer Output };\n} ? Output\n : Schema extends { readonly _output: infer Output } ? Output\n : Fallback;\n\ntype ReadonlyOutput<Output> = Output extends object ? Readonly<Output> : Output;\n\ntype LocationOutput<\n Schemas,\n Location extends PropertyKey,\n Fallback,\n> = Schemas extends { readonly [Key in Location]: infer Schema }\n ? ReadonlyOutput<SchemaOutput<Schema, Fallback>>\n : Fallback;\n\ntype BodyOutput<Schemas> = Schemas extends {\n readonly body: { readonly schema: infer Schema };\n} ? ReadonlyOutput<SchemaOutput<Schema, unknown>>\n : undefined;\n\n/**\n * The authenticated caller a handler runs on behalf of.\n *\n * Present only on routes whose security declares authentication; a route\n * declaring `\"none\"` receives `null` instead, and the type reflects that so a\n * handler cannot read a principal it was never given.\n */\nexport interface RoutePrincipal {\n /** Stable identifier for the caller, unique within its {@linkcode type}. */\n readonly id: string;\n /** What kind of caller this is, as named by the authentication provider. */\n readonly type: string;\n /** Additional claims the provider asserted about the caller. */\n readonly claims?: Readonly<Record<string, unknown>>;\n}\n\ntype SecurityPrincipal<Security> = Security extends {\n readonly authentication: { readonly mode: \"required\" };\n} ? RoutePrincipal\n : Security extends {\n readonly authentication: { readonly mode: \"none\" };\n } ? null\n : RoutePrincipal | null;\n\n/**\n * What a route handler receives.\n *\n * Each validated location is typed from the route's own schemas, so `params`,\n * `query`, `headers`, and `body` arrive already parsed rather than as raw\n * strings the handler has to re-check.\n */\nexport interface RouteHandlerContext<Schemas = unknown, Security = unknown> {\n /** The incoming request, unmodified. */\n readonly request: Request;\n /** Path parameters, parsed by the route's `params` schema. */\n readonly params: LocationOutput<\n Schemas,\n \"params\",\n Readonly<Record<string, string>>\n >;\n /** Query string values, parsed by the route's `query` schema. */\n readonly query: LocationOutput<\n Schemas,\n \"query\",\n Readonly<Record<string, unknown>>\n >;\n /** Request headers, parsed by the route's `headers` schema. */\n readonly headers: LocationOutput<\n Schemas,\n \"headers\",\n Readonly<Record<string, unknown>>\n >;\n /** The parsed request body, or `undefined` when the route declares none. */\n readonly body: BodyOutput<Schemas>;\n /** Aborts when the client disconnects or the request times out. */\n readonly signal: AbortSignal;\n /** The authenticated caller, or `null` on an unauthenticated route. */\n readonly principal: SecurityPrincipal<Security>;\n /** Correlates this request across logs and captured evidence. */\n readonly requestId: string;\n}\n\n/**\n * One method's implementation within a route module: its schemas, its security,\n * its documented contract, and the handler that answers it.\n */\nexport interface RouteOperation<\n Schemas = unknown,\n Security = unknown,\n Contract = unknown,\n> {\n /** Validation schemas for each request location and each response status. */\n readonly schemas: Schemas;\n /** Authentication and authorization requirements for this operation. */\n readonly security: Security;\n /** Documentation for this operation, such as its summary. */\n readonly contract: Contract;\n /** Answers the request once validation and security have passed. */\n readonly handler: (\n context: RouteHandlerContext<Schemas, Security>,\n ) => Response | Promise<Response>;\n}\n\n/** A route file's default export: one operation per method it answers. */\nexport type RouteModule = Partial<\n Record<HttpMethod, RouteOperation<unknown, unknown, unknown>>\n>;\n\n/**\n * One method of one route after discovery, with its URL path derived from the\n * file's position in the tree. This is what the router dispatches against.\n */\nexport interface NormalizedRoute {\n /** The method this entry answers. */\n readonly method: HttpMethod;\n /** The URL path, with parameters as `[name]` segments. */\n readonly path: string;\n /** Path of the file this route was discovered from. */\n readonly source: string;\n /** Names of the path parameters, in the order they appear. */\n readonly parameterNames: readonly string[];\n /** The operation to invoke for this method. */\n readonly operation: RouteOperation<unknown, unknown, unknown>;\n}\n\n/** One reason discovery refused a route tree. */\nexport interface RoutingDiagnostic {\n /** Stable machine-readable identifier for this kind of fault. */\n readonly code: string;\n /** What is wrong, in one sentence. */\n readonly summary: string;\n /** The files this diagnostic was raised against. */\n readonly files: readonly string[];\n /** The route path concerned, when the fault is specific to one. */\n readonly route?: string;\n /** What to change to resolve it. */\n readonly correction?: string;\n}\n\n/**\n * Thrown when a route tree cannot be discovered.\n *\n * Discovery reports every fault it found rather than the first, so one run\n * surfaces the whole set of corrections.\n */\nexport class RouteDiscoveryError extends Error {\n /**\n * Builds an error whose message lists every diagnostic, one per line.\n *\n * @param diagnostics Every fault discovery found, in the order detected.\n */\n constructor(readonly diagnostics: readonly RoutingDiagnostic[]) {\n super(\n diagnostics.map((diagnostic) =>\n `${diagnostic.code}: ${diagnostic.summary}`\n ).join(\"\\n\"),\n );\n this.name = \"RouteDiscoveryError\";\n }\n}\n","import { platform } from \"#platform\";\nimport type { NormalizedRoute } from \"./types.ts\";\n\ninterface Match {\n readonly route: NormalizedRoute;\n readonly params: Readonly<Record<string, string>>;\n}\n\nfunction splitPath(path: string): readonly string[] | undefined {\n try {\n return path.split(\"/\").filter(Boolean).map(decodeURIComponent);\n } catch {\n return undefined;\n }\n}\n\nfunction matchRoute(\n route: NormalizedRoute,\n requestSegments: readonly string[],\n): Match | undefined {\n const routeSegments = route.path.split(\"/\").filter(Boolean);\n if (routeSegments.length !== requestSegments.length) return undefined;\n\n const params: Record<string, string> = {};\n for (let index = 0; index < routeSegments.length; index += 1) {\n const expected = routeSegments[index];\n const actual = requestSegments[index];\n if (expected.startsWith(\":\")) params[expected.slice(1)] = actual;\n else if (expected !== actual) return undefined;\n }\n\n return { route, params };\n}\n\nfunction compareSpecificity(left: Match, right: Match): number {\n const leftSegments = left.route.path.split(\"/\").filter(Boolean);\n const rightSegments = right.route.path.split(\"/\").filter(Boolean);\n\n for (let index = 0; index < leftSegments.length; index += 1) {\n const leftDynamic = leftSegments[index].startsWith(\":\");\n const rightDynamic = rightSegments[index].startsWith(\":\");\n if (leftDynamic !== rightDynamic) return leftDynamic ? 1 : -1;\n }\n\n return left.route.path.localeCompare(right.route.path);\n}\n\nfunction problem(\n status: number,\n title: string,\n instance: string,\n headers?: HeadersInit,\n): Response {\n return new Response(\n JSON.stringify({ type: \"about:blank\", title, status, instance }),\n {\n status,\n headers: {\n \"content-type\": \"application/problem+json\",\n ...headers,\n },\n },\n );\n}\n\n/**\n * Builds a request handler that dispatches to a discovered route table.\n *\n * The returned object exposes `fetch`, so it can be passed to `platform.serve`\n * directly. An unmatched path answers 404 and an unmatched method answers 405,\n * both as problem-details responses.\n *\n * ```ts\n * import { createRouter, discoverRoutes } from \"@sleepy-hollow/framework\";\n *\n * const router = createRouter(await discoverRoutes(\"./api\"));\n * platform.serve(router.fetch);\n * ```\n *\n * @param routes The route table, normally from {@linkcode discoverRoutes}.\n * @returns A handler suitable for `platform.serve`.\n */\nexport function createRouter(\n routes: readonly NormalizedRoute[],\n): { fetch(request: Request): Promise<Response> } {\n const inventory = [...routes];\n\n return {\n async fetch(request: Request): Promise<Response> {\n const url = new URL(request.url);\n const requestSegments = splitPath(url.pathname);\n if (!requestSegments) return problem(404, \"Not Found\", url.pathname);\n\n const matches = inventory\n .map((route) => matchRoute(route, requestSegments))\n .filter((match): match is Match => match !== undefined)\n .sort(compareSpecificity);\n\n if (matches.length === 0) return problem(404, \"Not Found\", url.pathname);\n\n const selectedPath = matches[0].route.path;\n const pathMatches = matches.filter((match) =>\n match.route.path === selectedPath\n );\n const method = request.method.toUpperCase();\n const selected = pathMatches.find((match) =>\n match.route.method === method\n );\n if (!selected) {\n const allowed = [\n ...new Set(pathMatches.map((match) => match.route.method)),\n ]\n .sort();\n return problem(405, \"Method Not Allowed\", url.pathname, {\n allow: allowed.join(\", \"),\n });\n }\n\n return await selected.route.operation.handler({\n request,\n params: selected.params,\n query: Object.freeze({}),\n headers: Object.freeze({}),\n body: undefined,\n signal: request.signal,\n principal: null,\n requestId: \"\",\n });\n },\n };\n}\n"],"mappings":";;;;;AAgDO,SAAS,YAKd,OAU2C;AAC3C,SAAO;AACT;;;ACjEA,SAAS,SAAS,kBAAkB;AACpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,aAAa,aAA6B;AACnD,SAAS,eAAe;AACxB,SAAS,gBAAgB;AACzB,SAAS,cAAc;AACvB,SAAS,YAAY;AAiBrB,IAAM,WAAN,cAAuB,MAAM;AAAA,EAC3B,YAAY,MAAe;AACzB,UAAM,OAAO,cAAc,IAAI,KAAK,WAAW;AAC/C,SAAK,OAAO;AAAA,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IAAI,IAAI,YAAY,IAAI,CAAC,UAAU,MAAM,MAAM,MAAM,CAAC;AAAA,QAC3D,EACG,KAAK;AACR,eAAO,QAAQ,KAAK,sBAAsB,IAAI,UAAU;AAAA,UACtD,OAAO,QAAQ,KAAK,IAAI;AAAA,QAC1B,CAAC;AAAA,MACH;AAEA,aAAO,MAAM,SAAS,MAAM,UAAU,QAAQ;AAAA,QAC5C;AAAA,QACA,QAAQ,SAAS;AAAA,QACjB,OAAO,OAAO,OAAO,CAAC,CAAC;AAAA,QACvB,SAAS,OAAO,OAAO,CAAC,CAAC;AAAA,QACzB,MAAM;AAAA,QACN,QAAQ,QAAQ;AAAA,QAChB,WAAW;AAAA,QACX,WAAW;AAAA,MACb,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":["resolve"]}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
var __create = Object.create;
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __commonJS = (cb, mod) => function __require() {
|
|
8
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
19
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
20
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
21
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
22
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
23
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
24
|
+
mod
|
|
25
|
+
));
|
|
26
|
+
|
|
27
|
+
export {
|
|
28
|
+
__commonJS,
|
|
29
|
+
__toESM
|
|
30
|
+
};
|
|
31
|
+
//# sourceMappingURL=chunk-5WRI5ZAA.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// core/database/errors.ts
|
|
2
|
+
var DatabaseConfigurationError = class extends Error {
|
|
3
|
+
constructor(message) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.name = "DatabaseConfigurationError";
|
|
6
|
+
}
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
// core/database/postgres.ts
|
|
10
|
+
import { drizzle } from "drizzle-orm/node-postgres";
|
|
11
|
+
import { Pool } from "pg";
|
|
12
|
+
var DEFAULT_MAX_CONNECTIONS = 10;
|
|
13
|
+
function openPostgres(options) {
|
|
14
|
+
const databaseUrl = options.databaseUrl.trim();
|
|
15
|
+
if (!/^postgres(?:ql)?:\/\//i.test(databaseUrl)) {
|
|
16
|
+
throw new DatabaseConfigurationError("PostgreSQL requires a postgresql:// DATABASE_URL.");
|
|
17
|
+
}
|
|
18
|
+
const pool = new Pool({
|
|
19
|
+
connectionString: databaseUrl,
|
|
20
|
+
max: options.maxConnections ?? DEFAULT_MAX_CONNECTIONS,
|
|
21
|
+
ssl: options.tls === false ? void 0 : { rejectUnauthorized: true }
|
|
22
|
+
});
|
|
23
|
+
return {
|
|
24
|
+
profile: "postgres",
|
|
25
|
+
pool,
|
|
26
|
+
orm: drizzle(pool),
|
|
27
|
+
close: () => pool.end()
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// core/database/resource.ts
|
|
32
|
+
var identifier = /^[a-z][a-z0-9_]*$/;
|
|
33
|
+
function defineResource(definition) {
|
|
34
|
+
if (!identifier.test(definition.name)) {
|
|
35
|
+
throw new DatabaseConfigurationError("Resource names must be lowercase SQL identifiers.");
|
|
36
|
+
}
|
|
37
|
+
if (!Object.hasOwn(definition.fields, definition.primaryKey)) {
|
|
38
|
+
throw new DatabaseConfigurationError("The resource primary key must name a declared field.");
|
|
39
|
+
}
|
|
40
|
+
for (const field of Object.keys(definition.fields)) {
|
|
41
|
+
if (!identifier.test(field)) {
|
|
42
|
+
throw new DatabaseConfigurationError("Resource field names must be lowercase SQL identifiers.");
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return Object.freeze({
|
|
46
|
+
...definition,
|
|
47
|
+
fields: Object.freeze({ ...definition.fields })
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// core/database/sqlite.ts
|
|
52
|
+
import BetterSqlite3 from "better-sqlite3";
|
|
53
|
+
import { drizzle as drizzle2 } from "drizzle-orm/better-sqlite3";
|
|
54
|
+
var DEFAULT_BUSY_TIMEOUT_MS = 5e3;
|
|
55
|
+
function openEmbeddedSqlite(options) {
|
|
56
|
+
const filename = options.filename.trim();
|
|
57
|
+
if (filename.length === 0) {
|
|
58
|
+
throw new DatabaseConfigurationError("Embedded SQLite requires an explicit database filename.");
|
|
59
|
+
}
|
|
60
|
+
if (options.production && filename === ":memory:") {
|
|
61
|
+
throw new DatabaseConfigurationError("Production SQLite requires a durable database path, not :memory:.");
|
|
62
|
+
}
|
|
63
|
+
const client = new BetterSqlite3(filename);
|
|
64
|
+
client.pragma("foreign_keys = ON");
|
|
65
|
+
client.pragma(`busy_timeout = ${options.busyTimeoutMs ?? DEFAULT_BUSY_TIMEOUT_MS}`);
|
|
66
|
+
if (filename !== ":memory:") client.pragma("journal_mode = WAL");
|
|
67
|
+
return {
|
|
68
|
+
profile: "sqlite",
|
|
69
|
+
client,
|
|
70
|
+
orm: drizzle2(client),
|
|
71
|
+
close: () => client.close()
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// core/database/mod.ts
|
|
76
|
+
import { sql } from "drizzle-orm";
|
|
77
|
+
|
|
78
|
+
export {
|
|
79
|
+
DatabaseConfigurationError,
|
|
80
|
+
openPostgres,
|
|
81
|
+
defineResource,
|
|
82
|
+
openEmbeddedSqlite,
|
|
83
|
+
sql
|
|
84
|
+
};
|
|
85
|
+
//# sourceMappingURL=chunk-BAKXP7IR.js.map
|