prunelle 0.1.1 → 0.6.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.
Files changed (120) hide show
  1. package/llms.txt +130 -38
  2. package/package.json +8 -2
  3. package/src/a11y/declaration.ts +335 -0
  4. package/src/a11y/index.ts +446 -0
  5. package/src/a11y/rgaa-map.ts +184 -0
  6. package/src/attrs.ts +11 -3
  7. package/src/build/bundle.ts +80 -36
  8. package/src/build/client-entries.ts +3 -2
  9. package/src/build/client-plugin.ts +8 -4
  10. package/src/build/client-prune.ts +56 -6
  11. package/src/build/compile.ts +11 -9
  12. package/src/build/ecoindex.ts +229 -0
  13. package/src/build/index.ts +174 -108
  14. package/src/build/islands.ts +2 -2
  15. package/src/build/manifest.ts +66 -5
  16. package/src/build/output.ts +2 -2
  17. package/src/build/plugin-host.ts +92 -33
  18. package/src/build/precompress.ts +15 -2
  19. package/src/build/prerender.ts +128 -46
  20. package/src/build/report.ts +23 -2
  21. package/src/build/resolve.ts +8 -6
  22. package/src/build/routes.ts +175 -10
  23. package/src/build/static.ts +137 -39
  24. package/src/build/status-pages.ts +127 -0
  25. package/src/build/style-bundles.ts +526 -0
  26. package/src/cli/check-forms.ts +561 -0
  27. package/src/cli/check-links.ts +632 -0
  28. package/src/cli/check.ts +75 -20
  29. package/src/cli/commands.ts +85 -4
  30. package/src/cli/docs.ts +402 -0
  31. package/src/cli/inspect.ts +103 -14
  32. package/src/cli/mcp-tools.ts +490 -0
  33. package/src/cli/mcp.ts +205 -0
  34. package/src/cli/new.ts +2 -2
  35. package/src/cli/render.ts +421 -0
  36. package/src/cli/upgrade-names.ts +73 -13
  37. package/src/cli/upgrade.ts +137 -16
  38. package/src/compiler/analyze.ts +42 -9
  39. package/src/compiler/browser-globals.ts +140 -17
  40. package/src/compiler/cacheability.ts +636 -0
  41. package/src/compiler/compliance-rgaa.ts +508 -0
  42. package/src/compiler/compliance.ts +241 -289
  43. package/src/compiler/data-keys.ts +199 -192
  44. package/src/compiler/dev-source.ts +87 -0
  45. package/src/compiler/dom-attrs.ts +138 -65
  46. package/src/compiler/dom.ts +517 -442
  47. package/src/compiler/expr-context.ts +167 -57
  48. package/src/compiler/mistakes.ts +4 -1
  49. package/src/compiler/props.ts +87 -36
  50. package/src/compiler/scope.ts +400 -333
  51. package/src/compiler/server-only.ts +190 -151
  52. package/src/compiler/shared.ts +40 -12
  53. package/src/compiler/signal-reads.ts +6 -2
  54. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  55. package/src/compiler/ssr.ts +218 -87
  56. package/src/dev/error-log.ts +151 -0
  57. package/src/dev/index.ts +84 -34
  58. package/src/dev/open-editor.ts +204 -0
  59. package/src/dev/protocol.ts +1 -0
  60. package/src/dev/reload.ts +5 -3
  61. package/src/dev/supervisor.ts +42 -25
  62. package/src/dev/watchers.ts +47 -11
  63. package/src/dom/action.ts +43 -20
  64. package/src/dom/attrs.ts +15 -3
  65. package/src/dom/extras.ts +28 -12
  66. package/src/dom/index.ts +26 -8
  67. package/src/dom/island.ts +35 -28
  68. package/src/dom/loop.ts +10 -9
  69. package/src/plugins/config.ts +8 -7
  70. package/src/plugins/index.ts +2 -2
  71. package/src/plugins/load.ts +26 -7
  72. package/src/plugins/order.ts +38 -1
  73. package/src/plugins/public.ts +5 -2
  74. package/src/plugins/services.ts +81 -0
  75. package/src/plugins/types.ts +34 -0
  76. package/src/reactivity/graph.ts +10 -0
  77. package/src/reactivity/index.ts +24 -16
  78. package/src/reactivity/selector.ts +31 -4
  79. package/src/reactivity/store.ts +45 -13
  80. package/src/server/action-protect.ts +198 -0
  81. package/src/server/action-registry.ts +1 -1
  82. package/src/server/action.ts +82 -27
  83. package/src/server/assets.ts +34 -2
  84. package/src/server/compress.ts +91 -9
  85. package/src/server/document.ts +25 -10
  86. package/src/server/errors.ts +303 -65
  87. package/src/server/form-schema.ts +343 -0
  88. package/src/server/health.ts +244 -0
  89. package/src/server/http.ts +131 -32
  90. package/src/server/index.ts +231 -261
  91. package/src/server/loader.ts +5 -0
  92. package/src/server/param-matchers.ts +112 -0
  93. package/src/server/plugin-host.ts +123 -88
  94. package/src/server/public.ts +3 -3
  95. package/src/server/rate-limit.ts +58 -35
  96. package/src/server/request-body.ts +1 -1
  97. package/src/server/route-cache.ts +423 -0
  98. package/src/server/route-table.ts +339 -8
  99. package/src/server/router.ts +125 -40
  100. package/src/server/routing.ts +196 -63
  101. package/src/server/security.ts +208 -32
  102. package/src/server/serve-handlers.ts +21 -7
  103. package/src/server/start.ts +60 -16
  104. package/src/server/static-dir.ts +61 -8
  105. package/src/server/stream.ts +41 -22
  106. package/src/ssr/context.ts +85 -3
  107. package/src/ssr/index.ts +130 -3
  108. package/src/ssr/region.ts +31 -19
  109. package/src/test/browser.ts +28 -13
  110. package/src/test/index.ts +97 -12
  111. package/src/ts-plugin/diagnostics.ts +505 -0
  112. package/src/ts-plugin/fixes.ts +364 -0
  113. package/src/ts-plugin/index.ts +194 -0
  114. package/templates/_shared/AGENTS.md +2 -2
  115. package/templates/_shared/mcp.json +11 -0
  116. package/templates/_shared/src/routes/legal.tsx +5 -0
  117. package/templates/_shared/tsconfig.json +5 -0
  118. package/templates/blog/prunelle.config.ts +1 -1
  119. package/templates/blog/src/routes/index.tsx +4 -0
  120. package/ts-plugin.cjs +4277 -0
