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