@yannosay/sinth 5.2.3 → 5.3.1
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 +48 -0
- package/README.md +24 -23
- package/RUNTIME-EXCEPTION.md +25 -0
- package/dist/browser/compile.d.ts +35 -0
- package/dist/browser/compile.js +158 -0
- package/dist/browser/sinth.js +1492 -0
- package/dist/cli/index.js +3 -1
- package/dist/cli/templates.js +2 -2
- package/dist/cli/ui.d.ts +0 -1
- package/dist/cli/ui.js +1 -2
- package/dist/compiler/ast.d.ts +11 -0
- package/dist/compiler/codegen.d.ts +2 -87
- package/dist/compiler/codegen.js +49 -6
- package/dist/compiler/diagnostics.d.ts +0 -1
- package/dist/compiler/diagnostics.js +0 -4
- package/dist/compiler/html.d.ts +2 -0
- package/dist/compiler/html.js +11 -1
- package/dist/compiler/lexer.js +3 -0
- package/dist/compiler/parser.js +27 -1
- package/dist/compiler/prerender.js +4 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +3 -1
- package/dist/project/build.d.ts +6 -0
- package/dist/project/build.js +69 -41
- package/dist/project/config.d.ts +1 -0
- package/dist/project/config.js +3 -2
- package/dist/project/project.d.ts +1 -0
- package/dist/project/project.js +2 -1
- package/dist/runtime/index.d.ts +6 -0
- package/dist/runtime/index.js +18 -2
- package/dist/runtime/router.d.ts +36 -0
- package/dist/runtime/router.js +215 -0
- package/dist/server/client.js +3 -1
- package/dist/server/dev.js +65 -25
- package/dist/server/functions.d.ts +49 -0
- package/dist/server/functions.js +309 -0
- package/dist/server/preview.d.ts +2 -0
- package/dist/server/preview.js +41 -18
- package/dist/server/static.d.ts +10 -0
- package/dist/server/static.js +25 -0
- package/package.json +22 -13
- package/schema/sinth.config.schema.json +2 -1
- package/DOCS.md +0 -1360
package/dist/server/dev.js
CHANGED
|
@@ -44,8 +44,11 @@ const html_1 = require("../compiler/html");
|
|
|
44
44
|
const build_1 = require("../project/build");
|
|
45
45
|
const ui_1 = require("../cli/ui");
|
|
46
46
|
const client_1 = require("./client");
|
|
47
|
+
const functions_1 = require("./functions");
|
|
47
48
|
const static_1 = require("./static");
|
|
48
49
|
const CLIENT_URL = "/__sinth/client.js";
|
|
50
|
+
const HTML = "text/html; charset=utf-8";
|
|
51
|
+
const NO_STORE = { "Cache-Control": "no-store" };
|
|
49
52
|
const IGNORED = /(^|[\\/])(node_modules|\.git|\.sinth|\.wrangler|dist)([\\/]|$)/;
|
|
50
53
|
const WATCHED_EXT = /\.(sinth|css|scss|sass|js|mjs|ts|tsx|jsx|json|svg|png|jpe?g|gif|webp|avif|ico|woff2?|ttf|otf|txt|xml|webmanifest|html)$/i;
|
|
51
54
|
function hash(data) {
|
|
@@ -121,51 +124,83 @@ async function startDevServer(project, opts) {
|
|
|
121
124
|
};
|
|
122
125
|
const started = Date.now();
|
|
123
126
|
await rebuild();
|
|
124
|
-
const findPage = (
|
|
127
|
+
const findPage = (sitePath) => {
|
|
125
128
|
if (!output)
|
|
126
129
|
return undefined;
|
|
127
|
-
for (const cand of (0, static_1.routeCandidates)(
|
|
130
|
+
for (const cand of (0, static_1.routeCandidates)(sitePath)) {
|
|
128
131
|
const f = output.files.get(cand.slice(1));
|
|
129
132
|
if (f && cand.endsWith(".html"))
|
|
130
133
|
return Buffer.from(f.contents).toString("utf-8");
|
|
131
134
|
}
|
|
132
135
|
return undefined;
|
|
133
136
|
};
|
|
134
|
-
const
|
|
137
|
+
const resolve = (urlPath) => {
|
|
138
|
+
const sitePath = (0, static_1.stripBase)(urlPath, cfg.base);
|
|
139
|
+
const notFound = () => ({ status: 404, body: findPage("/404") ?? errorPage("404 Not Found", `No page or file matches ${urlPath}`), type: HTML });
|
|
140
|
+
if (sitePath === null)
|
|
141
|
+
return urlPath === "/" ? { status: 302, body: "", type: "text/plain", headers: { Location: cfg.base } } : notFound();
|
|
142
|
+
const isPageRequest = !/\.[a-z0-9]+$/i.test(sitePath) || sitePath.endsWith(".html");
|
|
143
|
+
if (isPageRequest && lastError && !output)
|
|
144
|
+
return { status: 500, body: errorPage(lastError.title, lastError.message), type: HTML };
|
|
145
|
+
const html = isPageRequest ? findPage(sitePath) : undefined;
|
|
146
|
+
if (html)
|
|
147
|
+
return { status: 200, body: html, type: HTML, headers: NO_STORE };
|
|
148
|
+
const mem = output?.files.get(sitePath.slice(1));
|
|
149
|
+
if (mem)
|
|
150
|
+
return { status: 200, body: mem.contents, type: (0, static_1.mimeType)(sitePath), headers: NO_STORE };
|
|
151
|
+
const fromPublic = (0, static_1.fileIfExists)((0, static_1.safeJoin)(cfg.publicDir, sitePath));
|
|
152
|
+
const fromStatic = cfg.staticDirs.some(d => sitePath.startsWith("/" + d + "/")) ? (0, static_1.fileIfExists)((0, static_1.safeJoin)(project.root, sitePath)) : null;
|
|
153
|
+
const file = fromPublic ?? fromStatic;
|
|
154
|
+
if (file)
|
|
155
|
+
return { status: 200, body: fs.readFileSync(file), type: (0, static_1.mimeType)(file), headers: NO_STORE };
|
|
156
|
+
return notFound();
|
|
157
|
+
};
|
|
158
|
+
const functions = new functions_1.FunctionsHost(project.root);
|
|
159
|
+
const handle = async (req, res) => {
|
|
135
160
|
const urlPath = (0, static_1.decodePath)(req.url);
|
|
136
161
|
if (!urlPath)
|
|
137
162
|
return (0, static_1.send)(res, 400, "Bad request", "text/plain");
|
|
138
|
-
if (req.method !== "GET" && req.method !== "HEAD")
|
|
139
|
-
return (0, static_1.send)(res, 405, "Method not allowed", "text/plain");
|
|
140
163
|
if (urlPath === "/__sinth/events") {
|
|
141
164
|
res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive" });
|
|
142
|
-
res.write(`data: ${JSON.stringify({ type: "init", pages: hashes, error: lastError })}\n\n`);
|
|
165
|
+
res.write(`data: ${JSON.stringify({ type: "init", pages: hashes, error: lastError, base: cfg.base })}\n\n`);
|
|
143
166
|
clients.add(res);
|
|
144
167
|
req.on("close", () => clients.delete(res));
|
|
145
168
|
return;
|
|
146
169
|
}
|
|
147
170
|
if (urlPath === CLIENT_URL)
|
|
148
|
-
return (0, static_1.send)(res, 200, client_1.DEV_CLIENT, "text/javascript; charset=utf-8",
|
|
149
|
-
const
|
|
150
|
-
if (
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
171
|
+
return (0, static_1.send)(res, 200, client_1.DEV_CLIENT, "text/javascript; charset=utf-8", NO_STORE);
|
|
172
|
+
const head = req.method === "HEAD";
|
|
173
|
+
if (functions.enabled) {
|
|
174
|
+
try {
|
|
175
|
+
const response = await functions.handle(await (0, functions_1.toRequest)(req), async (r) => (0, static_1.assetResponse)(resolve((0, static_1.decodePath)(new URL(r.url).pathname) ?? "/")));
|
|
176
|
+
if (response)
|
|
177
|
+
return await (0, functions_1.sendResponse)(res, response, head);
|
|
178
|
+
}
|
|
179
|
+
catch (err) {
|
|
180
|
+
if (err instanceof diagnostics_1.SinthError)
|
|
181
|
+
(0, ui_1.printDiagnostic)(err.diagnostic);
|
|
182
|
+
else
|
|
183
|
+
ui_1.log.error(err.stack ?? String(err));
|
|
184
|
+
if (!res.headersSent)
|
|
185
|
+
(0, static_1.send)(res, 500, errorPage("Function error", err instanceof diagnostics_1.SinthError ? (0, diagnostics_1.formatDiagnostic)(err.diagnostic, false) : String(err.stack ?? err)), HTML);
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
if (req.method !== "GET" && !head)
|
|
190
|
+
return (0, static_1.send)(res, 405, "Method not allowed", "text/plain");
|
|
191
|
+
(0, static_1.sendAsset)(res, resolve(urlPath), head);
|
|
192
|
+
};
|
|
193
|
+
const server = http.createServer((req, res) => {
|
|
194
|
+
handle(req, res).catch(err => {
|
|
195
|
+
ui_1.log.error(err.stack ?? String(err));
|
|
196
|
+
if (!res.headersSent)
|
|
197
|
+
(0, static_1.send)(res, 500, "Internal error", "text/plain");
|
|
198
|
+
else
|
|
199
|
+
res.end();
|
|
200
|
+
});
|
|
166
201
|
});
|
|
167
202
|
const port = await (0, static_1.listen)(server, opts.port, opts.host);
|
|
168
|
-
const url = `http://${(0, static_1.displayHost)(opts.host)}:${port}`;
|
|
203
|
+
const url = `http://${(0, static_1.displayHost)(opts.host)}:${port}${cfg.base}`;
|
|
169
204
|
ui_1.log.blank();
|
|
170
205
|
console.log(` ${ui_1.c.green("➜")} ${ui_1.c.bold("Local:")} ${ui_1.c.cyan(url)}`);
|
|
171
206
|
if (opts.host === "0.0.0.0" || opts.host === "::")
|
|
@@ -189,6 +224,11 @@ async function startDevServer(project, opts) {
|
|
|
189
224
|
broadcast({ type: "reload" });
|
|
190
225
|
return;
|
|
191
226
|
}
|
|
227
|
+
if (file.startsWith(functions.dir + path.sep)) {
|
|
228
|
+
functions.invalidate();
|
|
229
|
+
ui_1.log.success(`${ui_1.c.gray(path.relative(project.root, file).replace(/\\/g, "/"))} ${ui_1.c.dim("reloaded")}`);
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
192
232
|
if (path.basename(file) === "sinth.config.json") {
|
|
193
233
|
ui_1.log.warn("sinth.config.json changed. Restart the dev server to apply it.");
|
|
194
234
|
return;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import * as http from "http";
|
|
2
|
+
/**
|
|
3
|
+
* Server routes in `functions/`, following the Cloudflare Pages Functions conventions so the same
|
|
4
|
+
* files run in `sinth dev`, `sinth preview` and on Cloudflare Pages after `sinth deploy`:
|
|
5
|
+
*
|
|
6
|
+
* functions/api/hello.ts -> /api/hello
|
|
7
|
+
* functions/api/users/[id].ts -> /api/users/:id (context.params.id)
|
|
8
|
+
* functions/files/[[path]].ts -> /files/a/b/c (context.params.path = ["a", "b", "c"])
|
|
9
|
+
* functions/_middleware.ts -> runs before every route below its folder
|
|
10
|
+
*
|
|
11
|
+
* A module exports `onRequest` or method handlers such as `onRequestGet` / `onRequestPost`.
|
|
12
|
+
*/
|
|
13
|
+
export declare const FUNCTIONS_DIR = "functions";
|
|
14
|
+
export interface FunctionContext {
|
|
15
|
+
request: Request;
|
|
16
|
+
params: Record<string, string | string[]>;
|
|
17
|
+
env: Record<string, unknown>;
|
|
18
|
+
data: Record<string, unknown>;
|
|
19
|
+
functionPath: string;
|
|
20
|
+
next(input?: Request | string, init?: RequestInit): Promise<Response>;
|
|
21
|
+
waitUntil(promise: Promise<unknown>): void;
|
|
22
|
+
passThroughOnException(): void;
|
|
23
|
+
}
|
|
24
|
+
/** Serves a static file or page for `next()` and `env.ASSETS`. */
|
|
25
|
+
export type AssetHandler = (request: Request) => Promise<Response>;
|
|
26
|
+
export declare class FunctionsHost {
|
|
27
|
+
private readonly root;
|
|
28
|
+
private routes;
|
|
29
|
+
private modules;
|
|
30
|
+
private building;
|
|
31
|
+
readonly dir: string;
|
|
32
|
+
private readonly cacheDir;
|
|
33
|
+
constructor(root: string);
|
|
34
|
+
get enabled(): boolean;
|
|
35
|
+
invalidate(): void;
|
|
36
|
+
private scan;
|
|
37
|
+
private load;
|
|
38
|
+
private compile;
|
|
39
|
+
/**
|
|
40
|
+
* Runs the middleware chain and the matching route for a request. Returns null when no
|
|
41
|
+
* function applies, so the caller serves the request as a static file.
|
|
42
|
+
*/
|
|
43
|
+
handle(request: Request, assets: AssetHandler): Promise<Response | null>;
|
|
44
|
+
private handlerFor;
|
|
45
|
+
}
|
|
46
|
+
/** Converts a Node request into a Fetch API Request. */
|
|
47
|
+
export declare function toRequest(req: http.IncomingMessage): Promise<Request>;
|
|
48
|
+
/** Streams a Fetch API Response to a Node response. */
|
|
49
|
+
export declare function sendResponse(res: http.ServerResponse, response: Response, head?: boolean): Promise<void>;
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.FunctionsHost = exports.FUNCTIONS_DIR = void 0;
|
|
37
|
+
exports.toRequest = toRequest;
|
|
38
|
+
exports.sendResponse = sendResponse;
|
|
39
|
+
const crypto = __importStar(require("crypto"));
|
|
40
|
+
const esbuild = __importStar(require("esbuild"));
|
|
41
|
+
const fs = __importStar(require("fs"));
|
|
42
|
+
const path = __importStar(require("path"));
|
|
43
|
+
const diagnostics_1 = require("../compiler/diagnostics");
|
|
44
|
+
const ui_1 = require("../cli/ui");
|
|
45
|
+
/**
|
|
46
|
+
* Server routes in `functions/`, following the Cloudflare Pages Functions conventions so the same
|
|
47
|
+
* files run in `sinth dev`, `sinth preview` and on Cloudflare Pages after `sinth deploy`:
|
|
48
|
+
*
|
|
49
|
+
* functions/api/hello.ts -> /api/hello
|
|
50
|
+
* functions/api/users/[id].ts -> /api/users/:id (context.params.id)
|
|
51
|
+
* functions/files/[[path]].ts -> /files/a/b/c (context.params.path = ["a", "b", "c"])
|
|
52
|
+
* functions/_middleware.ts -> runs before every route below its folder
|
|
53
|
+
*
|
|
54
|
+
* A module exports `onRequest` or method handlers such as `onRequestGet` / `onRequestPost`.
|
|
55
|
+
*/
|
|
56
|
+
exports.FUNCTIONS_DIR = "functions";
|
|
57
|
+
const EXTENSIONS = /\.(ts|js|mjs|tsx|jsx)$/;
|
|
58
|
+
const METHOD_EXPORTS = {
|
|
59
|
+
GET: "onRequestGet", POST: "onRequestPost", PUT: "onRequestPut", PATCH: "onRequestPatch",
|
|
60
|
+
DELETE: "onRequestDelete", HEAD: "onRequestHead", OPTIONS: "onRequestOptions",
|
|
61
|
+
};
|
|
62
|
+
function parseSegments(rel) {
|
|
63
|
+
const parts = rel.replace(EXTENSIONS, "").split("/").filter(Boolean);
|
|
64
|
+
if (parts[parts.length - 1] === "index" || parts[parts.length - 1] === "_middleware")
|
|
65
|
+
parts.pop();
|
|
66
|
+
return parts.map(p => {
|
|
67
|
+
const catchall = p.match(/^\[\[([A-Za-z_]\w*)\]\]$/);
|
|
68
|
+
if (catchall)
|
|
69
|
+
return { kind: "catchall", name: catchall[1] };
|
|
70
|
+
const param = p.match(/^\[([A-Za-z_]\w*)\]$/);
|
|
71
|
+
if (param)
|
|
72
|
+
return { kind: "param", name: param[1] };
|
|
73
|
+
return { kind: "static", value: p };
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
function rank(route) {
|
|
77
|
+
return route.segments.map(s => (s.kind === "static" ? 0 : s.kind === "param" ? 1 : 2));
|
|
78
|
+
}
|
|
79
|
+
function compareRoutes(a, b) {
|
|
80
|
+
if (a.segments.length !== b.segments.length)
|
|
81
|
+
return b.segments.length - a.segments.length;
|
|
82
|
+
const ra = rank(a);
|
|
83
|
+
const rb = rank(b);
|
|
84
|
+
for (let i = 0; i < ra.length; i++)
|
|
85
|
+
if (ra[i] !== rb[i])
|
|
86
|
+
return ra[i] - rb[i];
|
|
87
|
+
return 0;
|
|
88
|
+
}
|
|
89
|
+
function matchRoute(route, parts, prefixOnly) {
|
|
90
|
+
const params = {};
|
|
91
|
+
for (let i = 0; i < route.segments.length; i++) {
|
|
92
|
+
const seg = route.segments[i];
|
|
93
|
+
if (seg.kind === "catchall") {
|
|
94
|
+
if (i >= parts.length)
|
|
95
|
+
return null;
|
|
96
|
+
params[seg.name] = parts.slice(i);
|
|
97
|
+
return params;
|
|
98
|
+
}
|
|
99
|
+
if (i >= parts.length)
|
|
100
|
+
return null;
|
|
101
|
+
if (seg.kind === "static" && seg.value !== parts[i])
|
|
102
|
+
return null;
|
|
103
|
+
if (seg.kind === "param")
|
|
104
|
+
params[seg.name] = parts[i];
|
|
105
|
+
}
|
|
106
|
+
return prefixOnly || route.segments.length === parts.length ? params : null;
|
|
107
|
+
}
|
|
108
|
+
function readDevVars(root) {
|
|
109
|
+
const vars = {};
|
|
110
|
+
for (const name of [".dev.vars", ".env"]) {
|
|
111
|
+
const file = path.join(root, name);
|
|
112
|
+
if (!fs.existsSync(file))
|
|
113
|
+
continue;
|
|
114
|
+
for (const line of fs.readFileSync(file, "utf-8").split(/\r?\n/)) {
|
|
115
|
+
const m = line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/);
|
|
116
|
+
if (!m || m[1] in vars)
|
|
117
|
+
continue;
|
|
118
|
+
vars[m[1]] = m[2].replace(/^(["'])(.*)\1$/, "$2");
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return vars;
|
|
122
|
+
}
|
|
123
|
+
class FunctionsHost {
|
|
124
|
+
root;
|
|
125
|
+
routes = null;
|
|
126
|
+
modules = new Map();
|
|
127
|
+
building = null;
|
|
128
|
+
dir;
|
|
129
|
+
cacheDir;
|
|
130
|
+
constructor(root) {
|
|
131
|
+
this.root = root;
|
|
132
|
+
this.dir = path.join(root, exports.FUNCTIONS_DIR);
|
|
133
|
+
this.cacheDir = path.join(root, ".sinth", "functions");
|
|
134
|
+
if (!globalThis.crypto)
|
|
135
|
+
globalThis.crypto = crypto.webcrypto;
|
|
136
|
+
}
|
|
137
|
+
get enabled() {
|
|
138
|
+
return fs.existsSync(this.dir);
|
|
139
|
+
}
|
|
140
|
+
invalidate() {
|
|
141
|
+
this.routes = null;
|
|
142
|
+
this.building = null;
|
|
143
|
+
}
|
|
144
|
+
scan() {
|
|
145
|
+
if (this.routes)
|
|
146
|
+
return this.routes;
|
|
147
|
+
const routes = [];
|
|
148
|
+
const walk = (dir) => {
|
|
149
|
+
if (!fs.existsSync(dir))
|
|
150
|
+
return;
|
|
151
|
+
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
152
|
+
const full = path.join(dir, e.name);
|
|
153
|
+
if (e.isDirectory())
|
|
154
|
+
walk(full);
|
|
155
|
+
else if (EXTENSIONS.test(e.name) && !e.name.endsWith(".d.ts") && !/\.(test|spec)\./.test(e.name)) {
|
|
156
|
+
const rel = path.relative(this.dir, full).replace(/\\/g, "/");
|
|
157
|
+
routes.push({ file: full, segments: parseSegments(rel), middleware: /(^|\/)_middleware\.\w+$/.test(rel) });
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
walk(this.dir);
|
|
162
|
+
this.routes = routes.sort(compareRoutes);
|
|
163
|
+
return this.routes;
|
|
164
|
+
}
|
|
165
|
+
async load() {
|
|
166
|
+
if (!this.building)
|
|
167
|
+
this.building = this.compile();
|
|
168
|
+
return this.building;
|
|
169
|
+
}
|
|
170
|
+
async compile() {
|
|
171
|
+
const routes = this.scan();
|
|
172
|
+
this.modules.clear();
|
|
173
|
+
if (!routes.length)
|
|
174
|
+
return;
|
|
175
|
+
fs.mkdirSync(this.cacheDir, { recursive: true });
|
|
176
|
+
const entryPoints = {};
|
|
177
|
+
for (const r of routes)
|
|
178
|
+
entryPoints[crypto.createHash("sha1").update(r.file).digest("hex").slice(0, 16)] = r.file;
|
|
179
|
+
let result;
|
|
180
|
+
try {
|
|
181
|
+
result = await esbuild.build({
|
|
182
|
+
entryPoints, bundle: true, platform: "node", format: "cjs", target: "node18", outdir: this.cacheDir,
|
|
183
|
+
write: true, logLevel: "silent", sourcemap: "inline", absWorkingDir: this.root, outExtension: { ".js": ".cjs" },
|
|
184
|
+
entryNames: "[name]-" + Date.now().toString(36),
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
catch (err) {
|
|
188
|
+
const first = err.errors?.[0];
|
|
189
|
+
this.building = null;
|
|
190
|
+
throw new diagnostics_1.SinthError("E0803", `Function build failed: ${first?.text ?? err.message}`, first?.location ? { file: path.resolve(this.root, first.location.file), line: first.location.line, col: first.location.column + 1 } : undefined);
|
|
191
|
+
}
|
|
192
|
+
for (const w of result.warnings)
|
|
193
|
+
ui_1.log.warn(w.text);
|
|
194
|
+
for (const [name, file] of Object.entries(entryPoints)) {
|
|
195
|
+
const out = fs.readdirSync(this.cacheDir).filter(f => f.startsWith(name + "-")).sort().pop();
|
|
196
|
+
if (!out)
|
|
197
|
+
continue;
|
|
198
|
+
const full = path.join(this.cacheDir, out);
|
|
199
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
200
|
+
this.modules.set(file, require(full));
|
|
201
|
+
for (const old of fs.readdirSync(this.cacheDir))
|
|
202
|
+
if (old.startsWith(name + "-") && old !== out)
|
|
203
|
+
fs.rmSync(path.join(this.cacheDir, old), { force: true });
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Runs the middleware chain and the matching route for a request. Returns null when no
|
|
208
|
+
* function applies, so the caller serves the request as a static file.
|
|
209
|
+
*/
|
|
210
|
+
async handle(request, assets) {
|
|
211
|
+
if (!this.enabled)
|
|
212
|
+
return null;
|
|
213
|
+
const url = new URL(request.url);
|
|
214
|
+
const parts = url.pathname.split("/").filter(Boolean).map(decodeURIComponent);
|
|
215
|
+
const routes = this.scan();
|
|
216
|
+
if (!routes.length)
|
|
217
|
+
return null;
|
|
218
|
+
await this.load();
|
|
219
|
+
const chain = [];
|
|
220
|
+
for (const r of [...routes].filter(x => x.middleware).sort((a, b) => a.segments.length - b.segments.length)) {
|
|
221
|
+
const params = matchRoute(r, parts, true);
|
|
222
|
+
const handler = params && this.handlerFor(r.file, request.method);
|
|
223
|
+
if (params && handler)
|
|
224
|
+
for (const h of Array.isArray(handler) ? handler : [handler])
|
|
225
|
+
chain.push({ handler: h, params, file: r.file });
|
|
226
|
+
}
|
|
227
|
+
for (const r of routes) {
|
|
228
|
+
if (r.middleware)
|
|
229
|
+
continue;
|
|
230
|
+
const params = matchRoute(r, parts, false);
|
|
231
|
+
if (!params)
|
|
232
|
+
continue;
|
|
233
|
+
const handler = this.handlerFor(r.file, request.method);
|
|
234
|
+
if (!handler)
|
|
235
|
+
continue;
|
|
236
|
+
for (const h of Array.isArray(handler) ? handler : [handler])
|
|
237
|
+
chain.push({ handler: h, params, file: r.file });
|
|
238
|
+
break;
|
|
239
|
+
}
|
|
240
|
+
if (!chain.length)
|
|
241
|
+
return null;
|
|
242
|
+
const env = { ...readDevVars(this.root), ASSETS: { fetch: (input, init) => assets(new Request(input, init)) } };
|
|
243
|
+
const data = {};
|
|
244
|
+
const run = async (index, req) => {
|
|
245
|
+
const step = chain[index];
|
|
246
|
+
if (!step)
|
|
247
|
+
return assets(req);
|
|
248
|
+
const result = await step.handler({
|
|
249
|
+
request: req, params: step.params, env, data,
|
|
250
|
+
functionPath: url.pathname,
|
|
251
|
+
next: (input, init) => run(index + 1, input === undefined ? req : new Request(input, init)),
|
|
252
|
+
waitUntil: p => { p.catch(err => ui_1.log.error(String(err))); },
|
|
253
|
+
passThroughOnException: () => undefined,
|
|
254
|
+
});
|
|
255
|
+
if (!(result instanceof Response)) {
|
|
256
|
+
throw new Error(`${path.relative(this.root, step.file)} must return a Response (got ${result === undefined ? "undefined" : typeof result})`);
|
|
257
|
+
}
|
|
258
|
+
return result;
|
|
259
|
+
};
|
|
260
|
+
return run(0, request);
|
|
261
|
+
}
|
|
262
|
+
handlerFor(file, method) {
|
|
263
|
+
const mod = this.modules.get(file);
|
|
264
|
+
if (!mod)
|
|
265
|
+
return undefined;
|
|
266
|
+
return mod[METHOD_EXPORTS[method] ?? ""] ?? mod.onRequest;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
exports.FunctionsHost = FunctionsHost;
|
|
270
|
+
/** Converts a Node request into a Fetch API Request. */
|
|
271
|
+
async function toRequest(req) {
|
|
272
|
+
const headers = new Headers();
|
|
273
|
+
for (const [k, v] of Object.entries(req.headers)) {
|
|
274
|
+
if (v === undefined)
|
|
275
|
+
continue;
|
|
276
|
+
for (const value of Array.isArray(v) ? v : [v])
|
|
277
|
+
headers.append(k, value);
|
|
278
|
+
}
|
|
279
|
+
let body;
|
|
280
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
281
|
+
const chunks = [];
|
|
282
|
+
for await (const chunk of req)
|
|
283
|
+
chunks.push(chunk);
|
|
284
|
+
body = Buffer.concat(chunks);
|
|
285
|
+
}
|
|
286
|
+
return new Request(`http://${req.headers.host ?? "localhost"}${req.url ?? "/"}`, { method: req.method, headers, body });
|
|
287
|
+
}
|
|
288
|
+
/** Streams a Fetch API Response to a Node response. */
|
|
289
|
+
async function sendResponse(res, response, head = false) {
|
|
290
|
+
const headers = {};
|
|
291
|
+
response.headers.forEach((value, key) => { if (key !== "set-cookie")
|
|
292
|
+
headers[key] = value; });
|
|
293
|
+
const cookies = response.headers.getSetCookie?.() ?? [];
|
|
294
|
+
if (cookies.length)
|
|
295
|
+
headers["set-cookie"] = cookies;
|
|
296
|
+
res.writeHead(response.status, response.statusText, headers);
|
|
297
|
+
if (!response.body || head) {
|
|
298
|
+
res.end();
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
const reader = response.body.getReader();
|
|
302
|
+
for (;;) {
|
|
303
|
+
const { done, value } = await reader.read();
|
|
304
|
+
if (done)
|
|
305
|
+
break;
|
|
306
|
+
res.write(value);
|
|
307
|
+
}
|
|
308
|
+
res.end();
|
|
309
|
+
}
|
package/dist/server/preview.d.ts
CHANGED
package/dist/server/preview.js
CHANGED
|
@@ -40,6 +40,7 @@ const path = __importStar(require("path"));
|
|
|
40
40
|
const diagnostics_1 = require("../compiler/diagnostics");
|
|
41
41
|
const ui_1 = require("../cli/ui");
|
|
42
42
|
const dev_1 = require("./dev");
|
|
43
|
+
const functions_1 = require("./functions");
|
|
43
44
|
const static_1 = require("./static");
|
|
44
45
|
function parseHeadersFile(file) {
|
|
45
46
|
if (!fs.existsSync(file))
|
|
@@ -74,32 +75,54 @@ async function startPreview(outDir, opts) {
|
|
|
74
75
|
Object.assign(out, r.headers);
|
|
75
76
|
return out;
|
|
76
77
|
};
|
|
77
|
-
const
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
return (0, static_1.send)(res, 405, "Method not allowed", "text/plain");
|
|
83
|
-
if (urlPath.endsWith(".html") && urlPath !== "/404.html") {
|
|
84
|
-
const clean = urlPath.replace(/(index)?\.html$/, "");
|
|
85
|
-
res.writeHead(308, { Location: clean || "/" });
|
|
86
|
-
res.end();
|
|
87
|
-
return;
|
|
78
|
+
const html = (file) => (file.endsWith(".html") ? "text/html; charset=utf-8" : (0, static_1.mimeType)(file));
|
|
79
|
+
const resolve = (urlPath) => {
|
|
80
|
+
const sitePath = (0, static_1.stripBase)(urlPath, opts.base);
|
|
81
|
+
if (sitePath !== null && sitePath.endsWith(".html") && sitePath !== "/404.html") {
|
|
82
|
+
return { status: 308, body: "", type: "text/plain", headers: { Location: urlPath.replace(/(index)?\.html$/, "") || "/" } };
|
|
88
83
|
}
|
|
89
|
-
|
|
84
|
+
if (sitePath === null && urlPath === "/")
|
|
85
|
+
return { status: 302, body: "", type: "text/plain", headers: { Location: opts.base } };
|
|
86
|
+
for (const cand of sitePath === null ? [] : (0, static_1.routeCandidates)(sitePath)) {
|
|
90
87
|
const file = (0, static_1.fileIfExists)((0, static_1.safeJoin)(outDir, cand));
|
|
91
|
-
if (file && path.basename(file) !== "_headers")
|
|
92
|
-
return
|
|
93
|
-
}
|
|
88
|
+
if (file && path.basename(file) !== "_headers")
|
|
89
|
+
return { status: 200, body: fs.readFileSync(file), type: html(file), headers: headersFor(urlPath) };
|
|
94
90
|
}
|
|
95
91
|
const notFound = (0, static_1.fileIfExists)(path.join(outDir, "404.html"));
|
|
96
|
-
return
|
|
92
|
+
return { status: 404, body: notFound ? fs.readFileSync(notFound) : "404 Not Found", type: notFound ? "text/html; charset=utf-8" : "text/plain", headers: headersFor(urlPath) };
|
|
93
|
+
};
|
|
94
|
+
const functions = new functions_1.FunctionsHost(opts.root);
|
|
95
|
+
const handle = async (req, res) => {
|
|
96
|
+
const urlPath = (0, static_1.decodePath)(req.url);
|
|
97
|
+
if (!urlPath)
|
|
98
|
+
return (0, static_1.send)(res, 400, "Bad request", "text/plain");
|
|
99
|
+
const head = req.method === "HEAD";
|
|
100
|
+
if (functions.enabled) {
|
|
101
|
+
const response = await functions.handle(await (0, functions_1.toRequest)(req), async (r) => (0, static_1.assetResponse)(resolve((0, static_1.decodePath)(new URL(r.url).pathname) ?? "/")));
|
|
102
|
+
if (response)
|
|
103
|
+
return (0, functions_1.sendResponse)(res, response, head);
|
|
104
|
+
}
|
|
105
|
+
if (req.method !== "GET" && !head)
|
|
106
|
+
return (0, static_1.send)(res, 405, "Method not allowed", "text/plain");
|
|
107
|
+
(0, static_1.sendAsset)(res, resolve(urlPath), head);
|
|
108
|
+
};
|
|
109
|
+
const server = http.createServer((req, res) => {
|
|
110
|
+
handle(req, res).catch(err => {
|
|
111
|
+
if (err instanceof diagnostics_1.SinthError)
|
|
112
|
+
(0, ui_1.printDiagnostic)(err.diagnostic);
|
|
113
|
+
else
|
|
114
|
+
ui_1.log.error(err.stack ?? String(err));
|
|
115
|
+
if (!res.headersSent)
|
|
116
|
+
(0, static_1.send)(res, 500, "Internal error", "text/plain");
|
|
117
|
+
else
|
|
118
|
+
res.end();
|
|
119
|
+
});
|
|
97
120
|
});
|
|
98
121
|
const port = await (0, static_1.listen)(server, opts.port, opts.host);
|
|
99
|
-
const url = `http://${(0, static_1.displayHost)(opts.host)}:${port}`;
|
|
122
|
+
const url = `http://${(0, static_1.displayHost)(opts.host)}:${port}${opts.base}`;
|
|
100
123
|
ui_1.log.blank();
|
|
101
124
|
console.log(` ${ui_1.c.green("➜")} ${ui_1.c.bold("Preview:")} ${ui_1.c.cyan(url)}`);
|
|
102
|
-
console.log(` ${ui_1.c.gray("Serving " + path.relative(process.cwd(), outDir) + " with production headers")}`);
|
|
125
|
+
console.log(` ${ui_1.c.gray("Serving " + (path.relative(process.cwd(), outDir) || ".") + " with production headers" + (functions.enabled ? " and functions/" : ""))}`);
|
|
103
126
|
ui_1.log.blank();
|
|
104
127
|
if (opts.open)
|
|
105
128
|
(0, dev_1.openBrowser)(url);
|
package/dist/server/static.d.ts
CHANGED
|
@@ -5,6 +5,16 @@ export declare function decodePath(url: string | undefined): string | null;
|
|
|
5
5
|
export declare function safeJoin(root: string, urlPath: string): string | null;
|
|
6
6
|
export declare function fileIfExists(file: string | null): string | null;
|
|
7
7
|
export declare function send(res: http.ServerResponse, status: number, body: string | Uint8Array, type: string, headers?: Record<string, string>): void;
|
|
8
|
+
export interface Asset {
|
|
9
|
+
status: number;
|
|
10
|
+
body: string | Uint8Array;
|
|
11
|
+
type: string;
|
|
12
|
+
headers?: Record<string, string>;
|
|
13
|
+
}
|
|
14
|
+
/** Maps a request path to a path inside the site when it is hosted under `base` (e.g. "/docs/"). */
|
|
15
|
+
export declare function stripBase(urlPath: string, base: string): string | null;
|
|
16
|
+
export declare function sendAsset(res: http.ServerResponse, asset: Asset, head?: boolean): void;
|
|
17
|
+
export declare function assetResponse(asset: Asset): Response;
|
|
8
18
|
export declare function routeCandidates(urlPath: string): string[];
|
|
9
19
|
export declare function listen(server: http.Server, port: number, host: string, attempts?: number): Promise<number>;
|
|
10
20
|
export declare function displayHost(host: string): string;
|
package/dist/server/static.js
CHANGED
|
@@ -39,6 +39,9 @@ exports.decodePath = decodePath;
|
|
|
39
39
|
exports.safeJoin = safeJoin;
|
|
40
40
|
exports.fileIfExists = fileIfExists;
|
|
41
41
|
exports.send = send;
|
|
42
|
+
exports.stripBase = stripBase;
|
|
43
|
+
exports.sendAsset = sendAsset;
|
|
44
|
+
exports.assetResponse = assetResponse;
|
|
42
45
|
exports.routeCandidates = routeCandidates;
|
|
43
46
|
exports.listen = listen;
|
|
44
47
|
exports.displayHost = displayHost;
|
|
@@ -106,6 +109,28 @@ function send(res, status, body, type, headers = {}) {
|
|
|
106
109
|
});
|
|
107
110
|
res.end(body);
|
|
108
111
|
}
|
|
112
|
+
/** Maps a request path to a path inside the site when it is hosted under `base` (e.g. "/docs/"). */
|
|
113
|
+
function stripBase(urlPath, base) {
|
|
114
|
+
if (base === "/")
|
|
115
|
+
return urlPath;
|
|
116
|
+
if (urlPath === base.slice(0, -1))
|
|
117
|
+
return "/";
|
|
118
|
+
return urlPath.startsWith(base) ? urlPath.slice(base.length - 1) : null;
|
|
119
|
+
}
|
|
120
|
+
function sendAsset(res, asset, head = false) {
|
|
121
|
+
if (head) {
|
|
122
|
+
res.writeHead(asset.status, { "Content-Type": asset.type, "X-Content-Type-Options": "nosniff", ...asset.headers });
|
|
123
|
+
res.end();
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
send(res, asset.status, asset.body, asset.type, asset.headers);
|
|
127
|
+
}
|
|
128
|
+
function assetResponse(asset) {
|
|
129
|
+
return new Response(asset.status === 204 || asset.status === 304 ? null : asset.body, {
|
|
130
|
+
status: asset.status,
|
|
131
|
+
headers: { "Content-Type": asset.type, ...asset.headers },
|
|
132
|
+
});
|
|
133
|
+
}
|
|
109
134
|
function routeCandidates(urlPath) {
|
|
110
135
|
const clean = urlPath.replace(/\/+$/, "") || "/";
|
|
111
136
|
if (clean === "/")
|