package/src/cli/new.ts CHANGED
@@ -15,8 +15,8 @@ export interface ScaffoldOptions {
15
15
 
16
16
  const TEMPLATES_DIR = join(import.meta.dir, '../../templates')
17
17
 
18
- // npm leaves any file named `.gitignore` out of a package, so the template stores it under another name.
19
- const RENAMED: Record<string, string> = { gitignore: '.gitignore' }
18
+ // npm leaves dotfiles like `.gitignore` out of a package, so the template stores them without the leading dot.
19
+ const RENAMED: Record<string, string> = { 'gitignore': '.gitignore', 'mcp.json': '.mcp.json' }
20
20
 
21
21
  export function scaffoldProject(targetDir: string, options: ScaffoldOptions = {}): { root: string, files: string[] } {
22
22
  const root = resolve(targetDir)
@@ -0,0 +1,421 @@
1
+ // `prunelle render <url>`: render a route or API endpoint in-process via `testApp()` without binding a port or touching `dist/`.
2
+
3
+ import type { PrunellePlugin } from '../plugins/types'
4
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
5
+ import { join, resolve } from 'node:path'
6
+ import { isNotSourceDir, relPosix, walkFiles } from '../build/files'
7
+ import { processSuffix } from '../build/output'
8
+ import { ensureCacheGitignore } from '../build/precompress'
9
+ import { SERVER_ENTRY_FILE } from '../build/server-entry'
10
+ import { loadConfig } from '../plugins/load'
11
+ import { testApp } from '../test/index'
12
+
13
+ const ABSOLUTE_URL_RE = /^https?:\/\//i
14
+ const CONFIG_FILES = ['prunelle.config.ts', 'prunelle.config.js', 'prunelle.config.mjs'] as const
15
+ const CUSTOM_ROUTES_DIR_RE = /\broutesDir\s*:\s*['"]([^'"]+)['"]/
16
+ const CUSTOM_PUBLIC_DIR_RE = /\bpublicDir\s*:\s*['"]([^'"]+)['"]/
17
+ const SAFE_ORIGIN_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])
18
+ const RENDER_LOCK_STALE_MS = 120_000
19
+ const RENDER_LOCK_TIMEOUT_MS = 60_000
20
+ const RENDER_LOCK_POLL_MS = 25
21
+
22
+ const STATUS_TEXT: Record<number, string> = {
23
+ 200: 'OK',
24
+ 201: 'Created',
25
+ 202: 'Accepted',
26
+ 204: 'No Content',
27
+ 301: 'Moved Permanently',
28
+ 302: 'Found',
29
+ 303: 'See Other',
30
+ 304: 'Not Modified',
31
+ 307: 'Temporary Redirect',
32
+ 308: 'Permanent Redirect',
33
+ 400: 'Bad Request',
34
+ 401: 'Unauthorized',
35
+ 403: 'Forbidden',
36
+ 404: 'Not Found',
37
+ 405: 'Method Not Allowed',
38
+ 409: 'Conflict',
39
+ 413: 'Payload Too Large',
40
+ 422: 'Unprocessable Content',
41
+ 429: 'Too Many Requests',
42
+ 500: 'Internal Server Error',
43
+ 502: 'Bad Gateway',
44
+ 503: 'Service Unavailable',
45
+ }
46
+
47
+ export interface RenderUrlOptions {
48
+ root: string
49
+ url: string
50
+ method?: string | undefined
51
+ body?: string | undefined
52
+ headers?: readonly string[] | undefined
53
+ cookies?: readonly string[] | undefined
54
+ includeHeaders?: boolean | undefined
55
+ fresh?: boolean | undefined
56
+ }
57
+
58
+ export interface RenderUrlResult {
59
+ status: number
60
+ statusText: string
61
+ headers: Record<string, string>
62
+ setCookies: string[]
63
+ body: string
64
+ /** Lossless raw response bytes (for binary responses, `body` holds base64 instead of UTF-8-corrupted text). */
65
+ bodyBytes?: Uint8Array | undefined
66
+ /** True when the response content-type is binary (non-text, non-JSON, non-XML, non-SVG). */
67
+ isBinary?: boolean | undefined
68
+ ok: boolean
69
+ reusedBuild: boolean
70
+ errors: string[]
71
+ }
72
+
73
+ function normalizeTargetUrl(rawUrl: string): string {
74
+ const trimmed = rawUrl.trim()
75
+ if (trimmed.length === 0)
76
+ throw new Error('prunelle render: URL cannot be empty')
77
+
78
+ if (ABSOLUTE_URL_RE.test(trimmed)) {
79
+ try {
80
+ return new URL(trimmed).href
81
+ }
82
+ catch {
83
+ throw new Error(`prunelle render: invalid URL "${rawUrl}"`)
84
+ }
85
+ }
86
+
87
+ const normalized = trimmed.startsWith('/') ? trimmed : `/${trimmed}`
88
+ try {
89
+ void new URL(normalized, 'http://localhost')
90
+ }
91
+ catch {
92
+ throw new Error(`prunelle render: invalid URL "${rawUrl}"`)
93
+ }
94
+ return normalized
95
+ }
96
+
97
+ function buildRequestHeaders(
98
+ rawHeaders: readonly string[] | undefined,
99
+ rawCookies: readonly string[] | undefined,
100
+ method: string,
101
+ targetUrl: string,
102
+ ): Headers {
103
+ const headers = new Headers()
104
+
105
+ for (const raw of rawHeaders ?? []) {
106
+ const colon = raw.indexOf(':')
107
+ if (colon <= 0)
108
+ throw new Error(`prunelle render: invalid header "${raw}" (expected "Name: Value")`)
109
+ const name = raw.slice(0, colon).trim()
110
+ if (name.length === 0)
111
+ throw new Error(`prunelle render: invalid header "${raw}" (expected "Name: Value")`)
112
+ const value = raw.slice(colon + 1).trim()
113
+ headers.append(name, value)
114
+ }
115
+
116
+ if (rawCookies !== undefined && rawCookies.length > 0) {
117
+ const joined = rawCookies.join('; ')
118
+ const existing = headers.get('cookie')
119
+ headers.set('cookie', existing !== null && existing.length > 0 ? `${existing}; ${joined}` : joined)
120
+ }
121
+
122
+ if (!SAFE_ORIGIN_METHODS.has(method) && !headers.has('origin')) {
123
+ const origin = ABSOLUTE_URL_RE.test(targetUrl) ? new URL(targetUrl).origin : 'http://localhost'
124
+ headers.set('origin', origin)
125
+ }
126
+
127
+ return headers
128
+ }
129
+
130
+ function isBinaryContentType(contentType: string | null): boolean {
131
+ if (contentType === null)
132
+ return false
133
+ const mime = (contentType.split(';')[0] ?? '').trim().toLowerCase()
134
+ if (mime === '' || mime.startsWith('text/'))
135
+ return false
136
+ if (mime === 'application/json' || mime.endsWith('+json'))
137
+ return false
138
+ if (mime === 'application/xml' || mime.endsWith('+xml'))
139
+ return false
140
+ if (mime === 'application/javascript' || mime === 'application/ecmascript' || mime === 'application/x-www-form-urlencoded')
141
+ return false
142
+ return true
143
+ }
144
+
145
+ function resolvePluginWatchPaths(plugin: PrunellePlugin, root: string): string[] {
146
+ if (plugin.watchPaths === undefined)
147
+ return []
148
+ try {
149
+ return typeof plugin.watchPaths === 'function' ? plugin.watchPaths(root) : plugin.watchPaths
150
+ }
151
+ catch {
152
+ return []
153
+ }
154
+ }
155
+
156
+ async function collectSourceInputs(root: string): Promise<{ dirs: string[], files: string[] }> {
157
+ const dirs = new Set<string>([
158
+ resolve(root, 'src'),
159
+ resolve(root, 'public'),
160
+ resolve(root, 'content'),
161
+ resolve(root, 'messages'),
162
+ ])
163
+ const files = new Set<string>()
164
+ for (const file of CONFIG_FILES) {
165
+ const full = join(root, file)
166
+ if (!existsSync(full))
167
+ continue
168
+ const text = readFileSync(full, 'utf8')
169
+ const routesMatch = CUSTOM_ROUTES_DIR_RE.exec(text)
170
+ if (routesMatch?.[1] !== undefined)
171
+ dirs.add(resolve(root, routesMatch[1]))
172
+ const publicMatch = CUSTOM_PUBLIC_DIR_RE.exec(text)
173
+ if (publicMatch?.[1] !== undefined)
174
+ dirs.add(resolve(root, publicMatch[1]))
175
+ }
176
+
177
+ try {
178
+ const config = await loadConfig(root)
179
+ if (config.routesDir !== undefined)
180
+ dirs.add(resolve(root, config.routesDir))
181
+ if (config.publicDir !== undefined)
182
+ dirs.add(resolve(root, config.publicDir))
183
+ for (const plugin of config.plugins ?? []) {
184
+ for (const watchPath of resolvePluginWatchPaths(plugin, root)) {
185
+ const full = resolve(root, watchPath)
186
+ const st = statSync(full, { throwIfNoEntry: false })
187
+ if (st?.isFile())
188
+ files.add(full)
189
+ else if (st?.isDirectory())
190
+ dirs.add(full)
191
+ }
192
+ }
193
+ }
194
+ catch {
195
+ // Broken configs will be surfaced cleanly by build(); fall back to static directory scan for the stamp.
196
+ return { dirs: [...dirs], files: [...files] }
197
+ }
198
+
199
+ return { dirs: [...dirs], files: [...files] }
200
+ }
201
+
202
+ async function computeSourceStamp(root: string): Promise<string> {
203
+ const { dirs, files: watchedFiles } = await collectSourceInputs(root)
204
+ const files = new Set<string>(watchedFiles)
205
+
206
+ for (const name of [...CONFIG_FILES, 'package.json']) {
207
+ const full = join(root, name)
208
+ const st = statSync(full, { throwIfNoEntry: false })
209
+ if (st !== undefined && st.isFile())
210
+ files.add(full)
211
+ }
212
+
213
+ for (const dir of dirs) {
214
+ for (const file of walkFiles(dir, { skipDir: isNotSourceDir, keep: entry => entry.isFile() }))
215
+ files.add(file)
216
+ }
217
+
218
+ const entries: string[] = []
219
+ for (const file of files) {
220
+ const st = statSync(file, { throwIfNoEntry: false })
221
+ if (st !== undefined)
222
+ entries.push(`${relPosix(root, file)}:${st.mtimeMs}:${st.size}`)
223
+ }
224
+ entries.sort()
225
+ return entries.join('\n')
226
+ }
227
+
228
+ function isProcessAlive(pid: number): boolean {
229
+ try {
230
+ process.kill(pid, 0)
231
+ return true
232
+ }
233
+ catch (err) {
234
+ return err instanceof Error && 'code' in err && err.code === 'EPERM'
235
+ }
236
+ }
237
+
238
+ function tryClearStaleLock(lockFile: string): void {
239
+ const st = statSync(lockFile, { throwIfNoEntry: false })
240
+ if (st === undefined)
241
+ return
242
+ let pid = Number.NaN
243
+ try {
244
+ pid = Number.parseInt(readFileSync(lockFile, 'utf8').trim(), 10)
245
+ }
246
+ catch {
247
+ return
248
+ }
249
+ const deadForeignPid = Number.isInteger(pid) && pid > 0 && pid !== process.pid && !isProcessAlive(pid)
250
+ const expired = Date.now() - st.mtimeMs > RENDER_LOCK_STALE_MS
251
+ if (deadForeignPid || expired)
252
+ rmSync(lockFile, { force: true })
253
+ }
254
+
255
+ async function acquireRenderLock(cacheRoot: string): Promise<() => void> {
256
+ mkdirSync(cacheRoot, { recursive: true })
257
+ const lockFile = join(cacheRoot, 'render-build.lock')
258
+ const deadline = Date.now() + RENDER_LOCK_TIMEOUT_MS
259
+ while (true) {
260
+ try {
261
+ writeFileSync(lockFile, String(process.pid), { flag: 'wx' })
262
+ return () => {
263
+ rmSync(lockFile, { force: true })
264
+ }
265
+ }
266
+ catch (err) {
267
+ if ((err as NodeJS.ErrnoException).code !== 'EEXIST')
268
+ throw err
269
+ tryClearStaleLock(lockFile)
270
+ if (Date.now() >= deadline)
271
+ throw new Error(`prunelle render: timed out waiting for ${lockFile}: remove the lock file if no other render is running.`)
272
+ await Bun.sleep(RENDER_LOCK_POLL_MS)
273
+ }
274
+ }
275
+ }
276
+
277
+ function writeStampAtomic(stampFile: string, content: string): void {
278
+ const tmpFile = `${stampFile}.${processSuffix()}.tmp`
279
+ writeFileSync(tmpFile, content, 'utf8')
280
+ renameSync(tmpFile, stampFile)
281
+ }
282
+
283
+ function readStamp(stampFile: string): string | undefined {
284
+ if (!existsSync(stampFile))
285
+ return undefined
286
+ try {
287
+ return readFileSync(stampFile, 'utf8')
288
+ }
289
+ catch {
290
+ return undefined
291
+ }
292
+ }
293
+
294
+ function extractResponseHeaders(res: Response): { headers: Record<string, string>, setCookies: string[] } {
295
+ const setCookies = res.headers.getSetCookie?.() ?? []
296
+ const headers: Record<string, string> = {}
297
+ for (const [key, value] of res.headers.entries()) {
298
+ if (key.toLowerCase() === 'set-cookie')
299
+ continue
300
+ headers[key] = value
301
+ }
302
+ return { headers, setCookies }
303
+ }
304
+
305
+ /** Renders a URL against the Prunelle app under `options.root` in-process, reusing a cached build under `.prunelle-cache/render-build` when sources are unchanged. */
306
+ export async function renderUrl(options: RenderUrlOptions): Promise<RenderUrlResult> {
307
+ const root = resolve(options.root)
308
+ const targetUrl = normalizeTargetUrl(options.url)
309
+ const method = options.method !== undefined && options.method.trim().length > 0
310
+ ? options.method.trim().toUpperCase()
311
+ : (options.body !== undefined ? 'POST' : 'GET')
312
+ const headers = buildRequestHeaders(options.headers, options.cookies, method, targetUrl)
313
+
314
+ const cacheRoot = join(root, '.prunelle-cache')
315
+ const renderOutDir = join(cacheRoot, 'render-build')
316
+ const stampFile = join(renderOutDir, '.render-stamp')
317
+ const manifestFile = join(renderOutDir, 'manifest.json')
318
+ const entryFile = join(renderOutDir, 'server', SERVER_ENTRY_FILE)
319
+
320
+ const sourceStamp = await computeSourceStamp(root)
321
+ ensureCacheGitignore(cacheRoot)
322
+ const releaseLock = await acquireRenderLock(cacheRoot)
323
+
324
+ try {
325
+ const canReuse = options.fresh !== true
326
+ && existsSync(manifestFile)
327
+ && existsSync(entryFile)
328
+ && readStamp(stampFile) === sourceStamp
329
+
330
+ const app = await testApp({
331
+ root,
332
+ outDir: renderOutDir,
333
+ prebuilt: canReuse,
334
+ prerender: false,
335
+ })
336
+
337
+ try {
338
+ if (!canReuse)
339
+ writeStampAtomic(stampFile, sourceStamp)
340
+
341
+ const reqInit: RequestInit = method !== 'GET' && method !== 'HEAD' && options.body !== undefined
342
+ ? { method, headers, body: options.body }
343
+ : { method, headers }
344
+ const res = await app.fetch(targetUrl, reqInit)
345
+ const bodyBytes = new Uint8Array(await res.arrayBuffer())
346
+ const isBinary = isBinaryContentType(res.headers.get('content-type'))
347
+ const body = isBinary ? Buffer.from(bodyBytes).toString('base64') : new TextDecoder().decode(bodyBytes)
348
+ const { headers: resHeaders, setCookies } = extractResponseHeaders(res)
349
+ const statusText = res.statusText.length > 0 ? res.statusText : (STATUS_TEXT[res.status] ?? '')
350
+
351
+ return {
352
+ status: res.status,
353
+ statusText,
354
+ headers: resHeaders,
355
+ setCookies,
356
+ body,
357
+ bodyBytes,
358
+ isBinary,
359
+ ok: res.status >= 200 && res.status < 400,
360
+ reusedBuild: canReuse,
361
+ errors: [...app.errors],
362
+ }
363
+ }
364
+ finally {
365
+ await app.dispose()
366
+ }
367
+ }
368
+ finally {
369
+ releaseLock()
370
+ }
371
+ }
372
+
373
+ function formatRenderHeaderBlock(result: RenderUrlResult): string {
374
+ const statusLine = result.statusText.length > 0
375
+ ? `HTTP/1.1 ${result.status} ${result.statusText}`
376
+ : `HTTP/1.1 ${result.status}`
377
+ const lines = [statusLine]
378
+
379
+ for (const [name, value] of Object.entries(result.headers)) {
380
+ if (name.toLowerCase() === 'set-cookie')
381
+ continue
382
+ lines.push(`${name}: ${value}`)
383
+ }
384
+ for (const cookie of result.setCookies)
385
+ lines.push(`set-cookie: ${cookie}`)
386
+
387
+ return `${lines.join('\n')}\n\n`
388
+ }
389
+
390
+ /** Formats a `RenderUrlResult`, prepending the HTTP status line and headers when `includeHeaders` is true (`-i`). */
391
+ export function formatRenderResult(result: RenderUrlResult, includeHeaders: boolean): string {
392
+ if (!includeHeaders)
393
+ return result.body
394
+ return `${formatRenderHeaderBlock(result)}${result.body}`
395
+ }
396
+
397
+ /** Encodes a `RenderUrlResult` as raw bytes so binary payloads (PNG, PDF, WASM, etc.) reach stdout without UTF-8 corruption. */
398
+ export function formatRenderResultBytes(result: RenderUrlResult, includeHeaders: boolean): Uint8Array {
399
+ const payload = result.bodyBytes ?? new TextEncoder().encode(result.body)
400
+ if (!includeHeaders)
401
+ return payload
402
+ const headerBytes = new TextEncoder().encode(formatRenderHeaderBlock(result))
403
+ const combined = new Uint8Array(headerBytes.byteLength + payload.byteLength)
404
+ combined.set(headerBytes, 0)
405
+ combined.set(payload, headerBytes.byteLength)
406
+ return combined
407
+ }
408
+
409
+ /** Writes a `RenderUrlResult` to stdout (or a custom writer), emitting raw bytes for binary responses and UTF-8 text otherwise. */
410
+ export function writeRenderResult(
411
+ result: RenderUrlResult,
412
+ includeHeaders: boolean,
413
+ write: (chunk: string | Uint8Array) => unknown = chunk => process.stdout.write(chunk),
414
+ ): void {
415
+ if (result.isBinary === true) {
416
+ write(formatRenderResultBytes(result, includeHeaders))
417
+ return
418
+ }
419
+ const out = formatRenderResult(result, includeHeaders)
420
+ write(out.endsWith('\n') || out.length === 0 ? out : `${out}\n`)
421
+ }
@@ -6,6 +6,7 @@ import { walk } from '../compiler/ast'
6
6
  import { SourceEditor } from '../compiler/patch'
