rosetack 0.1.2 → 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/deploy/cloudflare/functions/[[path]].ts +61 -0
- package/deploy/cloudflare/wrangler.toml +14 -0
- package/deploy/netlify/functions/rosetack.ts +38 -0
- package/deploy/netlify.toml +17 -0
- package/devtools/devtools.html +7 -0
- package/devtools/devtools.js +1 -0
- package/devtools/manifest.json +8 -0
- package/devtools/panel.html +28 -0
- package/devtools/panel.js +54 -0
- package/dist-cli/compiler.mjs +2194 -561
- package/dist-cli/edge.mjs +159 -48
- package/dist-cli/rosetack.mjs +2899 -739
- package/dist-cli/runtime.mjs +305 -43
- package/dist-cli/test.mjs +2332 -630
- package/package.json +4 -3
- package/src/FRAMEWORK_VERSION +1 -1
- package/src/cli/content.ts +186 -0
- package/src/cli/edge.ts +78 -62
- package/src/cli/image-size.ts +83 -0
- package/src/cli/index.ts +391 -334
- package/src/cli/prod-server.ts +324 -0
- package/src/cli/prompt.ts +51 -20
- package/src/cli/shell.ts +105 -74
- package/src/cli/test.ts +9 -70
- package/src/compiler/index.ts +2107 -913
- package/src/runtime/index.ts +367 -168
- package/src/types/rosetack.d.ts +16 -66
- package/templates/admin/package.json +14 -0
- package/templates/admin/rosetack.config.js +1 -0
- package/templates/admin/src/pages/_middleware.rose +33 -0
- package/templates/admin/src/pages/api/items.rose +37 -0
- package/templates/admin/src/pages/api/login.rose +25 -0
- package/templates/admin/src/pages/index.rose +79 -0
- package/templates/api/package.json +14 -0
- package/templates/api/rosetack.config.js +1 -0
- package/templates/api/src/pages/api/health.rose +7 -0
- package/templates/api/src/pages/api/items.rose +46 -0
- package/templates/api/src/pages/api/login.rose +24 -0
- package/templates/api/src/pages/index.rose +25 -0
- package/templates/blog/package.json +14 -0
- package/templates/blog/rosetack.config.js +1 -0
- package/templates/blog/src/pages/404.rose +2 -0
- package/templates/blog/src/pages/_layout.rose +42 -0
- package/templates/blog/src/pages/_middleware.rose +74 -0
- package/templates/blog/src/pages/admin.rose +85 -0
- package/templates/blog/src/pages/api/login.rose +46 -0
- package/templates/blog/src/pages/api/posts/[id].rose +37 -0
- package/templates/blog/src/pages/api/posts.rose +72 -0
- package/templates/blog/src/pages/index.rose +31 -0
- package/templates/blog/src/pages/post/[id].rose +36 -0
- package/templates/site/package.json +14 -0
- package/templates/site/rosetack.config.js +1 -0
- package/templates/site/src/pages/404.rose +2 -0
- package/templates/site/src/pages/_layout.rose +40 -0
- package/templates/site/src/pages/about.rose +6 -0
- package/templates/site/src/pages/index.rose +13 -0
- package/templates/site/src/pages/pricing.rose +8 -0
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
(globalThis as any).__rosetack_SKIP_MINIFY = true;
|
|
2
|
+
|
|
3
|
+
import http from 'node:http';
|
|
4
|
+
import { Readable } from 'node:stream';
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import zlib from 'node:zlib';
|
|
8
|
+
import { createHash } from 'node:crypto';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
import { createEdgeHandler } from './edge.ts';
|
|
11
|
+
|
|
12
|
+
const dist = fileURLToPath(new URL('./', import.meta.url));
|
|
13
|
+
const port = Number(process.env.PORT || 8080);
|
|
14
|
+
let handle: ((request: Request) => Promise<Response>) | null = null;
|
|
15
|
+
let mod: any = null;
|
|
16
|
+
let warmList: string[] = [];
|
|
17
|
+
|
|
18
|
+
const earlyHintLinks: string[] = (() => {
|
|
19
|
+
try {
|
|
20
|
+
const html = fs.readFileSync(path.join(dist, 'index.html'), 'utf8');
|
|
21
|
+
const links: string[] = [];
|
|
22
|
+
for (const m of html.matchAll(/<script[^>]+src="([^"]+)"/g)) {
|
|
23
|
+
const v = `<${m[1]}>; rel=preload; as=script`;
|
|
24
|
+
if (!links.includes(v)) links.push(v);
|
|
25
|
+
}
|
|
26
|
+
for (const m of html.matchAll(/<link[^>]+rel="stylesheet"[^>]*>/g)) {
|
|
27
|
+
const href = /href="([^"]+)"/.exec(m[0])?.[1];
|
|
28
|
+
if (href) { const v = `<${href}>; rel=preload; as=style`; if (!links.includes(v)) links.push(v); }
|
|
29
|
+
}
|
|
30
|
+
for (const m of html.matchAll(/<link[^>]+href="([^"]+)"[^>]+rel="stylesheet"[^>]*>/g)) {
|
|
31
|
+
const v = `<${m[1]}>; rel=preload; as=style`;
|
|
32
|
+
if (!links.includes(v)) links.push(v);
|
|
33
|
+
}
|
|
34
|
+
return links;
|
|
35
|
+
} catch { return []; }
|
|
36
|
+
})();
|
|
37
|
+
|
|
38
|
+
const ready = createEdgeHandler(dist).then(async (h) => {
|
|
39
|
+
handle = h;
|
|
40
|
+
try {
|
|
41
|
+
mod = await import(new URL('./server.js', import.meta.url).href);
|
|
42
|
+
warmList = ['/', ...((mod.dynamicRoutes as string[]) || []).filter((r: string) => !r.includes(':'))];
|
|
43
|
+
} catch { /* warm list stays just the home route */ }
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
const hotCache = new Map<string, { raw: Buffer; br: Buffer; gzip: Buffer; headers: Record<string, string>; etag: string; fetchedAt: number; refreshing?: boolean }>();
|
|
47
|
+
const HOT_TTL = 10_000;
|
|
48
|
+
|
|
49
|
+
function fnv(s: string): string {
|
|
50
|
+
let h = 0x811c9dc5;
|
|
51
|
+
for (let i = 0; i < s.length; i++) {
|
|
52
|
+
h ^= s.charCodeAt(i);
|
|
53
|
+
h = (h * 0x01000193) >>> 0;
|
|
54
|
+
}
|
|
55
|
+
return h.toString(16);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async function refetchHot(pathname: string, cookieHeader: string): Promise<void> {
|
|
59
|
+
const headers: Record<string, string> = { 'user-agent': 'rosetack-hot' };
|
|
60
|
+
if (cookieHeader) headers.cookie = cookieHeader;
|
|
61
|
+
const response = await handle!(new Request('http://localhost' + pathname, { headers }));
|
|
62
|
+
const csp = response.headers.get('content-security-policy') || '';
|
|
63
|
+
const key = pathname + '|' + fnv(cookieHeader);
|
|
64
|
+
if (response.status !== 200 || csp.includes('nonce-')) {
|
|
65
|
+
hotCache.delete(key);
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
const head: Record<string, string> = {};
|
|
69
|
+
response.headers.forEach((v, k) => { if (k !== 'content-length' && k !== 'date' && k !== 'content-encoding') head[k] = v; });
|
|
70
|
+
const raw = Buffer.from(await response.arrayBuffer());
|
|
71
|
+
const compressed = raw.length > 1024;
|
|
72
|
+
hotCache.set(key, {
|
|
73
|
+
raw,
|
|
74
|
+
br: compressed ? zlib.brotliCompressSync(raw) : raw,
|
|
75
|
+
gzip: compressed ? zlib.gzipSync(raw, { level: 9 }) : raw,
|
|
76
|
+
compressed,
|
|
77
|
+
headers: head,
|
|
78
|
+
etag: `W/"${raw.length}-${fnv(cookieHeader)}"`,
|
|
79
|
+
fetchedAt: Date.now(),
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function warmHot(pathname: string, cookieHeader: string): void {
|
|
84
|
+
refetchHot(pathname, cookieHeader)
|
|
85
|
+
.catch(() => {
|
|
86
|
+
const e = hotCache.get(pathname + '|' + fnv(cookieHeader));
|
|
87
|
+
if (e) { e.refreshing = false; e.fetchedAt = Date.now() - HOT_TTL + 2000; }
|
|
88
|
+
})
|
|
89
|
+
.finally(() => {
|
|
90
|
+
const e = hotCache.get(pathname + '|' + fnv(cookieHeader));
|
|
91
|
+
if (e) e.refreshing = false;
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function tryHot(req: http.IncomingMessage, res: http.ServerResponse): boolean {
|
|
96
|
+
if (req.method !== 'GET') return false;
|
|
97
|
+
const q = req.url || '/';
|
|
98
|
+
const qm = q.indexOf('?');
|
|
99
|
+
if (qm >= 0) return false;
|
|
100
|
+
const cookieHeader = String(req.headers.cookie || '');
|
|
101
|
+
const key = q + '|' + fnv(cookieHeader);
|
|
102
|
+
const entry = hotCache.get(key);
|
|
103
|
+
if (!entry) return false;
|
|
104
|
+
const age = Date.now() - entry.fetchedAt;
|
|
105
|
+
if (age > HOT_TTL && !entry.refreshing) {
|
|
106
|
+
entry.refreshing = true;
|
|
107
|
+
warmHot(q, cookieHeader);
|
|
108
|
+
}
|
|
109
|
+
res.statusCode = 200;
|
|
110
|
+
for (const k in entry.headers) res.setHeader(k, entry.headers[k]);
|
|
111
|
+
res.setHeader('ETag', entry.etag);
|
|
112
|
+
if (req.headers['if-none-match'] === entry.etag) {
|
|
113
|
+
res.statusCode = 304;
|
|
114
|
+
res.end();
|
|
115
|
+
return true;
|
|
116
|
+
}
|
|
117
|
+
const compressed = (entry as any).compressed !== false;
|
|
118
|
+
const accept = String(req.headers['accept-encoding'] || '');
|
|
119
|
+
const enc = compressed ? (/br\b/i.test(accept) ? 'br' : /gzip\b/i.test(accept) ? 'gzip' : null) : null;
|
|
120
|
+
if (enc) {
|
|
121
|
+
res.setHeader('Content-Encoding', enc);
|
|
122
|
+
res.end(enc === 'br' ? entry.br : entry.gzip);
|
|
123
|
+
} else {
|
|
124
|
+
res.end(entry.raw);
|
|
125
|
+
}
|
|
126
|
+
return true;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function fillHot(pathname: string, cookieHeader: string, response: Response): void {
|
|
130
|
+
const csp = response.headers.get('content-security-policy') || '';
|
|
131
|
+
if (response.status !== 200 || csp.includes('nonce-')) return;
|
|
132
|
+
const head: Record<string, string> = {};
|
|
133
|
+
response.headers.forEach((v, k) => { if (k !== 'content-length' && k !== 'date' && k !== 'content-encoding') head[k] = v; });
|
|
134
|
+
response.arrayBuffer().then((ab) => {
|
|
135
|
+
const raw = Buffer.from(ab);
|
|
136
|
+
hotCache.set(pathname + '|' + fnv(cookieHeader), {
|
|
137
|
+
raw,
|
|
138
|
+
compressed: raw.length > 1024,
|
|
139
|
+
br: raw.length > 1024 ? zlib.brotliCompressSync(raw) : raw,
|
|
140
|
+
gzip: raw.length > 1024 ? zlib.gzipSync(raw, { level: 9 }) : raw,
|
|
141
|
+
headers: head,
|
|
142
|
+
etag: `W/"${raw.length}-${fnv(cookieHeader)}"`,
|
|
143
|
+
fetchedAt: Date.now(),
|
|
144
|
+
});
|
|
145
|
+
}).catch(() => {});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const fileCache = new Map<string, { raw: Buffer; br: Buffer; gzip: Buffer; etag: string; mtimeMs: number }>();
|
|
149
|
+
const TYPES: Record<string, string> = {
|
|
150
|
+
'.html': 'text/html; charset=utf-8',
|
|
151
|
+
'.js': 'application/javascript; charset=utf-8',
|
|
152
|
+
'.css': 'text/css; charset=utf-8',
|
|
153
|
+
'.json': 'application/json; charset=utf-8',
|
|
154
|
+
'.svg': 'image/svg+xml',
|
|
155
|
+
'.png': 'image/png',
|
|
156
|
+
'.jpg': 'image/jpeg',
|
|
157
|
+
'.webp': 'image/webp',
|
|
158
|
+
'.ico': 'image/x-icon',
|
|
159
|
+
'.woff2': 'font/woff2',
|
|
160
|
+
'.txt': 'text/plain; charset=utf-8',
|
|
161
|
+
'.xml': 'application/xml',
|
|
162
|
+
'.webmanifest': 'application/manifest+json',
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
try {
|
|
166
|
+
const raw = fs.readFileSync(new URL('../.env', import.meta.url), 'utf-8');
|
|
167
|
+
for (const line of raw.split(/\r?\n/)) {
|
|
168
|
+
const t = line.trim();
|
|
169
|
+
if (!t || t.startsWith('#')) continue;
|
|
170
|
+
const eq = t.indexOf('=');
|
|
171
|
+
if (eq <= 0) continue;
|
|
172
|
+
const k = t.slice(0, eq).trim();
|
|
173
|
+
let v = t.slice(eq + 1).trim();
|
|
174
|
+
if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) v = v.slice(1, -1);
|
|
175
|
+
if (!(k in process.env)) process.env[k] = v;
|
|
176
|
+
}
|
|
177
|
+
} catch { /* no .env: fine */ }
|
|
178
|
+
const REVALIDATE_TOKEN = process.env.rosetack_REVALIDATE_TOKEN || '';
|
|
179
|
+
let revalidateMod: any = null;
|
|
180
|
+
|
|
181
|
+
function handleRevalidate(req: http.IncomingMessage, res: http.ServerResponse): boolean {
|
|
182
|
+
if (req.method !== 'POST' || !req.url!.startsWith('/__rosetack/revalidate')) return false;
|
|
183
|
+
if (!REVALIDATE_TOKEN) { res.statusCode = 404; res.end(); return true; }
|
|
184
|
+
if (req.headers['x-rosetack-token'] !== REVALIDATE_TOKEN) {
|
|
185
|
+
res.statusCode = 403; res.setHeader('content-type', 'application/json');
|
|
186
|
+
res.end(JSON.stringify({ error: 'invalid token' })); return true;
|
|
187
|
+
}
|
|
188
|
+
let body = '';
|
|
189
|
+
req.on('data', (c) => { body += c; if (body.length > 1e6) req.destroy(); });
|
|
190
|
+
req.on('end', () => {
|
|
191
|
+
try {
|
|
192
|
+
if (!revalidateMod) revalidateMod = mod;
|
|
193
|
+
const payload = JSON.parse(body || '{}');
|
|
194
|
+
if (payload.all) {
|
|
195
|
+
revalidateMod.invalidateRenderCache();
|
|
196
|
+
res.end(JSON.stringify({ revalidated: true, scope: 'all' }));
|
|
197
|
+
} else {
|
|
198
|
+
let n = 0;
|
|
199
|
+
for (const p of payload.paths || []) n += revalidateMod.invalidatePath(String(p));
|
|
200
|
+
res.end(JSON.stringify({ revalidated: true, paths: (payload.paths || []).length, dropped: n }));
|
|
201
|
+
}
|
|
202
|
+
} catch (e: any) {
|
|
203
|
+
res.statusCode = 400; res.end(JSON.stringify({ error: String(e).slice(0, 120) }));
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
return true;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function serveStatic(req: http.IncomingMessage, res: http.ServerResponse, rawUrl: string): boolean {
|
|
210
|
+
let pathname: string;
|
|
211
|
+
try {
|
|
212
|
+
pathname = decodeURIComponent(new URL('http://localhost' + rawUrl).pathname);
|
|
213
|
+
} catch {
|
|
214
|
+
return false;
|
|
215
|
+
}
|
|
216
|
+
if (pathname.includes('\0') || pathname.includes('..')) return false;
|
|
217
|
+
const filePath = path.join(dist, pathname);
|
|
218
|
+
if (!filePath.startsWith(dist)) return false;
|
|
219
|
+
let st: fs.Stats;
|
|
220
|
+
try {
|
|
221
|
+
st = fs.statSync(filePath);
|
|
222
|
+
if (!st.isFile()) return false;
|
|
223
|
+
} catch {
|
|
224
|
+
return false;
|
|
225
|
+
}
|
|
226
|
+
const ext = path.extname(filePath).toLowerCase();
|
|
227
|
+
if (!TYPES[ext]) return false;
|
|
228
|
+
let entry = fileCache.get(filePath);
|
|
229
|
+
if (!entry || entry.mtimeMs !== st.mtimeMs) {
|
|
230
|
+
const raw = fs.readFileSync(filePath);
|
|
231
|
+
entry = {
|
|
232
|
+
raw,
|
|
233
|
+
compressed: raw.length > 1024,
|
|
234
|
+
br: raw.length > 1024 ? zlib.brotliCompressSync(raw) : raw,
|
|
235
|
+
gzip: raw.length > 1024 ? zlib.gzipSync(raw, { level: 9 }) : raw,
|
|
236
|
+
etag: `W/"${st.size}-${st.mtimeMs}"`,
|
|
237
|
+
mtimeMs: st.mtimeMs,
|
|
238
|
+
};
|
|
239
|
+
fileCache.set(filePath, entry);
|
|
240
|
+
if (fileCache.size > 500) fileCache.delete(fileCache.keys().next().value as string);
|
|
241
|
+
}
|
|
242
|
+
res.statusCode = 200;
|
|
243
|
+
res.setHeader('Content-Type', TYPES[ext]);
|
|
244
|
+
res.setHeader('ETag', entry.etag);
|
|
245
|
+
res.setHeader('Vary', 'Accept-Encoding');
|
|
246
|
+
const isEntryDoc = pathname === '/' || pathname.endsWith('/') || TYPES[ext].startsWith('text/html');
|
|
247
|
+
res.setHeader('Cache-Control', isEntryDoc ? 'public, max-age=0, must-revalidate' : 'public, max-age=3600');
|
|
248
|
+
if (req.headers['if-none-match'] === entry.etag) {
|
|
249
|
+
res.statusCode = 304;
|
|
250
|
+
res.end();
|
|
251
|
+
return true;
|
|
252
|
+
}
|
|
253
|
+
const compressed = (entry as any).compressed !== false;
|
|
254
|
+
const accept = String(req.headers['accept-encoding'] || '');
|
|
255
|
+
const enc = compressed ? (/br\b/i.test(accept) ? 'br' : /gzip\b/i.test(accept) ? 'gzip' : null) : null;
|
|
256
|
+
if (enc) {
|
|
257
|
+
res.setHeader('Content-Encoding', enc);
|
|
258
|
+
res.end(enc === 'br' ? entry.br : entry.gzip);
|
|
259
|
+
} else {
|
|
260
|
+
res.end(entry.raw);
|
|
261
|
+
}
|
|
262
|
+
return true;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
http.createServer(async (req, res) => {
|
|
266
|
+
try {
|
|
267
|
+
await ready;
|
|
268
|
+
if (handleRevalidate(req, res)) return;
|
|
269
|
+
if (hotCache.size > 0 && tryHot(req, res)) return;
|
|
270
|
+
if (req.method === 'GET' && !req.headers.cookie && hotCache.size === 0) {
|
|
271
|
+
for (const r of warmList) warmHot(r, '');
|
|
272
|
+
}
|
|
273
|
+
if (hotCache.size > 0 && tryHot(req, res)) return;
|
|
274
|
+
if (req.method === 'GET' || req.method === 'HEAD') {
|
|
275
|
+
if (serveStatic(req, res, req.url || '/')) return;
|
|
276
|
+
}
|
|
277
|
+
const url = 'http://' + (req.headers.host || `localhost:${port}`) + (req.url || '/');
|
|
278
|
+
const init: RequestInit = { method: req.method, headers: req.headers as any };
|
|
279
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
280
|
+
(init as any).body = Readable.toWeb(req) as any;
|
|
281
|
+
(init as any).duplex = 'half';
|
|
282
|
+
}
|
|
283
|
+
const cookieHeader = String(req.headers.cookie || '');
|
|
284
|
+
if (earlyHintLinks.length && req.method === 'GET' && String(req.headers.accept ?? '').includes('text/html')) {
|
|
285
|
+
try { res.writeEarlyHints({ link: earlyHintLinks }); } catch { /* client gone: the render still finishes */ }
|
|
286
|
+
}
|
|
287
|
+
const response = await handle!(new Request(url, init));
|
|
288
|
+
if (req.method === 'GET') fillHot(req.url || '/', cookieHeader, response.clone());
|
|
289
|
+
res.statusCode = response.status;
|
|
290
|
+
response.headers.forEach((v, k) => res.setHeader(k, v));
|
|
291
|
+
const htmlDoc = (response.headers.get('content-type') ?? '').startsWith('text/html');
|
|
292
|
+
const accept = String(req.headers['accept-encoding'] ?? '');
|
|
293
|
+
if (response.body && htmlDoc && (accept.includes('br') || accept.includes('gzip'))) {
|
|
294
|
+
const raw = Buffer.from(await response.arrayBuffer());
|
|
295
|
+
const etag = 'W/"' + createHash('sha1').update(raw).digest('base64url').slice(0, 24) + '"';
|
|
296
|
+
if (req.method === 'GET' && req.headers['if-none-match'] === etag) {
|
|
297
|
+
res.statusCode = 304;
|
|
298
|
+
res.end();
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
res.setHeader('ETag', etag);
|
|
302
|
+
res.setHeader('Content-Length', String(raw.length));
|
|
303
|
+
if (accept.includes('br')) {
|
|
304
|
+
res.setHeader('Content-Encoding', 'br');
|
|
305
|
+
res.end(zlib.brotliCompressSync(raw));
|
|
306
|
+
} else {
|
|
307
|
+
res.setHeader('Content-Encoding', 'gzip');
|
|
308
|
+
res.end(zlib.gzipSync(raw));
|
|
309
|
+
}
|
|
310
|
+
} else if (response.body) {
|
|
311
|
+
Readable.fromWeb(response.body as any).pipe(res);
|
|
312
|
+
} else {
|
|
313
|
+
res.end();
|
|
314
|
+
}
|
|
315
|
+
} catch (err) {
|
|
316
|
+
if (!res.headersSent) {
|
|
317
|
+
res.statusCode = 500;
|
|
318
|
+
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
|
|
319
|
+
}
|
|
320
|
+
res.end('server error');
|
|
321
|
+
}
|
|
322
|
+
}).listen(port, () => {
|
|
323
|
+
console.log(`🌹 RoseTack prod server on http://localhost:${port}`);
|
|
324
|
+
});
|
package/src/cli/prompt.ts
CHANGED
|
@@ -1,17 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
* The canonical .rose authoring contract, printed by `rosetack prompt`.
|
|
3
|
-
*
|
|
4
|
-
* Why a command and not a doc page: the audience is as often an AI agent as
|
|
5
|
-
* a human, and the agent needs the contract at the moment it writes code,
|
|
6
|
-
* not a URL to go read. One command, stdout, no network - the same shape as
|
|
7
|
-
* every other tool an agent already shells out to.
|
|
8
|
-
*
|
|
9
|
-
* The content is the compiler's actual rules, in the order a page meets
|
|
10
|
-
* them: file layout, the script block, the template, head and styles,
|
|
11
|
-
* events and actions, the exports, the npm boundary, and the error
|
|
12
|
-
* contract. Anything the compiler REFUSES is listed as a rule here, so a
|
|
13
|
-
* correct page compiles on the first try.
|
|
14
|
-
*/
|
|
1
|
+
// The canonical .rose authoring contract, printed by `rosetack prompt`.
|
|
15
2
|
export const AI_PROMPT = `# rosetack authoring contract (printed by \`rosetack prompt\`)
|
|
16
3
|
|
|
17
4
|
rosetack is a zero-hydration web framework: a .rose file compiles to a server
|
|
@@ -47,7 +34,7 @@ the smallest thing that works - the compiler decides what ships.
|
|
|
47
34
|
<h1>Posts</h1>
|
|
48
35
|
<p>Total: {total}</p>
|
|
49
36
|
<button on:click={() => $setState('count', count() + 1)}>+1</button>
|
|
50
|
-
<form method="POST"><
|
|
37
|
+
<form method="POST"><input type="hidden" name="__action" value="like"><button type="submit">Like</button></form>
|
|
51
38
|
\`\`\`
|
|
52
39
|
|
|
53
40
|
Rules the compiler enforces (breaking one fails the build):
|
|
@@ -56,6 +43,9 @@ Rules the compiler enforces (breaking one fails the build):
|
|
|
56
43
|
type arguments ($state<Post[]>([])) are all erased from the shipped bundles.
|
|
57
44
|
- $state / $data declarations are top-level statements. The declared name IS the
|
|
58
45
|
getter: write count() in the template and the script, never bare count.
|
|
46
|
+
$persist is $state backed by localStorage: let theme = $persist('light') —
|
|
47
|
+
the value survives reloads (SSR renders the initial; the client re-seeds
|
|
48
|
+
from storage at boot).
|
|
59
49
|
- A route param (pages/blog/[id].rose) is read as state too: declare it
|
|
60
50
|
(\`let id = $state('1')\`) and read id() - the server overwrites the default
|
|
61
51
|
with the URL's value, and export const params = { id: [...] } bakes those
|
|
@@ -64,9 +54,36 @@ Rules the compiler enforces (breaking one fails the build):
|
|
|
64
54
|
synchronously inside its parent. Fetch in the page or the middleware and pass
|
|
65
55
|
the value down as a prop.
|
|
66
56
|
- Template interpolation {expr} is HTML-escaped. {@html expr} is the explicit
|
|
67
|
-
trusted-HTML escape hatch - use it only for content you control.
|
|
68
|
-
-
|
|
69
|
-
|
|
57
|
+
trusted-HTML escape hatch - use it only for content you control. {@const name
|
|
58
|
+
= expr} is a template-level binding: it evaluates once and is visible to every
|
|
59
|
+
expression that follows in the same scope (use it to name a computed value
|
|
60
|
+
inside {#each} without re-evaluating, or to shorten a long expression).
|
|
61
|
+
- Blocks: {#if cond}...{:else if cond2}...{:else}...{/if},
|
|
62
|
+
{#each items as item, i}...{:else}...{/each} (i is the zero-based index, the
|
|
63
|
+
{:else} renders when the list is empty, and the item may be a DESTRUCTURING
|
|
64
|
+
pattern - {#each items as {name, price}} or {#each entries as [k, v]} - the
|
|
65
|
+
body then reads the properties/elements directly),
|
|
66
|
+
{#key expr}...{/key} (re-creates the
|
|
67
|
+
body whenever expr changes), {#boundary}...{:fallback}...{/boundary} (the
|
|
68
|
+
fallback renders on a throw; {$boundaryError()?.message} reads the caught
|
|
69
|
+
error), {#island name="x"}...{/island} (partial hydration) and
|
|
70
|
+
{#defer}...{/defer} (progressive render; hold=N keeps the skeleton up at
|
|
71
|
+
least N ms). {:else} / {:else if} must sit inside an {#if} block.
|
|
72
|
+
- Two-way binding: <input bind:value={q}> / <input type="checkbox"
|
|
73
|
+
bind:checked={on}> / <select bind:value={s}>. Numeric inputs coerce through
|
|
74
|
+
valueAsNumber. Radio groups: <input type="radio" value="free"
|
|
75
|
+
bind:group={plan}> - the group state holds the selected value and every
|
|
76
|
+
radio's checked state follows it. bind:this={ref} captures the ELEMENT into
|
|
77
|
+
a $state slot (declare it: let ref = $state(null)) - call ref().focus() or
|
|
78
|
+
measure it after mount. A bind:* name must be a $state declaration.
|
|
79
|
+
- Conditional attributes: class:NAME={expr} and style:PROP={expr} merge with
|
|
80
|
+
the tag's static class/style into one reactive attribute.
|
|
81
|
+
- Boolean attributes (checked/disabled/...) are presence-correct: a false
|
|
82
|
+
expression omits the attribute entirely.
|
|
83
|
+
- use:NAME attaches a registered element action: directives.NAME = (el, param)
|
|
84
|
+
=> { ...; return { update: (p) => ..., destroy: () => ... } } (or return a
|
|
85
|
+
cleanup function). A reactive param: use:tooltip={text} - the action's
|
|
86
|
+
update half re-runs when text changes; the param arrives JSON-parsed.
|
|
70
87
|
- A <slot> with attributes is a named slot and must declare its name:
|
|
71
88
|
<slot name="row" item={post} />. A named slot must be a DIRECT child of the
|
|
72
89
|
component tag - never inside another element or an {#if}/{#each} block.
|
|
@@ -81,12 +98,26 @@ Rules the compiler enforces (breaking one fails the build):
|
|
|
81
98
|
|
|
82
99
|
## Events and server actions
|
|
83
100
|
|
|
84
|
-
- on:
|
|
85
|
-
the script or an inline arrow:
|
|
101
|
+
- on:EVENT={handler} wires a client event - ANY event, not just click. The
|
|
102
|
+
handler is a named function from the script or an inline arrow:
|
|
103
|
+
on:click={() => $setState('n', n() + 1)}, on:keydown={noteKey}.
|
|
104
|
+
click/input/change/submit ride one delegated listener per event type; every
|
|
105
|
+
other event (keydown, focus, scroll, mouseenter, ...) is bound directly on
|
|
106
|
+
the element by wire(), so no handler is ever silently dead. |window /
|
|
107
|
+
|document move the binding onto the global instead (Escape closes the modal,
|
|
108
|
+
scroll, resize) - one target per handler.
|
|
109
|
+
Modifiers ride the event: on:submit|preventDefault={save} (supported:
|
|
110
|
+
|preventDefault, |stopPropagation, |self - only when the event target IS the
|
|
111
|
+
bound element, |once - unbind after the first run). capture/passive are NOT
|
|
112
|
+
supported: they are listener options and one delegated listener per event
|
|
113
|
+
type cannot carry per-element options.
|
|
86
114
|
- A server action is an exported async function. Call it from a native form
|
|
87
115
|
(method="POST", no JS needed - progressive enhancement) or from any event
|
|
88
116
|
(on:click={like} - one POST, in-place adopt). Its return value is an
|
|
89
117
|
incremental patch: $append(row) / $prepend(row) / $merge({...}).
|
|
118
|
+
- A form selects its action by the __action FIELD: name the function
|
|
119
|
+
\`action\` (the default) or add <input type="hidden" name="__action"
|
|
120
|
+
value="like">. The server reads the field, not the URL.
|
|
90
121
|
- Business failures: throw new ActionError('message', 422, 'field'). It lands
|
|
91
122
|
in ordinary state - $actionError() reads it back, a {#boundary} contains it.
|
|
92
123
|
- beforeAction(name, form) is the per-page guard that vetoes an action.
|