rosetack 0.1.3 → 0.1.4
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/dist-cli/compiler.mjs +1391 -131
- package/dist-cli/edge.mjs +45 -10
- package/dist-cli/rosetack.mjs +1865 -254
- package/dist-cli/runtime.mjs +194 -13
- package/dist-cli/test.mjs +1466 -175
- package/package.json +1 -1
- package/src/FRAMEWORK_VERSION +1 -1
- package/src/cli/content.ts +186 -0
- package/src/cli/edge.ts +9 -1
- package/src/cli/image-size.ts +83 -0
- package/src/cli/index.ts +149 -7
- package/src/cli/prod-server.ts +324 -0
- package/src/cli/prompt.ts +47 -19
- package/src/cli/shell.ts +39 -6
- package/src/compiler/index.ts +1188 -64
- package/src/runtime/index.ts +215 -13
package/package.json
CHANGED
package/src/FRAMEWORK_VERSION
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
0.1.
|
|
1
|
+
0.1.4
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
export interface ContentEntry {
|
|
5
|
+
slug: string;
|
|
6
|
+
frontmatter: Record<string, string | string[]>;
|
|
7
|
+
/** markdown source, unrendered (the page renders it, highlight applies) */
|
|
8
|
+
body: string;
|
|
9
|
+
/** rendered html with heading anchors (T20-free: ids for TOC deep links) */
|
|
10
|
+
html: string;
|
|
11
|
+
readingTime: number;
|
|
12
|
+
wordCount: number;
|
|
13
|
+
toc: { level: number; text: string; id: string }[];
|
|
14
|
+
excerpt: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Parse `---`-delimited frontmatter: `key: value` lines, `[a, b]` arrays. */
|
|
18
|
+
export function parseFrontmatter(raw: string): {
|
|
19
|
+
frontmatter: Record<string, string | string[]>;
|
|
20
|
+
body: string;
|
|
21
|
+
} {
|
|
22
|
+
if (!raw.startsWith("---")) return { frontmatter: {}, body: raw };
|
|
23
|
+
const end = raw.indexOf("\n---", 3);
|
|
24
|
+
if (end < 0) return { frontmatter: {}, body: raw };
|
|
25
|
+
const head = raw.slice(4, end);
|
|
26
|
+
const body = raw.slice(raw.indexOf("\n", end + 1) + 1).replace(/^\s*\n/, "");
|
|
27
|
+
const frontmatter: Record<string, string | string[]> = {};
|
|
28
|
+
for (const line of head.split("\n")) {
|
|
29
|
+
const m = /^(\w[\w-]*):\s*(.*)$/.exec(line.trim());
|
|
30
|
+
if (!m) continue;
|
|
31
|
+
const [, k, v] = m;
|
|
32
|
+
const arr = /^\[(.+)\]$/.exec(v.trim());
|
|
33
|
+
frontmatter[k] = arr
|
|
34
|
+
? arr[1].split(",").map((x) => x.trim().replace(/^["']|["']$/g, ""))
|
|
35
|
+
: v.trim().replace(/^["']|["']$/g, "");
|
|
36
|
+
}
|
|
37
|
+
return { frontmatter, body };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Mini-markdown → HTML: headings, fenced code, lists, bold/italic/code,
|
|
41
|
+
* links, paragraphs. Zero dependencies; ~100 lines cover the blog 90%. */
|
|
42
|
+
function interpolate(md: string, vars: Record<string, unknown>): string {
|
|
43
|
+
return md.replace(/{{(\w[\w.]*)}}/g, (_m, k) => {
|
|
44
|
+
const v = k.split(".").reduce((o: any, p) => (o == null ? o : o[p]), vars as any);
|
|
45
|
+
return v === undefined || v === null ? "" : String(v);
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function renderMarkdown(md: string, vars?: Record<string, unknown>): string {
|
|
50
|
+
if (vars) md = interpolate(md, vars);
|
|
51
|
+
const blocks: string[] = [];
|
|
52
|
+
let src = md.replace(/```(\w*)\n([\s\S]*?)```/g, (_m, lang, code) => {
|
|
53
|
+
blocks.push(
|
|
54
|
+
`<pre data-lang="${lang}"><code>${code
|
|
55
|
+
.replace(/&/g, "&")
|
|
56
|
+
.replace(/</g, "<")
|
|
57
|
+
.replace(/>/g, ">")}</code></pre>`,
|
|
58
|
+
);
|
|
59
|
+
return `\u0000CODE${blocks.length - 1}\u0000`;
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
const inline = (s: string) =>
|
|
63
|
+
s
|
|
64
|
+
.replace(/&/g, "&")
|
|
65
|
+
.replace(/</g, "<")
|
|
66
|
+
.replace(/>/g, ">")
|
|
67
|
+
.replace(/`([^`]+)`/g, "<code>$1</code>")
|
|
68
|
+
.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>")
|
|
69
|
+
.replace(/\*([^*]+)\*/g, "<em>$1</em>")
|
|
70
|
+
.replace(
|
|
71
|
+
/\[([^\]]+)\]\(([^)]+)\)/g,
|
|
72
|
+
'<a href="$2" rel="noopener">$1</a>',
|
|
73
|
+
);
|
|
74
|
+
|
|
75
|
+
const out: string[] = [];
|
|
76
|
+
let listOpen: "ul" | "ol" | null = null;
|
|
77
|
+
const closeList = () => {
|
|
78
|
+
if (listOpen) { out.push(`</${listOpen}>`); listOpen = null; }
|
|
79
|
+
};
|
|
80
|
+
for (const line of src.split("\n")) {
|
|
81
|
+
const h = /^(#{1,4})\s+(.*)$/.exec(line);
|
|
82
|
+
const li = /^\s*[-*]\s+(.*)$/.exec(line);
|
|
83
|
+
const oli = /^\s*\d+\.\s+(.*)$/.exec(line);
|
|
84
|
+
if (h) { closeList(); out.push(`<h${h[1].length}>${inline(h[2])}</h${h[1].length}>`); }
|
|
85
|
+
else if (li) {
|
|
86
|
+
if (listOpen !== "ul") { closeList(); out.push("<ul>"); listOpen = "ul"; }
|
|
87
|
+
out.push(`<li>${inline(li[1])}</li>`);
|
|
88
|
+
} else if (oli) {
|
|
89
|
+
if (listOpen !== "ol") { closeList(); out.push("<ol>"); listOpen = "ol"; }
|
|
90
|
+
out.push(`<li>${inline(oli[1])}</li>`);
|
|
91
|
+
} else if (line.trim() === "") { closeList(); }
|
|
92
|
+
else if (line.startsWith("\u0000CODE")) { closeList(); out.push(line); }
|
|
93
|
+
else { closeList(); out.push(`<p>${inline(line)}</p>`); }
|
|
94
|
+
}
|
|
95
|
+
closeList();
|
|
96
|
+
return out
|
|
97
|
+
.join("\n")
|
|
98
|
+
.replace(/\u0000CODE(\d+)\u0000/g, (_m, i) => blocks[Number(i)]);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Scan src/content/<collection>/*.md into entries (slug = filename). */
|
|
102
|
+
export function scanContentDir(contentDir: string): Record<string, ContentEntry[]> {
|
|
103
|
+
const collections: Record<string, ContentEntry[]> = {};
|
|
104
|
+
if (!fs.existsSync(contentDir)) return collections;
|
|
105
|
+
for (const coll of fs.readdirSync(contentDir, { withFileTypes: true })) {
|
|
106
|
+
if (!coll.isDirectory()) continue;
|
|
107
|
+
const entries: ContentEntry[] = [];
|
|
108
|
+
const dir = path.join(contentDir, coll.name);
|
|
109
|
+
for (const f of fs.readdirSync(dir)) {
|
|
110
|
+
if (!f.endsWith(".md")) continue;
|
|
111
|
+
const raw = fs.readFileSync(path.join(dir, f), "utf-8");
|
|
112
|
+
const { frontmatter, body } = parseFrontmatter(raw);
|
|
113
|
+
if (String(frontmatter.draft ?? "").toLowerCase() === "true") continue;
|
|
114
|
+
const slug = f.replace(/\.md$/, "");
|
|
115
|
+
const html = renderMarkdown(body);
|
|
116
|
+
const words = body.replace(/[#*`\[\]()>-]/g, " ").split(/\s+/).filter(Boolean).length;
|
|
117
|
+
const headings: { level: number; text: string; id: string }[] = [];
|
|
118
|
+
const tocHtml = html.replace(/<h([1-4])>([^<]+)<\/h\1>/g, (_m, lvl: string, txt: string) => {
|
|
119
|
+
const id = txt.toLowerCase().replace(/[^\w\s-]/g, "").trim().replace(/\s+/g, "-");
|
|
120
|
+
headings.push({ level: Number(lvl), text: txt, id });
|
|
121
|
+
return `<h${lvl} id="${id}">${txt}</h${lvl}>`;
|
|
122
|
+
});
|
|
123
|
+
entries.push({
|
|
124
|
+
slug, frontmatter,
|
|
125
|
+
body, html: tocHtml,
|
|
126
|
+
readingTime: Math.max(1, Math.round(words / 200)),
|
|
127
|
+
wordCount: words,
|
|
128
|
+
toc: headings,
|
|
129
|
+
excerpt: String(frontmatter.summary ?? "") || (html.match(/<p>([\s\S]*?)<\/p>/)?.[1] ?? "").replace(/<[^>]+>/g, "").slice(0, 160),
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
entries.sort((a, b) =>
|
|
133
|
+
String(b.frontmatter.date ?? "").localeCompare(String(a.frontmatter.date ?? "")),
|
|
134
|
+
);
|
|
135
|
+
collections[coll.name] = entries;
|
|
136
|
+
}
|
|
137
|
+
return collections;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Prev/next navigation within a collection (date-descending order). */
|
|
141
|
+
export function prevNext(
|
|
142
|
+
entries: ContentEntry[],
|
|
143
|
+
slug: string,
|
|
144
|
+
): { prev: ContentEntry | null; next: ContentEntry | null } {
|
|
145
|
+
const i = entries.findIndex((e) => e.slug === slug);
|
|
146
|
+
return { prev: i > 0 ? entries[i - 1] : null, next: i >= 0 && i < entries.length - 1 ? entries[i + 1] : null };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Group a collection by a frontmatter array field (tags/categories). */
|
|
150
|
+
export function byTag(
|
|
151
|
+
entries: ContentEntry[],
|
|
152
|
+
field: string,
|
|
153
|
+
): Record<string, ContentEntry[]> {
|
|
154
|
+
const out: Record<string, ContentEntry[]> = {};
|
|
155
|
+
for (const e of entries) {
|
|
156
|
+
for (const t of (e.frontmatter[field] as string[] | undefined) ?? []) {
|
|
157
|
+
(out[t] ??= []).push(e);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
return out;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
globalThis.__rosetackContentMk = renderMarkdown;
|
|
164
|
+
|
|
165
|
+
/** RSS 2.0 feed from a collection - wire to /feed.xml or /api/feed. */
|
|
166
|
+
export function buildRss(
|
|
167
|
+
entries: ContentEntry[],
|
|
168
|
+
opts: { title: string; origin: string; description?: string; pathPrefix?: string },
|
|
169
|
+
): string {
|
|
170
|
+
const esc = (v: unknown) =>
|
|
171
|
+
String(v ?? "")
|
|
172
|
+
.replace(/&/g, "&")
|
|
173
|
+
.replace(/</g, "<")
|
|
174
|
+
.replace(/>/g, ">")
|
|
175
|
+
.replace(/"/g, """);
|
|
176
|
+
const prefix = opts.pathPrefix ?? "/";
|
|
177
|
+
const items = entries
|
|
178
|
+
.map((e) => {
|
|
179
|
+
const url = `${opts.origin}${prefix}${e.slug}`;
|
|
180
|
+
const pub = e.frontmatter.date ? new Date(String(e.frontmatter.date)).toUTCString() : "";
|
|
181
|
+
const excerpt = e.excerpt ? `<description>${esc(e.excerpt)}</description>` : "";
|
|
182
|
+
return ` <item>\n <title>${esc(e.frontmatter.title)}</title>\n <link>${esc(url)}</link>\n <guid isPermaLink="true">${esc(url)}</guid>\n ${pub ? `<pubDate>${pub}</pubDate>\n ` : ""}${excerpt}\n </item>`;
|
|
183
|
+
})
|
|
184
|
+
.join("\n");
|
|
185
|
+
return `<?xml version="1.0" encoding="UTF-8"?>\n<rss version="2.0"><channel>\n<title>${esc(opts.title)}</title>\n<link>${esc(opts.origin)}${prefix}</link>\n<description>${esc(opts.description ?? "")}</description>\n${items}\n</channel></rss>`;
|
|
186
|
+
}
|
package/src/cli/edge.ts
CHANGED
|
@@ -90,6 +90,7 @@ export async function createEdgeHandler(
|
|
|
90
90
|
client = null;
|
|
91
91
|
}
|
|
92
92
|
}
|
|
93
|
+
if (client && client.includes('chunks/')) client = null;
|
|
93
94
|
if (preloaded && 'styles' in preloaded) {
|
|
94
95
|
styles = preloaded.styles ?? '';
|
|
95
96
|
} else {
|
|
@@ -143,6 +144,7 @@ export async function createEdgeHandler(
|
|
|
143
144
|
return hookCtx ? mod.runResponseHooks(hookCtx, apiRes) : apiRes;
|
|
144
145
|
}
|
|
145
146
|
const form = request.method === 'POST' ? await request.formData() : undefined;
|
|
147
|
+
if (form) (mod as any).invalidateRenderCache?.();
|
|
146
148
|
if (!form && !broken.has(pathname) && !mod.isBuffered?.(pathname) && mod.canStream(pathname) && !mod.isNoJs(pathname)) {
|
|
147
149
|
const nonce = mod.cspNonce?.(pathname) ? mintNonce() : '';
|
|
148
150
|
const streamed = new Response(null, {
|
|
@@ -165,7 +167,13 @@ export async function createEdgeHandler(
|
|
|
165
167
|
});
|
|
166
168
|
return new Response(stream, { status: head.status, headers: head.headers });
|
|
167
169
|
}
|
|
168
|
-
const
|
|
170
|
+
const cookieHeader = request.headers.get('cookie') || '';
|
|
171
|
+
const memoHit = !form && (mod as any).isCachedRoute?.(pathname)
|
|
172
|
+
? (mod as any).peekRenderCache?.(pathname, cookieHeader)
|
|
173
|
+
: null;
|
|
174
|
+
const page = memoHit ?? ((mod as any).renderPageCached && !form
|
|
175
|
+
? await (mod as any).renderPageCached(pathname, cookieHeader)
|
|
176
|
+
: await mod.renderPage(pathname, form));
|
|
169
177
|
const nonce = mod.cspNonce?.(pathname) ? mintNonce() : '';
|
|
170
178
|
const html = buildShell(page.html, page.state, client, page.head, styles, page.csr !== false, page.lang, page.dir, nonce, page.shell !== false);
|
|
171
179
|
const buffered = new Response(html, {
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
|
|
3
|
+
export interface ImageDims {
|
|
4
|
+
width: number;
|
|
5
|
+
height: number;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/** Parse dimensions from the leading bytes of an image file. */
|
|
9
|
+
export function readImageSize(filePath: string): ImageDims | null {
|
|
10
|
+
try {
|
|
11
|
+
const fd = fs.openSync(filePath, "r");
|
|
12
|
+
const buf = Buffer.alloc(64);
|
|
13
|
+
const read = fs.readSync(fd, buf, 0, 64, 0);
|
|
14
|
+
fs.closeSync(fd);
|
|
15
|
+
if (read < 24) return null;
|
|
16
|
+
|
|
17
|
+
if (
|
|
18
|
+
buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47
|
|
19
|
+
) {
|
|
20
|
+
return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
if (buf.slice(0, 3).toString("latin1") === "GIF") {
|
|
24
|
+
return { width: buf.readUInt16LE(6), height: buf.readUInt16LE(8) };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
if (
|
|
28
|
+
buf.slice(0, 4).toString("latin1") === "RIFF" &&
|
|
29
|
+
buf.slice(8, 12).toString("latin1") === "WEBP"
|
|
30
|
+
) {
|
|
31
|
+
return parseWebP(buf);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if (buf[0] === 0xff && buf[1] === 0xd8) {
|
|
35
|
+
return parseJpeg(filePath);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
return null;
|
|
39
|
+
} catch {
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function parseWebP(buf: Buffer): ImageDims | null {
|
|
45
|
+
const format = buf.slice(12, 16).toString("latin1");
|
|
46
|
+
if (format === "VP8 ") {
|
|
47
|
+
return { width: buf.readUInt16LE(26) & 0x3fff, height: buf.readUInt16LE(28) & 0x3fff };
|
|
48
|
+
}
|
|
49
|
+
if (format === "VP8L") {
|
|
50
|
+
const b = buf.readUInt32LE(21);
|
|
51
|
+
return { width: (b & 0x3fff) + 1, height: ((b >> 14) & 0x3fff) + 1 };
|
|
52
|
+
}
|
|
53
|
+
if (format === "VP8X") {
|
|
54
|
+
const w = buf.readUIntLE(24, 3) + 1;
|
|
55
|
+
const h = buf.readUIntLE(27, 3) + 1;
|
|
56
|
+
return { width: w, height: h };
|
|
57
|
+
}
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function parseJpeg(filePath: string): ImageDims | null {
|
|
62
|
+
const fd = fs.openSync(filePath, "r");
|
|
63
|
+
try {
|
|
64
|
+
const buf = Buffer.alloc(4);
|
|
65
|
+
let pos = 2;
|
|
66
|
+
for (let guard = 0; guard < 64; guard++) {
|
|
67
|
+
if (fs.readSync(fd, buf, 0, 4, pos) < 4) return null;
|
|
68
|
+
if (buf[0] !== 0xff) { pos += 1; continue; }
|
|
69
|
+
const marker = buf[1];
|
|
70
|
+
if (marker === 0xd8 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) { pos += 2; continue; }
|
|
71
|
+
const len = fs.readSync(fd, buf, 0, 2, pos + 2) < 2 ? 0 : buf.readUInt16BE(2);
|
|
72
|
+
if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
|
|
73
|
+
const seg = Buffer.alloc(8);
|
|
74
|
+
fs.readSync(fd, seg, 0, 8, pos + 4);
|
|
75
|
+
return { width: seg.readUInt16BE(3), height: seg.readUInt16BE(1) };
|
|
76
|
+
}
|
|
77
|
+
pos += 2 + len;
|
|
78
|
+
}
|
|
79
|
+
return null;
|
|
80
|
+
} finally {
|
|
81
|
+
fs.closeSync(fd);
|
|
82
|
+
}
|
|
83
|
+
}
|
package/src/cli/index.ts
CHANGED
|
@@ -3,11 +3,14 @@
|
|
|
3
3
|
import * as fs from 'fs';
|
|
4
4
|
import * as path from 'path';
|
|
5
5
|
import * as zlib from 'zlib';
|
|
6
|
+
import { createHash } from 'crypto';
|
|
6
7
|
import { createRequire } from 'module';
|
|
7
8
|
import { pathToFileURL, fileURLToPath } from 'url';
|
|
8
9
|
import { buildProject, scanRoseFiles, scanComponentFiles, scriptOf, extractExports, loadPlugins, RoseError, errorInfo, type RouteInfo } from '../compiler/index.js';
|
|
9
10
|
import { getHtmlShell, getClientSource, getStyles, shellOpen, clientScriptTag, securityHeaders, mintNonce, setBundleMode } from './shell.js';
|
|
10
11
|
import { AI_PROMPT } from './prompt.js';
|
|
12
|
+
import { Readable } from 'stream';
|
|
13
|
+
import { createEdgeHandler } from './edge.js';
|
|
11
14
|
import type * as ts from 'typescript';
|
|
12
15
|
|
|
13
16
|
type Encoding = 'br' | 'gzip' | 'deflate';
|
|
@@ -130,6 +133,23 @@ let serverModule: any = null;
|
|
|
130
133
|
let serverMtime = -1;
|
|
131
134
|
let serverVersion = 0;
|
|
132
135
|
|
|
136
|
+
function loadDotEnv(dir: string): void {
|
|
137
|
+
try {
|
|
138
|
+
const raw = fs.readFileSync(path.join(dir, '.env'), 'utf-8');
|
|
139
|
+
for (const line of raw.split(/\r?\n/)) {
|
|
140
|
+
const t = line.trim();
|
|
141
|
+
if (!t || t.startsWith('#')) continue;
|
|
142
|
+
const eq = t.indexOf('=');
|
|
143
|
+
if (eq <= 0) continue;
|
|
144
|
+
const k = t.slice(0, eq).trim();
|
|
145
|
+
let v = t.slice(eq + 1).trim();
|
|
146
|
+
if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) v = v.slice(1, -1);
|
|
147
|
+
if (!(k in process.env)) process.env[k] = v;
|
|
148
|
+
}
|
|
149
|
+
} catch { }
|
|
150
|
+
}
|
|
151
|
+
loadDotEnv(process.cwd());
|
|
152
|
+
|
|
133
153
|
async function loadServer(): Promise<any> {
|
|
134
154
|
const file = path.join(OUT_DIR, 'server.js');
|
|
135
155
|
const mtimeMs = fs.statSync(file).mtimeMs;
|
|
@@ -612,6 +632,8 @@ function settleDevBuild(): Promise<void> | null {
|
|
|
612
632
|
}
|
|
613
633
|
|
|
614
634
|
// Wrap a dev response so every HTML document carries the bridge (and the resumed state, once).
|
|
635
|
+
let invalidateHook: (() => void) | null = null;
|
|
636
|
+
|
|
615
637
|
function devWrap(inner: (req: any, res: any) => void): (req: any, res: any) => void {
|
|
616
638
|
devMode = true;
|
|
617
639
|
return (req, res) => {
|
|
@@ -652,6 +674,27 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
|
|
|
652
674
|
res.end(blocked.body);
|
|
653
675
|
return;
|
|
654
676
|
}
|
|
677
|
+
if (req.method === 'POST' && (req.url || '').startsWith('/__rosetack/revalidate')) {
|
|
678
|
+
const token = process.env.rosetack_REVALIDATE_TOKEN || '';
|
|
679
|
+
if (!token) { res.statusCode = 404; res.end(); return; }
|
|
680
|
+
if (req.headers['x-rosetack-token'] !== token) {
|
|
681
|
+
res.statusCode = 403; res.setHeader('content-type', 'application/json');
|
|
682
|
+
res.end(JSON.stringify({ error: 'invalid token' })); return;
|
|
683
|
+
}
|
|
684
|
+
let body = '';
|
|
685
|
+
req.on('data', (c) => { body += c; if (body.length > 1e6) req.destroy(); });
|
|
686
|
+
req.on('end', () => {
|
|
687
|
+
try {
|
|
688
|
+
const payload = JSON.parse(body || '{}');
|
|
689
|
+
if (invalidateHook) invalidateHook();
|
|
690
|
+
res.setHeader('content-type', 'application/json');
|
|
691
|
+
res.end(JSON.stringify({ revalidated: true, scope: payload.all ? 'all' : 'paths' }));
|
|
692
|
+
} catch (e: any) {
|
|
693
|
+
res.statusCode = 400; res.end(JSON.stringify({ error: String(e).slice(0, 120) }));
|
|
694
|
+
}
|
|
695
|
+
});
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
655
698
|
const want = pathnameOf(req.url || '/');
|
|
656
699
|
const canonical = want.replace(/\/+$/, '') || '/';
|
|
657
700
|
if (canonical !== want) {
|
|
@@ -700,6 +743,7 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
|
|
|
700
743
|
body: body.length > 0 ? body : undefined,
|
|
701
744
|
});
|
|
702
745
|
ssrModule.setQuery?.(queryOf(req.url));
|
|
746
|
+
if ((req.method || 'GET') !== 'GET') ssrModule.invalidateRenderCache?.();
|
|
703
747
|
let apiRes = await ssrModule.handleApi(req.method || 'GET', apiPath, request);
|
|
704
748
|
if (hookCtx) apiRes = await ssrModule.runResponseHooks(hookCtx, apiRes);
|
|
705
749
|
writeWebHeaders(apiRes, res);
|
|
@@ -729,6 +773,7 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
|
|
|
729
773
|
}
|
|
730
774
|
}
|
|
731
775
|
ssrModule.setQuery?.(queryOf(req.url));
|
|
776
|
+
ssrModule.invalidateRenderCache?.();
|
|
732
777
|
const page = await ssrModule.renderPage(pathnameOf(req.url || '/'), form);
|
|
733
778
|
await sendPage(req, res, ssrModule, hookCtx, page, pathnameOf(req.url || '/'));
|
|
734
779
|
} catch (err) {
|
|
@@ -797,7 +842,7 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
|
|
|
797
842
|
};
|
|
798
843
|
const fileHeaders: Record<string, string> = {
|
|
799
844
|
'Content-Type': types[ext] || 'application/octet-stream',
|
|
800
|
-
'Cache-Control': rev ? `public, max-age=0, stale-while-revalidate=${rev.seconds}` : 'public, max-age=3600',
|
|
845
|
+
'Cache-Control': devMode ? 'no-cache' : rev ? `public, max-age=0, stale-while-revalidate=${rev.seconds}` : 'public, max-age=3600',
|
|
801
846
|
'ETag': entry.etag,
|
|
802
847
|
'Vary': 'Accept-Encoding',
|
|
803
848
|
};
|
|
@@ -871,7 +916,10 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
|
|
|
871
916
|
done();
|
|
872
917
|
return;
|
|
873
918
|
}
|
|
874
|
-
const
|
|
919
|
+
const hasQuery = (req.url || '').includes('?');
|
|
920
|
+
const page = req.method === 'GET' && !hasQuery && ssrModule.renderPageCached
|
|
921
|
+
? await ssrModule.renderPageCached(safe2, String(req.headers.cookie || ''))
|
|
922
|
+
: await ssrModule.renderPage(safe2);
|
|
875
923
|
await sendPage(req, res, ssrModule, hookCtx, page, safe2);
|
|
876
924
|
}).catch((err: unknown) => {
|
|
877
925
|
console.error(`rosetack: ${req.method} ${req.url} failed:`, err instanceof Error ? err.stack ?? err.message : err);
|
|
@@ -881,14 +929,31 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
|
|
|
881
929
|
}
|
|
882
930
|
res.statusCode = 500;
|
|
883
931
|
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
884
|
-
|
|
932
|
+
const devErr = err as { file?: string; line?: number | string; hint?: string };
|
|
933
|
+
let devDetail = '';
|
|
934
|
+
if (process.env.rosetack_DEV === '1' && err) {
|
|
935
|
+
const stack = err instanceof Error ? (err.stack || '').split('\n').slice(1, 7).join('\n') : '';
|
|
936
|
+
devDetail =
|
|
937
|
+
'<div style="margin:24px auto;max-width:860px;font:13px/1.6 ui-monospace,monospace;background:#1b1b1f;color:#e6e6ea;border:1px solid #3a3a42;border-radius:10px;padding:20px 24px;text-align:left;white-space:pre-wrap;word-break:break-word">' +
|
|
938
|
+
'<div style="font:600 15px/1.4 system-ui,sans-serif;color:#ff8b8b">Render failed: ' + escapeHtml(req.url || '') + '</div>' +
|
|
939
|
+
'<div style="margin:10px 0 0;color:#ffd479">' + escapeHtml(err instanceof Error ? err.message : err) + '</div>' +
|
|
940
|
+
(devErr.file ? '<div style="margin:6px 0 0;color:#9ad1ff">' + escapeHtml(devErr.file) + (devErr.line != null ? ':' + devErr.line : '') + '</div>' : '') +
|
|
941
|
+
(devErr.hint ? '<div style="margin:10px 0 0;color:#9fe8b0">Fix: ' + escapeHtml(devErr.hint) + '</div>' : '') +
|
|
942
|
+
(stack ? '<pre style="margin:12px 0 0;color:#8f8f9a">' + escapeHtml(stack) + '</pre>' : '') +
|
|
943
|
+
'</div>';
|
|
944
|
+
}
|
|
945
|
+
res.end('<h1>500</h1><p>Something went wrong rendering this page.</p>' + devDetail);
|
|
885
946
|
});
|
|
886
947
|
};
|
|
887
948
|
}
|
|
888
949
|
|
|
950
|
+
/** HTML-escape for the dev error overlay (F10). */
|
|
951
|
+
function escapeHtml(v: unknown): string {
|
|
952
|
+
return String(v ?? '').replace(/[<>&"]/g, (ch) => ({ '<': '<', '>': '>', '&': '&', '"': '"' }[ch] as string));
|
|
953
|
+
}
|
|
954
|
+
|
|
889
955
|
/** Strip the query string: routing matches the pathname, handlers read the full URL. */
|
|
890
|
-
function pathnameOf(url: string | undefined): string {
|
|
891
|
-
try {
|
|
956
|
+
function pathnameOf(url: string | undefined): string { try {
|
|
892
957
|
return new URL(url || '/', 'http://localhost').pathname;
|
|
893
958
|
} catch {
|
|
894
959
|
return (url || '/').split('?')[0];
|
|
@@ -1005,6 +1070,8 @@ function projectTag(): string {
|
|
|
1005
1070
|
}
|
|
1006
1071
|
|
|
1007
1072
|
async function dev(): Promise<void> {
|
|
1073
|
+
devMode = true;
|
|
1074
|
+
process.env.rosetack_DEV = '1';
|
|
1008
1075
|
console.log(`🌹 RoseTack v${version()}${projectTag()} dev server starting...`);
|
|
1009
1076
|
try {
|
|
1010
1077
|
await build();
|
|
@@ -1083,12 +1150,87 @@ async function serve(): Promise<void> {
|
|
|
1083
1150
|
},
|
|
1084
1151
|
};
|
|
1085
1152
|
try {
|
|
1086
|
-
await loadServer();
|
|
1153
|
+
const hooksMod = await loadServer();
|
|
1154
|
+
invalidateHook = () => { try { hooksMod.invalidateRenderCache(); } catch { } };
|
|
1087
1155
|
} catch (err) {
|
|
1088
1156
|
console.error('rosetack: dist/server.js failed to load for the serve hooks:', err instanceof Error ? err.message : String(err));
|
|
1089
1157
|
}
|
|
1090
1158
|
const http = await import('node:http');
|
|
1091
|
-
const
|
|
1159
|
+
const edgeReady = createEdgeHandler(OUT_DIR);
|
|
1160
|
+
edgeReady.then(async (handle) => {
|
|
1161
|
+
await ready;
|
|
1162
|
+
for (const r of (serverModule?.dynamicRoutes as string[] | undefined) || []) {
|
|
1163
|
+
if (r.includes(':')) continue;
|
|
1164
|
+
try {
|
|
1165
|
+
const res = await handle(new Request('http://localhost' + r));
|
|
1166
|
+
await res.arrayBuffer();
|
|
1167
|
+
} catch { /* a warm-up failure just means that route renders cold */ }
|
|
1168
|
+
}
|
|
1169
|
+
}).catch(() => {});
|
|
1170
|
+
const baseHandler = withAccessLog(serveStatic(OUT_DIR, true), `w${process.pid}`);
|
|
1171
|
+
const earlyHintLinks: string[] = (() => {
|
|
1172
|
+
try {
|
|
1173
|
+
const html = fs.readFileSync(path.join(OUT_DIR, 'index.html'), 'utf8');
|
|
1174
|
+
const links: string[] = [];
|
|
1175
|
+
for (const m of html.matchAll(/<script[^>]+src="([^"]+)"/g)) {
|
|
1176
|
+
const v = `<${m[1]}>; rel=preload; as=script`;
|
|
1177
|
+
if (!links.includes(v)) links.push(v);
|
|
1178
|
+
}
|
|
1179
|
+
for (const m of html.matchAll(/<link[^>]+rel="stylesheet"[^>]*>/g)) {
|
|
1180
|
+
const href = /href="([^"]+)"/.exec(m[0])?.[1];
|
|
1181
|
+
if (href) { const v = `<${href}>; rel=preload; as=style`; if (!links.includes(v)) links.push(v); }
|
|
1182
|
+
}
|
|
1183
|
+
for (const m of html.matchAll(/<link[^>]+href="([^"]+)"[^>]+rel="stylesheet"[^>]*>/g)) {
|
|
1184
|
+
const v = `<${m[1]}>; rel=preload; as=style`;
|
|
1185
|
+
if (!links.includes(v)) links.push(v);
|
|
1186
|
+
}
|
|
1187
|
+
return links;
|
|
1188
|
+
} catch { return []; }
|
|
1189
|
+
})();
|
|
1190
|
+
let dynRouteSet: Set<string> | null = null;
|
|
1191
|
+
const dynRoutesOf = (): Set<string> => {
|
|
1192
|
+
const list = (serverModule?.dynamicRoutes as string[] | undefined) || [];
|
|
1193
|
+
if (!dynRouteSet || dynRouteSet.size !== list.length) dynRouteSet = new Set(list);
|
|
1194
|
+
return dynRouteSet;
|
|
1195
|
+
};
|
|
1196
|
+
const server = http.createServer(async (req: any, res: any) => {
|
|
1197
|
+
try {
|
|
1198
|
+
if ((req.method === 'GET' || req.method === 'HEAD') && dynRoutesOf().has(pathnameOf(req.url || '/'))) {
|
|
1199
|
+
const handle = await edgeReady;
|
|
1200
|
+
if (earlyHintLinks.length && req.method === 'GET' && String(req.headers.accept ?? '').includes('text/html')) {
|
|
1201
|
+
try { res.writeEarlyHints({ link: earlyHintLinks }); } catch { /* client gone: the render still finishes */ }
|
|
1202
|
+
}
|
|
1203
|
+
const url = 'http://' + (req.headers.host || `localhost:${PORT}`) + (req.url || '/');
|
|
1204
|
+
const response = await handle(new Request(url, { method: req.method, headers: req.headers }));
|
|
1205
|
+
res.statusCode = response.status;
|
|
1206
|
+
response.headers.forEach((v: string, k: string) => res.setHeader(k, v));
|
|
1207
|
+
const htmlDoc = (response.headers.get('content-type') ?? '').startsWith('text/html');
|
|
1208
|
+
const enc = htmlDoc && req.method === 'GET' ? pickEncoding(req) : null;
|
|
1209
|
+
if (response.body && enc) {
|
|
1210
|
+
const raw = Buffer.from(await response.arrayBuffer());
|
|
1211
|
+
const etag = 'W/"' + createHash('sha1').update(raw).digest('base64url').slice(0, 24) + '"';
|
|
1212
|
+
if (req.headers['if-none-match'] === etag) {
|
|
1213
|
+
res.statusCode = 304;
|
|
1214
|
+
res.end();
|
|
1215
|
+
return;
|
|
1216
|
+
}
|
|
1217
|
+
const body = compress(enc, raw);
|
|
1218
|
+
res.setHeader('ETag', etag);
|
|
1219
|
+
res.setHeader('Content-Encoding', enc);
|
|
1220
|
+
res.setHeader('Content-Length', String(body.length));
|
|
1221
|
+
res.end(body);
|
|
1222
|
+
return;
|
|
1223
|
+
}
|
|
1224
|
+
if (response.body) {
|
|
1225
|
+
Readable.fromWeb(response.body as any).pipe(res);
|
|
1226
|
+
} else {
|
|
1227
|
+
res.end();
|
|
1228
|
+
}
|
|
1229
|
+
return;
|
|
1230
|
+
}
|
|
1231
|
+
} catch { /* any edge hiccup falls through to the proven pipeline */ }
|
|
1232
|
+
baseHandler(req, res);
|
|
1233
|
+
});
|
|
1092
1234
|
server.requestTimeout = 30_000;
|
|
1093
1235
|
server.headersTimeout = 65_000;
|
|
1094
1236
|
server.keepAliveTimeout = 5_000;
|