7
7
 
8
8
  const KAY_SOURCE_RE = /^@kayjs\//
9
+ const REF_TYPES_RE = /^(\s*\/\/\/\s*<reference\s+types=)(["'])([^"']+)\2(\s*\/>)/gm
9
10
 
10
11
  type Import = Extract<AstNode, { type: 'ImportDeclaration' }>
11
12
  type Specifier = Extract<AstNode, { type: 'ImportSpecifier' }>
@@ -25,17 +26,61 @@ export function prunelleName(name: string): string | undefined {
25
26
  }
26
27
 
27
28
  const nameOf = (node: { type: string, name?: string, value?: unknown }): string => node.type === 'Identifier' ? node.name! : String(node.value)
28
- const fromKay = (source: { value: unknown } | null | undefined): boolean => typeof source?.value === 'string' && KAY_SOURCE_RE.test(source.value)
29
29
 
30
- /** Rewrites the names `code` imports from `@kayjs/*`, run before its specifiers are renamed. */
31
- export function renameKayNames(file: string, code: string): string {
32
- if (!code.includes('@kayjs/'))
30
+ function resolveAlias(spec: string, aliases?: ReadonlyMap<string, string>): string | undefined {
31
+ if (aliases === undefined || aliases.size === 0)
32
+ return undefined
33
+ for (const [alias, target] of aliases) {
34
+ if (spec === alias)
35
+ return target
36
+ if (spec.startsWith(`${alias}/`))
37
+ return `${target}${spec.slice(alias.length)}`
38
+ }
39
+ return undefined
40
+ }
41
+
42
+ function hasKaySourceHint(code: string, aliases?: ReadonlyMap<string, string>): boolean {
43
+ if (code.includes('@kayjs/'))
44
+ return true
45
+ if (aliases === undefined || aliases.size === 0)
46
+ return false
47
+ for (const alias of aliases.keys()) {
48
+ if (code.includes(alias))
49
+ return true
50
+ }
51
+ return false
52
+ }
53
+
54
+ function rewriteTripleSlash(code: string, aliases?: ReadonlyMap<string, string>): string {
55
+ if (aliases === undefined || aliases.size === 0 || !code.includes('<reference'))
56
+ return code
57
+ return code.replace(REF_TYPES_RE, (full, pre: string, quote: string, spec: string, post: string) => {
58
+ const target = resolveAlias(spec, aliases)
59
+ return target === undefined ? full : `${pre}${quote}${target}${quote}${post}`
60
+ })
61
+ }
62
+
63
+ /** Rewrites the names `code` imports from `@kayjs/*` (and any npm aliases in `aliases`), plus alias module specifiers, run before `@kayjs/*` specifiers are renamed. */
64
+ export function renameKayNames(file: string, code: string, aliases?: ReadonlyMap<string, string>): string {
65
+ if (!hasKaySourceHint(code, aliases))
33
66
  return code
34
67
  const program = parseTsx(file, code)
35
68
  const editor = new SourceEditor(code)
36
69
  const bindings = new Map<string, Binding>()
37
70
  const namespaces = new Set<string>()
38
71
  const skipped = new Set<number>()
72
+ const patchedSources = new Set<number>()
73
+ const fromKay = (source: { value?: unknown } | null | undefined): boolean =>
74
+ typeof source?.value === 'string' && (KAY_SOURCE_RE.test(source.value) || resolveAlias(source.value, aliases) !== undefined)
75
+ const rewriteSource = (source: { start: number, end: number, value?: unknown } | null | undefined): void => {
76
+ if (source === null || source === undefined || typeof source.value !== 'string' || patchedSources.has(source.start))
77
+ return
78
+ const target = resolveAlias(source.value, aliases)
79
+ if (target === undefined)
80
+ return
81
+ patchedSources.add(source.start)
82
+ editor.replace(source.start + 1, source.end - 1, target)
83
+ }
39
84
  const rename = (node: AstNode): void => {
40
85
  const renamed = node.type === 'Identifier' || node.type === 'JSXIdentifier' ? prunelleName(node.name) : undefined
41
86
  if (renamed !== undefined)
@@ -45,8 +90,11 @@ export function renameKayNames(file: string, code: string): string {
45
90
  for (const stmt of program.body) {
46
91
  if (stmt.type === 'ImportDeclaration' && fromKay(stmt.source))
47
92
  collectImport(stmt, bindings, namespaces)
48
- if (stmt.type === 'TSModuleDeclaration' && stmt.id.type === 'Literal' && fromKay(stmt.id))
49
- renameAugmented(stmt.body, rename)
93
+ if (stmt.type === 'TSModuleDeclaration' && stmt.id.type === 'Literal') {
94
+ rewriteSource(stmt.id)
95
+ if (fromKay(stmt.id))
96
+ renameAugmented(stmt.body, rename)
97
+ }
50
98
  }
51
99
 
52
100
  const names = new Set<string>()
@@ -56,13 +104,22 @@ export function renameKayNames(file: string, code: string): string {
56
104
  binding.pinned = true
57
105
  }
58
106
  walk(program.body, (node) => {
59
- if (node.type === 'ImportDeclaration')
107
+ if (node.type === 'ImportDeclaration') {
108
+ rewriteSource(node.source)
60
109
  return false
110
+ }
61
111
  if (node.type === 'ExportNamedDeclaration' && node.source !== null) {
112
+ rewriteSource(node.source)
62
113
  if (fromKay(node.source))
63
114
  reexport(node.specifiers, editor)
64
115
  return false
65
116
  }
117
+ if (node.type === 'ExportAllDeclaration') {
118
+ rewriteSource(node.source)
119
+ return false
120
+ }
121
+ if (node.type === 'ImportExpression' && node.source.type === 'Literal')
122
+ rewriteSource(node.source)
66
123
  // Every keyed node (property, method, class field, type member) names its key, which is no reference.
67
124
  const keyed = node as AstNode & { key?: AstNode & { type: string, name?: string }, computed?: boolean, shorthand?: boolean }
68
125
  if (keyed.key !== undefined && keyed.computed === false) {
@@ -79,11 +136,14 @@ export function renameKayNames(file: string, code: string): string {
79
136
  rename(right)
80
137
  skipped.add(right.start)
81
138
  }
82
- if (node.type === 'TSImportType' && fromKay(node.source) && node.qualifier !== null) {
83
- let head: AstNode = node.qualifier
84
- while (head.type === 'TSQualifiedName')
85
- head = head.left
86
- rename(head)
139
+ if (node.type === 'TSImportType') {
140
+ rewriteSource(node.source)
141
+ if (fromKay(node.source) && node.qualifier !== null) {
142
+ let head: AstNode = node.qualifier
143
+ while (head.type === 'TSQualifiedName')
144
+ head = head.left
145
+ rename(head)
146
+ }
87
147
  }
88
148
  if (node.type === 'ExportSpecifier')
89
149
  pin(nameOf(node.local))
@@ -109,7 +169,7 @@ export function renameKayNames(file: string, code: string): string {
109
169
  for (const ref of binding.refs)
110
170
  editor.replace(ref.start, ref.end, binding.renamed)
111
171
  }
112
- return editor.toString()
172
+ return rewriteTripleSlash(editor.toString(), aliases)
113
173
  }
114
174
 
115
175
  function collectImport(stmt: Import, bindings: Map<string, Binding>, namespaces: Set<string>): void {