prunelle 0.0.0-stage → 0.2.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.
- package/llms.txt +148 -0
- package/package.json +53 -4
- package/src/ambient.d.ts +6 -0
- package/src/attrs.ts +35 -0
- package/src/build/bundle.ts +613 -0
- package/src/build/carry.ts +57 -0
- package/src/build/client-entries.ts +107 -0
- package/src/build/client-plugin.ts +169 -0
- package/src/build/client-prune.ts +118 -0
- package/src/build/compile.ts +128 -0
- package/src/build/files.ts +156 -0
- package/src/build/first-load.ts +164 -0
- package/src/build/graph.ts +247 -0
- package/src/build/index.ts +614 -0
- package/src/build/is-inside.ts +12 -0
- package/src/build/islands.ts +641 -0
- package/src/build/manifest.ts +281 -0
- package/src/build/output.ts +84 -0
- package/src/build/plugin-host.ts +220 -0
- package/src/build/precompress.ts +139 -0
- package/src/build/prerender.ts +150 -0
- package/src/build/render-rules.ts +205 -0
- package/src/build/report.ts +247 -0
- package/src/build/resolve.ts +50 -0
- package/src/build/routes.ts +338 -0
- package/src/build/server-entry.ts +38 -0
- package/src/build/static.ts +163 -0
- package/src/build/status-pages.ts +127 -0
- package/src/cli/check-forms.ts +654 -0
- package/src/cli/check-links.ts +619 -0
- package/src/cli/check.ts +367 -0
- package/src/cli/commands.ts +265 -0
- package/src/cli/index.ts +70 -0
- package/src/cli/inspect.ts +335 -0
- package/src/cli/new.ts +41 -0
- package/src/cli/upgrade-names.ts +209 -0
- package/src/cli/upgrade.ts +354 -0
- package/src/compiler/analyze.ts +618 -0
- package/src/compiler/ast.ts +82 -0
- package/src/compiler/browser-globals.ts +127 -0
- package/src/compiler/compliance-rgaa.ts +502 -0
- package/src/compiler/compliance.ts +497 -0
- package/src/compiler/data-keys.ts +295 -0
- package/src/compiler/dom-attrs.ts +379 -0
- package/src/compiler/dom.ts +566 -0
- package/src/compiler/emit.ts +131 -0
- package/src/compiler/expr-context.ts +408 -0
- package/src/compiler/index.ts +8 -0
- package/src/compiler/interactivity.ts +366 -0
- package/src/compiler/mistakes.ts +499 -0
- package/src/compiler/node-env.ts +50 -0
- package/src/compiler/patch.ts +97 -0
- package/src/compiler/props.ts +460 -0
- package/src/compiler/scope.ts +568 -0
- package/src/compiler/server-only.ts +326 -0
- package/src/compiler/shared.ts +369 -0
- package/src/compiler/signal-reads.ts +242 -0
- package/src/compiler/slots.ts +227 -0
- package/src/compiler/ssr-helpers.ts +555 -0
- package/src/compiler/ssr-island.ts +90 -0
- package/src/compiler/ssr-prunelle-tags.ts +56 -0
- package/src/compiler/ssr.ts +491 -0
- package/src/context.ts +165 -0
- package/src/dev/child.ts +30 -0
- package/src/dev/index.ts +208 -0
- package/src/dev/modules.ts +68 -0
- package/src/dev/protocol.ts +21 -0
- package/src/dev/queue.ts +79 -0
- package/src/dev/reload.ts +157 -0
- package/src/dev/supervisor.ts +187 -0
- package/src/dev/watchers.ts +215 -0
- package/src/dom/action.ts +164 -0
- package/src/dom/attrs.ts +72 -0
- package/src/dom/claim.ts +120 -0
- package/src/dom/extras.ts +562 -0
- package/src/dom/index.ts +289 -0
- package/src/dom/island.ts +284 -0
- package/src/dom/loop.ts +450 -0
- package/src/dom/revive.ts +36 -0
- package/src/index.ts +22 -0
- package/src/jsx-runtime.ts +566 -0
- package/src/plugins/config.ts +86 -0
- package/src/plugins/context.ts +66 -0
- package/src/plugins/index.ts +14 -0
- package/src/plugins/load.ts +70 -0
- package/src/plugins/order.ts +111 -0
- package/src/plugins/public.ts +12 -0
- package/src/plugins/requires.ts +47 -0
- package/src/plugins/services.ts +35 -0
- package/src/plugins/types.ts +242 -0
- package/src/reactivity/graph.ts +249 -0
- package/src/reactivity/index.ts +533 -0
- package/src/reactivity/selector.ts +51 -0
- package/src/reactivity/store.ts +208 -0
- package/src/server/action-protect.ts +186 -0
- package/src/server/action-registry.ts +78 -0
- package/src/server/action.ts +498 -0
- package/src/server/app-entry.ts +23 -0
- package/src/server/assets.ts +136 -0
- package/src/server/compress.ts +560 -0
- package/src/server/consent.ts +253 -0
- package/src/server/cookies.ts +139 -0
- package/src/server/document.ts +271 -0
- package/src/server/env.ts +33 -0
- package/src/server/errors.ts +382 -0
- package/src/server/form-schema.ts +343 -0
- package/src/server/health.ts +244 -0
- package/src/server/http.ts +508 -0
- package/src/server/index.ts +687 -0
- package/src/server/lifecycle.ts +75 -0
- package/src/server/loader.ts +118 -0
- package/src/server/page.ts +107 -0
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +256 -0
- package/src/server/prerendered.ts +71 -0
- package/src/server/public.ts +19 -0
- package/src/server/rate-limit.ts +133 -0
- package/src/server/region.ts +96 -0
- package/src/server/request-body.ts +27 -0
- package/src/server/request-path.ts +73 -0
- package/src/server/request-scope.ts +22 -0
- package/src/server/route-table.ts +82 -0
- package/src/server/router.ts +261 -0
- package/src/server/routing.ts +377 -0
- package/src/server/security.ts +472 -0
- package/src/server/serve-handlers.ts +83 -0
- package/src/server/served-file.ts +128 -0
- package/src/server/standard-schema.ts +87 -0
- package/src/server/start.ts +99 -0
- package/src/server/static-dir.ts +167 -0
- package/src/server/stream.ts +192 -0
- package/src/ssr/context.ts +350 -0
- package/src/ssr/index.ts +596 -0
- package/src/ssr/navigation.ts +96 -0
- package/src/ssr/region.ts +171 -0
- package/src/style.ts +33 -0
- package/src/test/browser.ts +192 -0
- package/src/test/index.ts +191 -0
- package/src/unrenderable.ts +35 -0
- package/templates/_shared/AGENTS.md +10 -0
- package/templates/_shared/CLAUDE.md +1 -0
- package/templates/_shared/gitignore +3 -0
- package/templates/_shared/public/robots.txt +2 -0
- package/templates/_shared/src/routes/legal.tsx +13 -0
- package/templates/_shared/tsconfig.json +20 -0
- package/templates/app/.env.example +4 -0
- package/templates/app/package.json +21 -0
- package/templates/app/prunelle.config.ts +11 -0
- package/templates/app/src/auth.ts +14 -0
- package/templates/app/src/routes/_layout.tsx +32 -0
- package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
- package/templates/app/src/routes/dashboard/index.tsx +13 -0
- package/templates/app/src/routes/index.tsx +15 -0
- package/templates/app/src/routes/login.tsx +34 -0
- package/templates/app/src/styles/app.css +7 -0
- package/templates/app/tests/app.test.ts +32 -0
- package/templates/blog/content/posts/welcome.md +9 -0
- package/templates/blog/package.json +22 -0
- package/templates/blog/prunelle.config.ts +23 -0
- package/templates/blog/src/posts.ts +26 -0
- package/templates/blog/src/routes/_layout.tsx +20 -0
- package/templates/blog/src/routes/blog/[slug].tsx +31 -0
- package/templates/blog/src/routes/index.tsx +33 -0
- package/templates/blog/src/styles/app.css +10 -0
- package/templates/fullstack/package.json +19 -0
- package/templates/fullstack/prunelle.config.ts +6 -0
- package/templates/fullstack/src/actions/greet.ts +19 -0
- package/templates/fullstack/src/components/Counter.tsx +10 -0
- package/templates/fullstack/src/components/GreetForm.tsx +27 -0
- package/templates/fullstack/src/routes/_layout.tsx +14 -0
- package/templates/fullstack/src/routes/api/health.ts +5 -0
- package/templates/fullstack/src/routes/index.tsx +13 -0
- package/templates/fullstack/src/styles/app.css +29 -0
- package/templates/fullstack/tests/app.test.ts +37 -0
- package/templates/minimal/package.json +19 -0
- package/templates/minimal/prunelle.config.ts +6 -0
- package/templates/minimal/src/components/Counter.tsx +10 -0
- package/templates/minimal/src/routes/_layout.tsx +14 -0
- package/templates/minimal/src/routes/index.tsx +11 -0
- package/templates/minimal/src/styles/app.css +22 -0
- package/README.md +0 -3
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// The generated entry files of the client build (the island runtime, the region bundle, one per island) and the hydrate strategies its loader keeps.
|
|
2
|
+
|
|
3
|
+
import type { BundleEnv } from './bundle'
|
|
4
|
+
import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
5
|
+
import { join } from 'node:path'
|
|
6
|
+
|
|
7
|
+
const LEADING_DOT_SLASH_RE = /^\.\//
|
|
8
|
+
|
|
9
|
+
/** The lazy strategies some island of the app hydrates with, so the loader keeps only theirs. A mode computed at runtime (`*`) may be any of them. */
|
|
10
|
+
export function hydrateStrategies(analyses: Iterable<{ defaultHydrate?: string | undefined, hydrateModes: Set<string> }>): { strategies: Record<'visible' | 'idle' | 'interaction' | 'media', boolean>, hasClientOnlyHydrate: boolean } {
|
|
11
|
+
const strategies = { visible: false, idle: false, interaction: false, media: false }
|
|
12
|
+
let hasClientOnlyHydrate = false
|
|
13
|
+
for (const analysis of analyses) {
|
|
14
|
+
for (const mode of [analysis.defaultHydrate, ...analysis.hydrateModes]) {
|
|
15
|
+
const any = mode === '*'
|
|
16
|
+
hasClientOnlyHydrate ||= any || mode === 'client'
|
|
17
|
+
strategies.visible ||= any || mode === 'visible'
|
|
18
|
+
strategies.idle ||= any || mode === 'idle'
|
|
19
|
+
strategies.interaction ||= any || mode === 'interaction'
|
|
20
|
+
strategies.media ||= any || (mode?.startsWith('media(') ?? false)
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return { strategies, hasClientOnlyHydrate }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Another build of the same app (`prunelle build` beside `prunelle dev`) may be reading the file, hence the rename.
|
|
27
|
+
function writeEntry(path: string, contents: string): void {
|
|
28
|
+
if (existsSync(path) && readFileSync(path, 'utf8') === contents)
|
|
29
|
+
return
|
|
30
|
+
const tmpPath = `${path}.${process.pid}.tmp`
|
|
31
|
+
writeFileSync(tmpPath, contents)
|
|
32
|
+
renameSync(tmpPath, path)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface ClientEntryFiles {
|
|
36
|
+
entryPoints: string[]
|
|
37
|
+
islandEntryToKey: Map<string, string>
|
|
38
|
+
runtimeEntryPath: string | undefined
|
|
39
|
+
/** The plugins' `regionClientEntry` modules, bundled apart so only the routes that render a `<Region>` load them. */
|
|
40
|
+
regionEntryPath: string | undefined
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function writeClientEntries(env: BundleEnv, entriesDir: string, options: { pluginClientEntries: string[], regionClientEntries: string[], hasClientOnlyHydrate: boolean, standaloneCss: string[] }): ClientEntryFiles {
|
|
44
|
+
const { pluginClientEntries, regionClientEntries, hasClientOnlyHydrate } = options
|
|
45
|
+
const out: ClientEntryFiles = { entryPoints: [], islandEntryToKey: new Map(), runtimeEntryPath: undefined, regionEntryPath: undefined }
|
|
46
|
+
if (env.islands.targets.size > 0 || pluginClientEntries.length > 0) {
|
|
47
|
+
const runtimeLines: string[] = []
|
|
48
|
+
if (env.islands.targets.size > 0) {
|
|
49
|
+
runtimeLines.push(`import { defineIslandElement } from 'prunelle/internal/island';`)
|
|
50
|
+
runtimeLines.push(`defineIslandElement();`)
|
|
51
|
+
}
|
|
52
|
+
for (const pe of pluginClientEntries)
|
|
53
|
+
runtimeLines.push(`import ${JSON.stringify(pe)};`)
|
|
54
|
+
out.runtimeEntryPath = join(entriesDir, 'runtime.ts')
|
|
55
|
+
writeEntry(out.runtimeEntryPath, `${runtimeLines.join('\n')}\n`)
|
|
56
|
+
out.entryPoints.push(out.runtimeEntryPath)
|
|
57
|
+
}
|
|
58
|
+
if (regionClientEntries.length > 0) {
|
|
59
|
+
out.regionEntryPath = join(entriesDir, 'regions.ts')
|
|
60
|
+
writeEntry(out.regionEntryPath, `${regionClientEntries.map(pe => `import ${JSON.stringify(pe)};`).join('\n')}\n`)
|
|
61
|
+
out.entryPoints.push(out.regionEntryPath)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
out.entryPoints.push(...options.standaloneCss)
|
|
65
|
+
|
|
66
|
+
// Each island hands the loader the DOM runtime its chunk imports anyway, so a page whose islands all wait downloads the loader alone.
|
|
67
|
+
const domExports = `export { hydrate${hasClientOnlyHydrate ? ', mount' : ''} } from 'prunelle/internal/dom';\n`
|
|
68
|
+
for (const [key, target] of env.islands.targets) {
|
|
69
|
+
const entryPath = join(entriesDir, `${target.id}.ts`)
|
|
70
|
+
const exportStmt = target.exportName === 'default'
|
|
71
|
+
? `export { default } from ${JSON.stringify(target.file)};\n`
|
|
72
|
+
: `export { ${target.exportName} as default } from ${JSON.stringify(target.file)};\n`
|
|
73
|
+
writeEntry(entryPath, exportStmt + domExports)
|
|
74
|
+
out.entryPoints.push(entryPath)
|
|
75
|
+
out.islandEntryToKey.set(entryPath, key)
|
|
76
|
+
}
|
|
77
|
+
return out
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** For each JS entry of the client build with static imports, every chunk it imports, transitively: the page preloads them beside the entry, so the browser fetches them at once rather than one level at a time. */
|
|
81
|
+
export function entryStaticImports(metafile: Bun.BuildOutput['metafile'], assetPrefix: string): Record<string, string[]> {
|
|
82
|
+
const deps = new Map<string, string[]>()
|
|
83
|
+
const entries: string[] = []
|
|
84
|
+
for (const [outKey, info] of Object.entries(metafile?.outputs ?? {})) {
|
|
85
|
+
const rel = outKey.replace(LEADING_DOT_SLASH_RE, '')
|
|
86
|
+
if (!rel.endsWith('.js'))
|
|
87
|
+
continue
|
|
88
|
+
deps.set(rel, (info.imports ?? []).filter(imp => imp.kind === 'import-statement').map(imp => imp.path.replace(LEADING_DOT_SLASH_RE, '')))
|
|
89
|
+
if (info.entryPoint !== undefined)
|
|
90
|
+
entries.push(rel)
|
|
91
|
+
}
|
|
92
|
+
const out: Record<string, string[]> = {}
|
|
93
|
+
for (const entry of entries) {
|
|
94
|
+
const seen = new Set<string>()
|
|
95
|
+
const stack = [...deps.get(entry)!]
|
|
96
|
+
while (stack.length > 0) {
|
|
97
|
+
const cur = stack.pop()!
|
|
98
|
+
if (seen.has(cur) || cur === entry)
|
|
99
|
+
continue
|
|
100
|
+
seen.add(cur)
|
|
101
|
+
stack.push(...deps.get(cur) ?? [])
|
|
102
|
+
}
|
|
103
|
+
if (seen.size > 0)
|
|
104
|
+
out[`${assetPrefix}/${entry}`] = [...seen].sort().map(rel => `${assetPrefix}/${rel}`)
|
|
105
|
+
}
|
|
106
|
+
return out
|
|
107
|
+
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
// The Bun plugin of the client build: prunelle specifiers, action stubs, compiled islands, and imports of the `prunelle` barrel pointed at the module holding each name.
|
|
2
|
+
|
|
3
|
+
import type { BunPlugin } from 'bun'
|
|
4
|
+
import type { BuildCache, ModuleGraph } from './graph'
|
|
5
|
+
import type { ActionsByFile } from './islands'
|
|
6
|
+
import { parseSync } from 'oxc-parser'
|
|
7
|
+
import { compileDom } from '../compiler/index'
|
|
8
|
+
import { SERVER_ONLY_FILTER } from '../compiler/server-only'
|
|
9
|
+
import { pruneForClient } from './client-prune'
|
|
10
|
+
import { isInNodeModules, relPosix } from './files'
|
|
11
|
+
import { resolvePrunelleSpecifier } from './resolve'
|
|
12
|
+
|
|
13
|
+
export const PRUNELLE_SPECIFIER_FILTER = /^prunelle(?:\/.*)?$/
|
|
14
|
+
export const TS_FILTER = /\.(?:ts|tsx)$/
|
|
15
|
+
const TS_LANG_RE = /\.[cm]?ts$/i
|
|
16
|
+
|
|
17
|
+
export interface ClientTransforms {
|
|
18
|
+
active: boolean
|
|
19
|
+
key: string
|
|
20
|
+
/** The first hook that threw, named, rethrown once the build is done. */
|
|
21
|
+
failure: Error | undefined
|
|
22
|
+
apply: (code: string, id: string, target: 'server' | 'client') => string
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface ClientPluginEnv {
|
|
26
|
+
root: string
|
|
27
|
+
graph: ModuleGraph
|
|
28
|
+
cache: BuildCache | undefined
|
|
29
|
+
actionsByFile: ActionsByFile
|
|
30
|
+
transforms: ClientTransforms
|
|
31
|
+
/** Collects each server-only import a browser file makes, reported once the build ends. */
|
|
32
|
+
leaks: Set<string>
|
|
33
|
+
/** Per file, the `export { … }` statement naming the islands it does not export itself. */
|
|
34
|
+
localExports: ReadonlyMap<string, string>
|
|
35
|
+
/** Per file the browser loads only for its own islands, the top-level names its client copy keeps. */
|
|
36
|
+
clientKeep: ReadonlyMap<string, ReadonlySet<string>>
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The `export { … }` statement each file needs so the client entry can import the islands the file does not export. */
|
|
40
|
+
export function localIslandExports(targets: Iterable<{ file: string, exportName: string, local?: string | undefined }>): Map<string, string> {
|
|
41
|
+
const names = new Map<string, string[]>()
|
|
42
|
+
for (const t of targets) {
|
|
43
|
+
if (t.local === undefined)
|
|
44
|
+
continue
|
|
45
|
+
const list = names.get(t.file) ?? []
|
|
46
|
+
list.push(t.local === t.exportName ? t.local : `${t.local} as ${t.exportName}`)
|
|
47
|
+
names.set(t.file, list)
|
|
48
|
+
}
|
|
49
|
+
return new Map([...names].map(([file, list]) => [file, `\nexport { ${list.join(', ')} };\n`]))
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Rewrites top-level `import { a, b } from 'prunelle'` statements to import each name from the module declaring it.
|
|
54
|
+
* Through the barrel every island reaches every module it re-exports, and Bun then places a module only some islands use (the action runtime) in the shared chunk in one build and in the island's own chunk in the next (#3598).
|
|
55
|
+
*/
|
|
56
|
+
export function directPrunelleImports(code: string, graph: ModuleGraph, filename = 'module.tsx'): string {
|
|
57
|
+
if (!code.includes('prunelle'))
|
|
58
|
+
return code
|
|
59
|
+
const barrel = resolvePrunelleSpecifier('prunelle')!
|
|
60
|
+
const lang = TS_LANG_RE.test(filename) ? 'ts' : 'tsx'
|
|
61
|
+
const parsed = parseSync(filename, code, { lang, sourceType: 'module' })
|
|
62
|
+
if (parsed.errors.length > 0)
|
|
63
|
+
return code
|
|
64
|
+
|
|
65
|
+
const edits: { start: number, end: number, text: string }[] = []
|
|
66
|
+
for (const stmt of parsed.program.body) {
|
|
67
|
+
if (stmt.type !== 'ImportDeclaration' || stmt.importKind === 'type' || stmt.source.value !== 'prunelle')
|
|
68
|
+
continue
|
|
69
|
+
if (stmt.specifiers.length === 0 || stmt.specifiers.some(s => s.type !== 'ImportSpecifier'))
|
|
70
|
+
continue
|
|
71
|
+
|
|
72
|
+
const byFile = new Map<string, string[]>()
|
|
73
|
+
const kept: string[] = []
|
|
74
|
+
for (const spec of stmt.specifiers) {
|
|
75
|
+
if (spec.type !== 'ImportSpecifier')
|
|
76
|
+
continue
|
|
77
|
+
const imported = spec.imported.type === 'Identifier' ? spec.imported.name : spec.imported.value
|
|
78
|
+
const importedRaw = spec.imported.type === 'Identifier' ? imported : JSON.stringify(imported)
|
|
79
|
+
const local = spec.local.name
|
|
80
|
+
const rawSpec = imported === local && spec.imported.type === 'Identifier' ? local : `${importedRaw} as ${local}`
|
|
81
|
+
if (spec.importKind === 'type') {
|
|
82
|
+
kept.push(`type ${rawSpec}`)
|
|
83
|
+
continue
|
|
84
|
+
}
|
|
85
|
+
const target = graph.exportTarget(barrel, imported)
|
|
86
|
+
if (target.file === barrel) {
|
|
87
|
+
kept.push(rawSpec)
|
|
88
|
+
continue
|
|
89
|
+
}
|
|
90
|
+
const names = byFile.get(target.file) ?? []
|
|
91
|
+
names.push(target.exportName === local ? local : `${target.exportName} as ${local}`)
|
|
92
|
+
byFile.set(target.file, names)
|
|
93
|
+
}
|
|
94
|
+
if (byFile.size === 0)
|
|
95
|
+
continue
|
|
96
|
+
|
|
97
|
+
const lines = [...byFile].map(([file, names]) => `import { ${names.join(', ')} } from ${JSON.stringify(file)};`)
|
|
98
|
+
if (kept.length > 0)
|
|
99
|
+
lines.push(`import { ${kept.join(', ')} } from 'prunelle';`)
|
|
100
|
+
const stmtText = code.slice(stmt.start, stmt.end)
|
|
101
|
+
// Same line count, so later positions in the module stay where they were.
|
|
102
|
+
edits.push({ start: stmt.start, end: stmt.end, text: `${lines.join(' ')}${'\n'.repeat(stmtText.split('\n').length - 1)}` })
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
if (edits.length === 0)
|
|
106
|
+
return code
|
|
107
|
+
let out = ''
|
|
108
|
+
let cursor = 0
|
|
109
|
+
for (const edit of edits) {
|
|
110
|
+
out += code.slice(cursor, edit.start) + edit.text
|
|
111
|
+
cursor = edit.end
|
|
112
|
+
}
|
|
113
|
+
return out + code.slice(cursor)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function clientPlugin(env: ClientPluginEnv): BunPlugin {
|
|
117
|
+
const { root, graph, cache, actionsByFile, transforms, leaks, localExports, clientKeep } = env
|
|
118
|
+
return {
|
|
119
|
+
name: 'prunelle-client',
|
|
120
|
+
setup(b) {
|
|
121
|
+
// Bun swaps node built-ins for empty shims in a browser build, so a server-only import would ship silently.
|
|
122
|
+
b.onResolve({ filter: SERVER_ONLY_FILTER }, (args) => {
|
|
123
|
+
if (!isInNodeModules(args.importer))
|
|
124
|
+
leaks.add(`${relPosix(root, args.importer)} imports server-only module "${args.path}"`)
|
|
125
|
+
return undefined
|
|
126
|
+
})
|
|
127
|
+
b.onResolve({ filter: PRUNELLE_SPECIFIER_FILTER }, (args) => {
|
|
128
|
+
const resolved = resolvePrunelleSpecifier(args.path)
|
|
129
|
+
return resolved !== undefined ? { path: resolved } : undefined
|
|
130
|
+
})
|
|
131
|
+
b.onLoad({ filter: TS_FILTER }, (args) => {
|
|
132
|
+
const actions = actionsByFile.get(args.path)
|
|
133
|
+
if (actions !== undefined) {
|
|
134
|
+
if (graph.analyses.get(args.path)?.isInteractive) {
|
|
135
|
+
leaks.add(`${relPosix(root, args.path)} exports server actions and uses browser interactivity (move actions to a separate non-interactive file)`)
|
|
136
|
+
return undefined
|
|
137
|
+
}
|
|
138
|
+
const lines = [`import { actionStub } from 'prunelle/internal/action';`]
|
|
139
|
+
for (const a of actions)
|
|
140
|
+
lines.push(`export const ${a.exportName} = actionStub(${JSON.stringify(a.url)});`)
|
|
141
|
+
return { contents: `${lines.join('\n')}\n`, loader: 'ts' }
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
if (!args.path.endsWith('.tsx')) {
|
|
145
|
+
const raw = graph.source(args.path)
|
|
146
|
+
const own = transforms.active && !isInNodeModules(args.path) ? transforms.apply(raw, args.path, 'client') : raw
|
|
147
|
+
const direct = directPrunelleImports(own, graph, args.path)
|
|
148
|
+
return direct !== raw ? { contents: direct, loader: 'ts' } : undefined
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const stamp = graph.stamp(args.path)
|
|
152
|
+
const extraExports = localExports.get(args.path) ?? ''
|
|
153
|
+
const keep = clientKeep.get(args.path)
|
|
154
|
+
const key = `${transforms.key}${extraExports}${keep === undefined ? '' : `|keep=${[...keep].sort().join(',')}`}`
|
|
155
|
+
const cachedDom = stamp !== undefined ? cache?.domCompiled.get(args.path) : undefined
|
|
156
|
+
if (cachedDom !== undefined && cachedDom.mtimeMs === stamp!.mtimeMs && cachedDom.size === stamp!.size && (cachedDom.key ?? '') === key)
|
|
157
|
+
return { contents: cachedDom.code, loader: 'tsx' }
|
|
158
|
+
const analysis = graph.analyses.get(args.path)
|
|
159
|
+
const source = graph.source(args.path)
|
|
160
|
+
const clientSource = keep === undefined || analysis === undefined ? source : pruneForClient(source, analysis.program, keep)
|
|
161
|
+
const dom = compileDom(args.path, clientSource, clientSource === source ? { analysis } : {})
|
|
162
|
+
const compiled = directPrunelleImports(transforms.apply(dom.code, args.path, 'client'), graph, args.path) + extraExports
|
|
163
|
+
if (cache !== undefined && stamp !== undefined)
|
|
164
|
+
cache.domCompiled.set(args.path, { mtimeMs: stamp.mtimeMs, size: stamp.size, key, code: compiled })
|
|
165
|
+
return { contents: compiled, loader: 'tsx' }
|
|
166
|
+
})
|
|
167
|
+
},
|
|
168
|
+
}
|
|
169
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// The browser's copy of a module it loads only for the islands declared in it: the code those islands reach, without the server code around them.
|
|
2
|
+
|
|
3
|
+
import type { Declaration, ImportDeclaration, ModuleExportName, Node, Program } from 'oxc-parser'
|
|
4
|
+
import type { ModuleAnalysis } from '../compiler/analyze'
|
|
5
|
+
import { parseTsx } from '../compiler/analyze'
|
|
6
|
+
import { clientReach } from '../compiler/interactivity'
|
|
7
|
+
import { SourceEditor } from '../compiler/patch'
|
|
8
|
+
import { collectPatternNames } from '../compiler/shared'
|
|
9
|
+
|
|
10
|
+
/** The top-level names the browser needs to run the islands `localNames` of a module: the bindings they reach and the imports those name. */
|
|
11
|
+
export function clientNeeds(analysis: Pick<ModuleAnalysis, 'bindings'>, localNames: readonly string[]): Set<string> {
|
|
12
|
+
const keep = new Set<string>()
|
|
13
|
+
for (const b of clientReach(analysis.bindings, localNames)) {
|
|
14
|
+
keep.add(b.name)
|
|
15
|
+
for (const ref of b.refs.keys())
|
|
16
|
+
keep.add(ref)
|
|
17
|
+
}
|
|
18
|
+
return keep
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** The analysis of the client copy `keep` gives, for the walk of what the browser loads: its imports, dynamic imports and program. */
|
|
22
|
+
export function clientView(analysis: ModuleAnalysis, code: string, keep: ReadonlySet<string>): ModuleAnalysis {
|
|
23
|
+
const pruned = pruneForClient(code, analysis.program, keep)
|
|
24
|
+
if (pruned === code)
|
|
25
|
+
return analysis
|
|
26
|
+
const spans = analysis.bindings.filter(b => b.name === '' || keep.has(b.name))
|
|
27
|
+
return {
|
|
28
|
+
...analysis,
|
|
29
|
+
program: parseTsx(analysis.filename, pruned),
|
|
30
|
+
imports: analysis.imports.flatMap((imp) => {
|
|
31
|
+
if (imp.specifiers.length === 0)
|
|
32
|
+
return [imp]
|
|
33
|
+
const specifiers = imp.specifiers.filter(s => keep.has(s.local))
|
|
34
|
+
return specifiers.length === 0 ? [] : [{ ...imp, specifiers }]
|
|
35
|
+
}),
|
|
36
|
+
reexports: [],
|
|
37
|
+
dynamicImports: analysis.dynamicImports.filter(d => spans.some(b => d.start >= b.start && d.start < b.end)),
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** `code` with each top-level declaration, import and re-export outside `keep` removed. Everything else (module-level statements, types) stays. */
|
|
42
|
+
export function pruneForClient(code: string, program: Program, keep: ReadonlySet<string>): string {
|
|
43
|
+
const editor = new SourceEditor(code)
|
|
44
|
+
for (const stmt of program.body) {
|
|
45
|
+
const text = keptText(stmt, code, keep)
|
|
46
|
+
if (text !== undefined)
|
|
47
|
+
editor.replace(stmt.start, stmt.end, text)
|
|
48
|
+
}
|
|
49
|
+
return editor.toString()
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const nameOf = (name: ModuleExportName): string => name.type === 'Identifier' ? name.name : String(name.value)
|
|
53
|
+
|
|
54
|
+
function declaredNames(decl: Declaration): string[] | undefined {
|
|
55
|
+
if (decl.type === 'FunctionDeclaration' || decl.type === 'ClassDeclaration')
|
|
56
|
+
return decl.id === null ? undefined : [decl.id.name]
|
|
57
|
+
if (decl.type !== 'VariableDeclaration')
|
|
58
|
+
return undefined
|
|
59
|
+
const names = new Set<string>()
|
|
60
|
+
for (const d of decl.declarations)
|
|
61
|
+
collectPatternNames(d.id, names)
|
|
62
|
+
return [...names]
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The text replacing a top-level statement: `''` to drop it, `undefined` to leave it as written. */
|
|
66
|
+
function keptText(stmt: Node, code: string, keep: ReadonlySet<string>): string | undefined {
|
|
67
|
+
switch (stmt.type) {
|
|
68
|
+
case 'ImportDeclaration':
|
|
69
|
+
return keptImport(stmt, code, keep)
|
|
70
|
+
case 'FunctionDeclaration':
|
|
71
|
+
case 'ClassDeclaration':
|
|
72
|
+
case 'VariableDeclaration': {
|
|
73
|
+
const names = declaredNames(stmt)
|
|
74
|
+
return names === undefined || names.some(n => keep.has(n)) ? undefined : ''
|
|
75
|
+
}
|
|
76
|
+
case 'ExportNamedDeclaration': {
|
|
77
|
+
if (stmt.exportKind === 'type')
|
|
78
|
+
return undefined
|
|
79
|
+
if (stmt.declaration !== null && stmt.declaration !== undefined) {
|
|
80
|
+
const names = declaredNames(stmt.declaration)
|
|
81
|
+
return names === undefined || names.some(n => keep.has(n)) ? undefined : ''
|
|
82
|
+
}
|
|
83
|
+
if (stmt.source !== null)
|
|
84
|
+
return ''
|
|
85
|
+
const specs = stmt.specifiers.filter(s => keep.has(nameOf(s.local)))
|
|
86
|
+
if (specs.length === stmt.specifiers.length)
|
|
87
|
+
return undefined
|
|
88
|
+
return specs.length === 0 ? '' : `export { ${specs.map(s => code.slice(s.start, s.end)).join(', ')} };`
|
|
89
|
+
}
|
|
90
|
+
case 'ExportDefaultDeclaration': {
|
|
91
|
+
const decl = stmt.declaration
|
|
92
|
+
const name = decl.type === 'Identifier' ? decl.name : (decl.type === 'FunctionDeclaration' || decl.type === 'ClassDeclaration') && decl.id !== null ? decl.id.name : 'default'
|
|
93
|
+
return keep.has(name) ? undefined : ''
|
|
94
|
+
}
|
|
95
|
+
case 'ExportAllDeclaration':
|
|
96
|
+
return stmt.exportKind === 'type' ? undefined : ''
|
|
97
|
+
default:
|
|
98
|
+
return undefined
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function keptImport(stmt: ImportDeclaration, code: string, keep: ReadonlySet<string>): string | undefined {
|
|
103
|
+
// A type import or one with attributes stays as written; a side-effect import keeps all of its zero specifiers.
|
|
104
|
+
if (stmt.importKind === 'type' || (stmt.attributes?.length ?? 0) > 0)
|
|
105
|
+
return undefined
|
|
106
|
+
// A type specifier is erased with the types, so it stays whatever uses it.
|
|
107
|
+
const specs = stmt.specifiers.filter(s => keep.has(s.local.name) || (s.type === 'ImportSpecifier' && s.importKind === 'type'))
|
|
108
|
+
if (specs.length === stmt.specifiers.length)
|
|
109
|
+
return undefined
|
|
110
|
+
const source = code.slice(stmt.source.start, stmt.source.end)
|
|
111
|
+
return specs.map((s) => {
|
|
112
|
+
if (s.type === 'ImportDefaultSpecifier')
|
|
113
|
+
return `import ${s.local.name} from ${source};`
|
|
114
|
+
if (s.type === 'ImportNamespaceSpecifier')
|
|
115
|
+
return `import * as ${s.local.name} from ${source};`
|
|
116
|
+
return `import { ${code.slice(s.start, s.end)} } from ${source};`
|
|
117
|
+
}).join(' ')
|
|
118
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// Single-executable standalone compiler (`prunelle build --compile [outfile]`)
|
|
2
|
+
// Embeds routes, plugins, prerendered HTML, and native zero-copy assets via `with { type: "file" }`.
|
|
3
|
+
|
|
4
|
+
import type { BunPlugin } from 'bun'
|
|
5
|
+
import type { BuildManifest } from './index'
|
|
6
|
+
import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
7
|
+
import { join } from 'node:path'
|
|
8
|
+
import { formatBunBuildLogs } from './files'
|
|
9
|
+
import { SERVER_ENTRY_FILE } from './server-entry'
|
|
10
|
+
|
|
11
|
+
export interface CompileExecutableOptions {
|
|
12
|
+
root: string
|
|
13
|
+
outDir: string
|
|
14
|
+
clientDir: string
|
|
15
|
+
manifest: BuildManifest
|
|
16
|
+
assetPrefix: string
|
|
17
|
+
site?: string | undefined
|
|
18
|
+
outfile: string
|
|
19
|
+
resolvePrunelleSpecifier: (specifier: string) => string | undefined
|
|
20
|
+
bunPlugins?: BunPlugin[] | undefined
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function compileExecutable(opts: CompileExecutableOptions): Promise<void> {
|
|
24
|
+
const { root, outDir, clientDir, manifest, assetPrefix, site, outfile, resolvePrunelleSpecifier, bunPlugins = [] } = opts
|
|
25
|
+
const entryPath = join(outDir, '__compile_entry.ts')
|
|
26
|
+
const prodEnvPath = join(outDir, '__compile_prod_env.ts')
|
|
27
|
+
// Evaluated first via ESM static import order so `prunelle.config.ts` and route modules see NODE_ENV=production!
|
|
28
|
+
writeFileSync(prodEnvPath, `const _envKey = 'NODE_ENV';\nprocess.env[_envKey] ??= 'production';\n`)
|
|
29
|
+
const entryJs = join(outDir, 'server', SERVER_ENTRY_FILE)
|
|
30
|
+
const lifecycle = join(import.meta.dir, '../server/lifecycle.ts')
|
|
31
|
+
const imports: string[] = [`import ${JSON.stringify(prodEnvPath)};`, `import { createApp, prunelleConfig } from ${JSON.stringify(entryJs)};`, `import { handleSignals } from ${JSON.stringify(lifecycle)};`]
|
|
32
|
+
|
|
33
|
+
// Embed client assets, public files and prerendered pages natively via `with { type: "file" }` (0 base64, 0 startup decode!), each with the sidecars the build compressed it into.
|
|
34
|
+
let fileIdx = 0
|
|
35
|
+
const embed = (entries: string[], rel: string, abs: string): void => {
|
|
36
|
+
for (const ext of ['', '.br', '.gz']) {
|
|
37
|
+
if (ext === '' || existsSync(`${abs}${ext}`)) {
|
|
38
|
+
const v = `_f${fileIdx++}`
|
|
39
|
+
imports.push(`import ${v} from ${JSON.stringify(`${abs}${ext}`)} with { type: "file" };`)
|
|
40
|
+
entries.push(`${JSON.stringify(`${rel}${ext}`)}: ${v}`)
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const embeddedAssets: string[] = []
|
|
45
|
+
for (const rel of [...manifest.assets, ...(manifest.carriedAssets ?? [])]) {
|
|
46
|
+
const abs = join(clientDir, rel)
|
|
47
|
+
if (existsSync(abs))
|
|
48
|
+
embed(embeddedAssets, rel, abs)
|
|
49
|
+
}
|
|
50
|
+
const embeddedPublic: string[] = []
|
|
51
|
+
const embeddedPublicEtags: string[] = []
|
|
52
|
+
for (const rel of manifest.publicFiles) {
|
|
53
|
+
const abs = join(outDir, 'public', rel)
|
|
54
|
+
if (!existsSync(abs))
|
|
55
|
+
continue
|
|
56
|
+
embed(embeddedPublic, rel, abs)
|
|
57
|
+
embeddedPublicEtags.push(`${JSON.stringify(rel)}: ${JSON.stringify(`W/"${Bun.hash(readFileSync(abs)).toString(36)}"`)}`)
|
|
58
|
+
}
|
|
59
|
+
const embeddedPrerenderedFiles: string[] = []
|
|
60
|
+
const embeddedPrerenderedEtags: string[] = []
|
|
61
|
+
for (const r of manifest.routes) {
|
|
62
|
+
if (r.prerendered) {
|
|
63
|
+
for (const [, relHtml] of Object.entries(r.prerendered)) {
|
|
64
|
+
const abs = join(outDir, relHtml)
|
|
65
|
+
if (!existsSync(abs))
|
|
66
|
+
continue
|
|
67
|
+
embed(embeddedPrerenderedFiles, relHtml, abs)
|
|
68
|
+
// An embedded file has no mtime to version it by.
|
|
69
|
+
embeddedPrerenderedEtags.push(`${JSON.stringify(relHtml)}: ${JSON.stringify(`W/"${Bun.hash(readFileSync(abs)).toString(36)}"`)}`)
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const siteProp = site !== undefined ? ` site: ${JSON.stringify(site)},` : ''
|
|
75
|
+
const healthPath = `${assetPrefix.replace(/\/$/, '')}/health`
|
|
76
|
+
const code = [
|
|
77
|
+
...imports,
|
|
78
|
+
`const manifest = ${JSON.stringify(manifest)};`,
|
|
79
|
+
`const assets = { ${embeddedAssets.join(', ')} };`,
|
|
80
|
+
`const publicAssets = { ${embeddedPublic.join(', ')} };`,
|
|
81
|
+
`const publicEtags = { ${embeddedPublicEtags.join(', ')} };`,
|
|
82
|
+
`const prerenderedFiles = { ${embeddedPrerenderedFiles.join(', ')} };`,
|
|
83
|
+
`const prerenderedEtags = { ${embeddedPrerenderedEtags.join(', ')} };`,
|
|
84
|
+
`const port = Number(process.env.PORT || prunelleConfig.port || 3000);`,
|
|
85
|
+
`const hostname = process.env.HOST || undefined;`,
|
|
86
|
+
`const formatHost = (h: string) => h.includes(':') && !h.startsWith('[') ? \`[\${h}]\` : h;`,
|
|
87
|
+
`if (Bun.argv.includes('--health')) { const rawHost = !hostname || hostname === '0.0.0.0' || hostname === '::' ? '127.0.0.1' : hostname; const r = await fetch(\`http://\${formatHost(rawHost)}:\${port}\${${JSON.stringify(healthPath)}}\`).catch(() => null); process.exit(r && r.ok ? 0 : 1); }`,
|
|
88
|
+
`const app = await createApp({ assetPrefix: ${JSON.stringify(assetPrefix)},${siteProp} manifest, assets, publicAssets, publicEtags, prerenderedFiles, prerenderedEtags });`,
|
|
89
|
+
`const server = app.serve(port, hostname);`,
|
|
90
|
+
`handleSignals(app, server);`,
|
|
91
|
+
`console.log(\`prunelle server listening on http://\${formatHost(hostname ?? 'localhost')}:\${server.port}\`);`,
|
|
92
|
+
].join('\n')
|
|
93
|
+
|
|
94
|
+
writeFileSync(entryPath, code)
|
|
95
|
+
try {
|
|
96
|
+
const prunelleResolvePlugin: BunPlugin = {
|
|
97
|
+
name: 'prunelle-compile-resolve',
|
|
98
|
+
setup(b) {
|
|
99
|
+
b.onResolve({ filter: /^prunelle(?:\/.*)?$/ }, (args) => {
|
|
100
|
+
const resolved = resolvePrunelleSpecifier(args.path)
|
|
101
|
+
return resolved !== undefined ? { path: resolved } : undefined
|
|
102
|
+
})
|
|
103
|
+
},
|
|
104
|
+
}
|
|
105
|
+
let res: Awaited<ReturnType<typeof Bun.build>>
|
|
106
|
+
try {
|
|
107
|
+
res = await Bun.build({
|
|
108
|
+
entrypoints: [entryPath],
|
|
109
|
+
compile: { outfile },
|
|
110
|
+
minify: true,
|
|
111
|
+
plugins: [prunelleResolvePlugin, ...bunPlugins],
|
|
112
|
+
})
|
|
113
|
+
}
|
|
114
|
+
catch (err) {
|
|
115
|
+
if (err instanceof AggregateError && err.errors.length > 0)
|
|
116
|
+
throw new Error(`prunelle build: --compile failed:\n${formatBunBuildLogs(err.errors, root)}`)
|
|
117
|
+
throw err
|
|
118
|
+
}
|
|
119
|
+
if (!res.success) {
|
|
120
|
+
const msgs = formatBunBuildLogs(res.logs, root)
|
|
121
|
+
throw new Error(`prunelle build: --compile failed:\n${msgs}`)
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
finally {
|
|
125
|
+
rmSync(entryPath, { force: true })
|
|
126
|
+
rmSync(prodEnvPath, { force: true })
|
|
127
|
+
}
|
|
128
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
// File-system helpers of the build: directory walks and the outDir safety check.
|
|
2
|
+
|
|
3
|
+
import type { Dirent } from 'node:fs'
|
|
4
|
+
import { existsSync, readdirSync, realpathSync, statSync } from 'node:fs'
|
|
5
|
+
import { tmpdir } from 'node:os'
|
|
6
|
+
import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
|
|
7
|
+
import { isInside } from './is-inside'
|
|
8
|
+
|
|
9
|
+
const TEST_FILE_RE = /\.(?:test|spec)\.(?:tsx|ts)$/
|
|
10
|
+
const BACKSLASH_RE = /\\/g
|
|
11
|
+
const NODE_MODULES_RE = /[\\/]node_modules[\\/]/
|
|
12
|
+
|
|
13
|
+
/** `relative(from, to)` with forward slashes, the form manifests and messages use. */
|
|
14
|
+
export function relPosix(from: string, to: string): string {
|
|
15
|
+
return relative(from, to).replace(BACKSLASH_RE, '/')
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Whether `file` sits under a `node_modules` folder, with either path separator. */
|
|
19
|
+
export function isInNodeModules(file: string): boolean {
|
|
20
|
+
return NODE_MODULES_RE.test(file)
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function isTsFile(file: string): boolean {
|
|
24
|
+
return file.endsWith('.tsx') || file.endsWith('.ts')
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The size of a file in bytes, or undefined when it does not exist. */
|
|
28
|
+
export function fileSize(file: string): number | undefined {
|
|
29
|
+
try {
|
|
30
|
+
return statSync(file).size
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return undefined
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
interface WalkOptions {
|
|
38
|
+
skipDir?: (name: string) => boolean
|
|
39
|
+
keep?: (entry: Dirent) => boolean
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Every kept file under `dir`, depth first; a missing `dir` is empty. */
|
|
43
|
+
export function walkFiles(dir: string, options: WalkOptions = {}, out: string[] = []): string[] {
|
|
44
|
+
if (!existsSync(dir))
|
|
45
|
+
return out
|
|
46
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
47
|
+
const full = join(dir, entry.name)
|
|
48
|
+
if (entry.isDirectory()) {
|
|
49
|
+
if (options.skipDir?.(entry.name) !== true)
|
|
50
|
+
walkFiles(full, options, out)
|
|
51
|
+
}
|
|
52
|
+
else if (options.keep === undefined || options.keep(entry)) {
|
|
53
|
+
out.push(full)
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return out
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Route sources: `.ts`/`.tsx` outside `_`-prefixed folders, without declarations and tests. */
|
|
60
|
+
export function walkRoutes(dir: string): string[] {
|
|
61
|
+
return walkFiles(dir, {
|
|
62
|
+
skipDir: name => name.startsWith('_'),
|
|
63
|
+
keep: entry => isTsFile(entry.name) && !entry.name.endsWith('.d.ts') && !TEST_FILE_RE.test(entry.name),
|
|
64
|
+
})
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Folders that never hold an app's own source: its dependencies, its build, and dot folders such as `.git` and `.prunelle-cache`. */
|
|
68
|
+
export function isNotSourceDir(name: string): boolean {
|
|
69
|
+
return name === 'node_modules' || name === 'dist' || name.startsWith('.')
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function walkAllFiles(dir: string): string[] {
|
|
73
|
+
return walkFiles(dir, { keep: entry => entry.isFile() })
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
export function assertSafeOutDir(root: string, outDir: string, routesDir: string, publicDir: string): void {
|
|
78
|
+
// Refuse filesystem root, home dir, tmpdir root, or root/ancestors of root
|
|
79
|
+
if (dirname(outDir) === outDir || outDir === tmpdir() || outDir === resolve(process.env.HOME ?? '\0')) {
|
|
80
|
+
throw new Error(`prunelle build: refusing unsafe outDir "${outDir}" — cannot wipe a root or shared system directory.`)
|
|
81
|
+
}
|
|
82
|
+
if (isInside(outDir, root, { orSame: true })) {
|
|
83
|
+
throw new Error(`prunelle build: refusing unsafe outDir "${outDir}" — outDir cannot be or contain project root "${root}".`)
|
|
84
|
+
}
|
|
85
|
+
if (existsSync(outDir)) {
|
|
86
|
+
try {
|
|
87
|
+
const realRoot = realpathSync(root)
|
|
88
|
+
const realOut = realpathSync(outDir)
|
|
89
|
+
if (dirname(realOut) === realOut || isInside(realOut, realRoot, { orSame: true })) {
|
|
90
|
+
throw new Error(`prunelle build: refusing unsafe outDir "${outDir}" — resolved target "${realOut}" is or contains project root "${realRoot}".`)
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
catch (err) {
|
|
94
|
+
if (err instanceof Error && err.message.startsWith('prunelle build: refusing unsafe outDir'))
|
|
95
|
+
throw err
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const protectedTargets: [string, string][] = [
|
|
99
|
+
['src', resolve(root, 'src')],
|
|
100
|
+
['routesDir', routesDir],
|
|
101
|
+
['publicDir', publicDir],
|
|
102
|
+
['prunelle.config.ts', resolve(root, 'prunelle.config.ts')],
|
|
103
|
+
['package.json', resolve(root, 'package.json')],
|
|
104
|
+
]
|
|
105
|
+
for (const [label, target] of protectedTargets) {
|
|
106
|
+
if (isInside(outDir, target, { orSame: true })) {
|
|
107
|
+
throw new Error(`prunelle build: refusing unsafe outDir "${outDir}" — it equals or contains protected path ${label} ("${target}").`)
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
// If outDir is outside root (e.g. an external temp build dir), refuse it if it looks like another project directory.
|
|
111
|
+
if (!isInside(root, outDir) && existsSync(outDir)) {
|
|
112
|
+
for (const marker of ['package.json', 'prunelle.config.ts', 'src']) {
|
|
113
|
+
if (existsSync(join(outDir, marker))) {
|
|
114
|
+
throw new Error(`prunelle build: refusing unsafe external outDir "${outDir}" — it contains "${marker}".`)
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export interface BunBuildLogLike {
|
|
121
|
+
message?: string | undefined
|
|
122
|
+
level?: string | undefined
|
|
123
|
+
position?: {
|
|
124
|
+
file?: string | undefined
|
|
125
|
+
line?: number | undefined
|
|
126
|
+
column?: number | undefined
|
|
127
|
+
length?: number | undefined
|
|
128
|
+
lineText?: string | undefined
|
|
129
|
+
} | null | undefined
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Formats Bun `BuildMessage` / `ResolveMessage` logs with `file:line:col: error|warning: <message>` and a source line frame. */
|
|
133
|
+
export function formatBunBuildLogs(logs: readonly unknown[], root?: string): string {
|
|
134
|
+
return logs.map((raw) => {
|
|
135
|
+
if (raw === null || typeof raw !== 'object')
|
|
136
|
+
return String(raw)
|
|
137
|
+
const log = raw as BunBuildLogLike
|
|
138
|
+
const msg = typeof log.message === 'string' && log.message.length > 0 ? log.message : String(raw)
|
|
139
|
+
const pos = log.position
|
|
140
|
+
if (pos && typeof pos.file === 'string' && pos.file.length > 0 && typeof pos.line === 'number') {
|
|
141
|
+
const file = root !== undefined && isAbsolute(pos.file) ? relPosix(root, pos.file) : pos.file
|
|
142
|
+
const col = typeof pos.column === 'number' && pos.column > 0 ? pos.column : 1
|
|
143
|
+
const severity = log.level === 'warning' ? 'warning' : 'error'
|
|
144
|
+
const header = `${file}:${pos.line}:${col}: ${severity}: ${msg}`
|
|
145
|
+
if (typeof pos.lineText === 'string') {
|
|
146
|
+
const lineStr = String(pos.line)
|
|
147
|
+
const pad = ' '.repeat(lineStr.length)
|
|
148
|
+
const maxSpan = Math.max(1, pos.lineText.length - (col - 1))
|
|
149
|
+
const len = typeof pos.length === 'number' && pos.length > 0 ? Math.min(pos.length, maxSpan) : 1
|
|
150
|
+
return `${header}\n ${lineStr} | ${pos.lineText}\n ${pad} | ${' '.repeat(Math.max(0, col - 1))}${'^'.repeat(len)}`
|
|
151
|
+
}
|
|
152
|
+
return header
|
|
153
|
+
}
|
|
154
|
+
return msg
|
|
155
|
+
}).join('\n')
|
|
156
|
+
}
|