@wular/pnext 0.0.14 → 0.0.15
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/package.json
CHANGED
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
* routes' server modules as soon as the route scan hands them over, and blocks on stdin for the
|
|
21
21
|
* go-ahead to finish the rest once the manifest is written.
|
|
22
22
|
*/
|
|
23
|
-
import { existsSync
|
|
23
|
+
import { existsSync } from 'node:fs'
|
|
24
24
|
import { readFile } from 'node:fs/promises'
|
|
25
25
|
import path from 'node:path'
|
|
26
26
|
import { fileURLToPath } from 'node:url'
|
|
@@ -33,9 +33,8 @@ import {
|
|
|
33
33
|
setEmitCompiledSpecifiersManifest,
|
|
34
34
|
} from '../../runtime/modules'
|
|
35
35
|
import { getCompatModeExtensions } from '../../extensions'
|
|
36
|
-
import { getFontExtensions } from '../../render/hooks'
|
|
37
36
|
import { findConventionFiles, findLayouts } from '../../routing/routes'
|
|
38
|
-
import { registerServerRuntime
|
|
37
|
+
import { registerServerRuntime } from '../../runtime/loader'
|
|
39
38
|
import { namedBunBinary } from '../boot/named-bin'
|
|
40
39
|
import type { VerboseLogger } from '../../utils/verbose'
|
|
41
40
|
import type { BuildManifest } from '../../types'
|
|
@@ -253,17 +252,8 @@ function pageServerFiles(config: ResolvedConfig, routeFiles: Iterable<string>) {
|
|
|
253
252
|
return files
|
|
254
253
|
}
|
|
255
254
|
|
|
256
|
-
const compileServer = (config: ResolvedConfig, file: string
|
|
257
|
-
devServerModuleHref(config, file, 'build',
|
|
258
|
-
conditionTarget: serverBundleTargetForRuntime(runtime || undefined),
|
|
259
|
-
}).then(href => report(compileKey(file, runtime), fileURLToPath(href)))
|
|
260
|
-
|
|
261
|
-
// A finished compile and a finished import are different facts about the same source, and a restart
|
|
262
|
-
// skips by key: reporting a handler's compile under its plain path would mark it imported too, so a
|
|
263
|
-
// crash in ONE handler's import would skip every other handler's import on the next attempt.
|
|
264
|
-
const compileKey = (file: string, runtime: string) => `${runtime}\u0000${file}`
|
|
265
|
-
const splitCompileKey = (key: string) => key.split('\u0000') as [string, string]
|
|
266
|
-
const importKey = (file: string) => `import\u0000${file}`
|
|
255
|
+
const compileServer = (config: ResolvedConfig, file: string) =>
|
|
256
|
+
devServerModuleHref(config, file, 'build').then(href => report(file, fileURLToPath(href)))
|
|
267
257
|
|
|
268
258
|
/**
|
|
269
259
|
* Compile the page routes' server modules from the build's route scan, long before the manifest
|
|
@@ -289,24 +279,19 @@ export async function warmRouteModules(
|
|
|
289
279
|
manifest: BuildManifest,
|
|
290
280
|
skip: ReadonlySet<string> = new Set(),
|
|
291
281
|
) {
|
|
292
|
-
// Every compile below is keyed by runtime as well as file. A module reachable from routes with
|
|
293
|
-
// different `runtime` segments resolves to a different artifact per route, and the renderer asks
|
|
294
|
-
// for the one its route selects — warming only the default target writes artifacts no request
|
|
295
|
-
// ever reads, and leaves the real ones to be compiled against a read-only filesystem.
|
|
296
282
|
const clientFiles = new Set<string>()
|
|
297
283
|
const handlers: BuildManifest['routes'] = []
|
|
298
|
-
const pageRoutes =
|
|
284
|
+
const pageRoutes: string[] = []
|
|
299
285
|
|
|
300
286
|
for (const route of manifest.routes) {
|
|
301
287
|
if (route.kind === 'handler') {
|
|
302
|
-
if (!skip.has(
|
|
288
|
+
if (!skip.has(route.file)) handlers.push(route)
|
|
303
289
|
continue
|
|
304
290
|
}
|
|
305
|
-
|
|
306
|
-
pageRoutes.set(runtime, [...(pageRoutes.get(runtime) ?? []), route.file])
|
|
291
|
+
pageRoutes.push(route.file)
|
|
307
292
|
for (const reference of route.clientReferences) {
|
|
308
293
|
if (ssrClientReference(reference) && existsSync(reference.file)) {
|
|
309
|
-
clientFiles.add(
|
|
294
|
+
clientFiles.add(reference.file)
|
|
310
295
|
}
|
|
311
296
|
}
|
|
312
297
|
}
|
|
@@ -315,29 +300,16 @@ export async function warmRouteModules(
|
|
|
315
300
|
// transforms in memory); the compiled build cache is only used with compat.
|
|
316
301
|
if (getCompatModeExtensions().reactEnabled(config)) {
|
|
317
302
|
await Promise.all([
|
|
318
|
-
...[...
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
.map(file => compileServer(config, file, runtime)),
|
|
322
|
-
),
|
|
323
|
-
// Handlers are compiled here, not left to the import below: the import runs the source through
|
|
324
|
-
// the registered runtime, while a request resolves the route as a compiled module under the
|
|
325
|
-
// condition target its `runtime` segment selects. Only this pass writes THAT artifact, and
|
|
326
|
-
// without it the first request compiles the handler against a read-only filesystem.
|
|
327
|
-
...handlers.map(route =>
|
|
328
|
-
compileServer(config, route.file, route.segmentConfig?.runtime ?? ''),
|
|
329
|
-
),
|
|
303
|
+
...[...pageServerFiles(config, pageRoutes)]
|
|
304
|
+
.filter(file => !skip.has(file))
|
|
305
|
+
.map(file => compileServer(config, file)),
|
|
330
306
|
...[...clientFiles]
|
|
331
|
-
.filter(
|
|
332
|
-
.map(
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
'build',
|
|
338
|
-
serverBundleTargetForRuntime(runtime || undefined),
|
|
339
|
-
).then(href => report(key, fileURLToPath(href)))
|
|
340
|
-
}),
|
|
307
|
+
.filter(file => !skip.has(file))
|
|
308
|
+
.map(file =>
|
|
309
|
+
devClientModuleHref(config, file, 'build').then(href =>
|
|
310
|
+
report(file, fileURLToPath(href)),
|
|
311
|
+
),
|
|
312
|
+
),
|
|
341
313
|
])
|
|
342
314
|
}
|
|
343
315
|
console.log(COMPILED_MARKER)
|
|
@@ -353,68 +325,15 @@ export async function warmRouteModules(
|
|
|
353
325
|
// time, so a handler that takes the process down is unambiguous and a
|
|
354
326
|
// restart must not run it again (Bun caches a failed import for the
|
|
355
327
|
// process' lifetime anyway, so a retry could not succeed either).
|
|
356
|
-
report(
|
|
328
|
+
report(route.file)
|
|
357
329
|
try {
|
|
358
330
|
await import(pathToFileHref(route.file))
|
|
359
331
|
} catch (error) {
|
|
360
332
|
console.warn(`vercel adapter: importing ${route.file} failed during warmup:`, error)
|
|
361
333
|
}
|
|
362
334
|
}
|
|
363
|
-
|
|
364
|
-
await materializeFonts(config, [...pageRoutes.values()].flat())
|
|
365
|
-
}
|
|
366
|
-
|
|
367
|
-
/**
|
|
368
|
-
* `next/font` emits its assets, and records the resolution a render reads, the first time something
|
|
369
|
-
* asks for a font - which on a deployed server is a request, against a read-only filesystem. Fonts are
|
|
370
|
-
* declared at module scope, so evaluating the modules that declare them is enough to register them;
|
|
371
|
-
* the render layer's own prewarm hook then resolves every one while writing still works, leaving the
|
|
372
|
-
* files under the out dir and the resolution in the build's font index. Only layouts are evaluated,
|
|
373
|
-
* not the whole page graph: a font belongs to the document shell, and the rest of the graph running
|
|
374
|
-
* at build time is exactly what this pass avoids.
|
|
375
|
-
*/
|
|
376
|
-
async function materializeFonts(config: ResolvedConfig, pageRoutes: string[]) {
|
|
377
|
-
// Nothing to register, and evaluating an app's layouts for no reason is a compile it never asked
|
|
378
|
-
// for: the font runtime is only in the compiled cache when something in the graph imports
|
|
379
|
-
// `next/font`, which the compile pass above has just settled.
|
|
380
|
-
if (!compiledFontRuntime(config)) return
|
|
381
|
-
const layouts = new Set<string>()
|
|
382
|
-
for (const routeFile of pageRoutes) {
|
|
383
|
-
for (const layout of findLayouts(config.appPath, routeFile)) {
|
|
384
|
-
if (existsSync(layout)) layouts.add(layout)
|
|
385
|
-
}
|
|
386
|
-
}
|
|
387
|
-
for (const file of layouts) {
|
|
388
|
-
try {
|
|
389
|
-
await import(await devServerModuleHref(config, file, 'build'))
|
|
390
|
-
} catch (error) {
|
|
391
|
-
console.warn(`vercel adapter: evaluating ${file} for fonts failed during warmup:`, error)
|
|
392
|
-
}
|
|
393
|
-
}
|
|
394
|
-
await getFontExtensions().prewarmFontAssets(config, { dev: false })
|
|
395
335
|
}
|
|
396
336
|
|
|
397
|
-
/** Whether the compile pass wrote an artifact for the next/font runtime. */
|
|
398
|
-
function compiledFontRuntime(config: ResolvedConfig): boolean {
|
|
399
|
-
const stack = [path.join(config.outPath, 'cache', 'server')]
|
|
400
|
-
while (stack.length > 0) {
|
|
401
|
-
const current = stack.pop()!
|
|
402
|
-
let entries
|
|
403
|
-
try {
|
|
404
|
-
entries = readdirSync(current, { withFileTypes: true })
|
|
405
|
-
} catch {
|
|
406
|
-
continue
|
|
407
|
-
}
|
|
408
|
-
for (const entry of entries) {
|
|
409
|
-
if (entry.isDirectory()) stack.push(path.join(current, entry.name))
|
|
410
|
-
else if (entry.name.startsWith('runtime.') && current.endsWith(FONT_RUNTIME_DIR)) return true
|
|
411
|
-
}
|
|
412
|
-
}
|
|
413
|
-
return false
|
|
414
|
-
}
|
|
415
|
-
|
|
416
|
-
const FONT_RUNTIME_DIR = path.join('compat', 'next', 'font')
|
|
417
|
-
|
|
418
337
|
/**
|
|
419
338
|
* Read the parent's line-delimited requests until the `skip` message, running
|
|
420
339
|
* each prewarm batch as it arrives. Returns the final request.
|
|
@@ -443,9 +362,7 @@ async function readWarmRequests(config: ResolvedConfig): Promise<Partial<WarmReq
|
|
|
443
362
|
|
|
444
363
|
if (import.meta.main) {
|
|
445
364
|
const root = process.argv[2]
|
|
446
|
-
|
|
447
|
-
// top of - same content-addressed path, opened with O_TRUNC, while the parent may be importing it.
|
|
448
|
-
const config = await loadConfig(root, { serve: true })
|
|
365
|
+
const config = await loadConfig(root)
|
|
449
366
|
await bootstrapCompat(config)
|
|
450
367
|
// This process only ever runs for a vercel-adapter build; record each
|
|
451
368
|
// artifact's specifiers so the parent's trace step can read them back.
|
|
@@ -3,7 +3,7 @@ import { existsSync, readFileSync, readdirSync, realpathSync, rmSync, statSync }
|
|
|
3
3
|
import { builtinModules } from 'node:module'
|
|
4
4
|
import path from 'node:path'
|
|
5
5
|
import { fileURLToPath } from 'node:url'
|
|
6
|
-
import { DEFAULT_OUT_DIR,
|
|
6
|
+
import { DEFAULT_OUT_DIR, pathToFileHref } from '../../config'
|
|
7
7
|
import type { ResolvedConfig } from '../../config'
|
|
8
8
|
import { globalCssSources } from '../../css/build'
|
|
9
9
|
import { getImportAliasExtensions } from '../../extensions'
|
|
@@ -19,13 +19,7 @@ import type { BuildManifest, StaticFileMetadata } from '../../types'
|
|
|
19
19
|
|
|
20
20
|
// Vercel unpacks a function's `.func` directory here at runtime. Baked
|
|
21
21
|
// absolute paths in the build output are rewritten to this root.
|
|
22
|
-
|
|
23
|
-
// PNEXT_VERCEL_EMULATE points both this and FUNCTION_PLATFORM at a local path and the host's own
|
|
24
|
-
// platform, so the built function can be run on this machine exactly as the deployment does - the
|
|
25
|
-
// only way to reproduce a request-time failure that needs the function's read-only root.
|
|
26
|
-
// eslint-disable-next-line turbo/no-undeclared-env-vars
|
|
27
|
-
const emulateRoot = process.env.PNEXT_VERCEL_EMULATE
|
|
28
|
-
const RUNTIME_ROOT = emulateRoot ? path.resolve(emulateRoot) : '/var/task'
|
|
22
|
+
const RUNTIME_ROOT = '/var/task'
|
|
29
23
|
|
|
30
24
|
// The single catch-all server function: the same `pnext start` pipeline,
|
|
31
25
|
// running on Vercel's Bun runtime (`"bunVersion": "1.x"` in vercel.json).
|
|
@@ -35,20 +29,12 @@ const SERVER_FUNCTION = '_pnext'
|
|
|
35
29
|
// goes into .vc-config.json and the same target selects the native packages
|
|
36
30
|
// shipped inside it, so the two can never drift. Vercel's default instruction
|
|
37
31
|
// set is x86_64 and its function runtime is glibc-based.
|
|
38
|
-
const FUNCTION_PLATFORM =
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
libc: process.platform === 'darwin' ? '' : 'glibc',
|
|
45
|
-
}
|
|
46
|
-
: ({
|
|
47
|
-
architecture: 'x86_64',
|
|
48
|
-
os: 'linux',
|
|
49
|
-
cpu: 'x64',
|
|
50
|
-
libc: 'glibc',
|
|
51
|
-
} as const)
|
|
32
|
+
const FUNCTION_PLATFORM = {
|
|
33
|
+
architecture: 'x86_64',
|
|
34
|
+
os: 'linux',
|
|
35
|
+
cpu: 'x64',
|
|
36
|
+
libc: 'glibc',
|
|
37
|
+
} as const
|
|
52
38
|
|
|
53
39
|
// Directories that only ever hold build-tool output, pruned at *any* depth. Depth matters: pruning
|
|
54
40
|
// only a package's top level ships every nested one. node_modules and .git are here for the same
|
|
@@ -85,12 +71,6 @@ interface PackRules {
|
|
|
85
71
|
droppedSuffixes: string[]
|
|
86
72
|
/** Absolute sources exempt from the prune list — the app's own build output. */
|
|
87
73
|
keepPaths: Set<string>
|
|
88
|
-
/** Absolute sources dropped even though they sit inside a kept path. */
|
|
89
|
-
dropPaths: Set<string>
|
|
90
|
-
/** Same set as `dropPaths`, by basename — the clone pass walks copies, not sources. */
|
|
91
|
-
dropNames: Set<string>
|
|
92
|
-
/** Resolved out root, so a walk can tell when it is standing exactly on it. */
|
|
93
|
-
outRootPath: string
|
|
94
74
|
}
|
|
95
75
|
|
|
96
76
|
// Test seam: the packing suite builds one app both ways and diffs the trees,
|
|
@@ -106,9 +86,6 @@ export function setPackPruningEnabled(enabled: boolean) {
|
|
|
106
86
|
}
|
|
107
87
|
}
|
|
108
88
|
|
|
109
|
-
// Build-time scratch directories at the top level of the out root.
|
|
110
|
-
const outRootScratch = [devOutSegment, 'typecheck', 'types']
|
|
111
|
-
|
|
112
89
|
function packRules(config: ResolvedConfig): PackRules {
|
|
113
90
|
if (!packPruningEnabled) {
|
|
114
91
|
return {
|
|
@@ -117,9 +94,6 @@ function packRules(config: ResolvedConfig): PackRules {
|
|
|
117
94
|
prunedDirs: new Set(['node_modules', '.git']),
|
|
118
95
|
droppedSuffixes: [],
|
|
119
96
|
keepPaths: new Set([path.resolve(config.outPath)]),
|
|
120
|
-
dropPaths: new Set(),
|
|
121
|
-
dropNames: new Set(),
|
|
122
|
-
outRootPath: path.resolve(config.outRootPath),
|
|
123
97
|
}
|
|
124
98
|
}
|
|
125
99
|
const keep = new Set(config.adapter?.keep ?? [])
|
|
@@ -139,40 +113,13 @@ function packRules(config: ResolvedConfig): PackRules {
|
|
|
139
113
|
// default out root goes with it: a `distDir` app moved its output away, but
|
|
140
114
|
// the next.config bundle the function imports at boot still lives there.
|
|
141
115
|
keepPaths: new Set([path.resolve(config.outPath), path.resolve(config.root, DEFAULT_OUT_DIR)]),
|
|
142
|
-
// Kept because they sit inside the out dir, shipped because nothing prunes
|
|
143
|
-
// within a kept path — but a dev server's scratch tree (tens of MB on a
|
|
144
|
-
// machine that ran `pnext dev`), the typecheck scratch and the generated
|
|
145
|
-
// types are all build-time only, and the bun1.x function has a 150 MiB cap.
|
|
146
|
-
// Absolute, not by name: `types` and `dist` are ordinary directory names in
|
|
147
|
-
// a dependency, and only these exact ones are build scratch.
|
|
148
|
-
dropPaths: new Set(outRootScratch.map(name => path.resolve(config.outRootPath, name))),
|
|
149
|
-
dropNames: new Set(outRootScratch),
|
|
150
|
-
outRootPath: path.resolve(config.outRootPath),
|
|
151
116
|
}
|
|
152
117
|
}
|
|
153
118
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
// SOURCE paths, so every module compiled out of a dependency sits under a literal `node_modules`
|
|
157
|
-
// segment, and pruning by name deletes artifacts the function resolves by exact path at request time.
|
|
158
|
-
function shipsDir(
|
|
159
|
-
pack: PackRules,
|
|
160
|
-
name: string,
|
|
161
|
-
source: string,
|
|
162
|
-
inOutRoot = false,
|
|
163
|
-
symlink = false,
|
|
164
|
-
) {
|
|
165
|
-
const absolute = path.resolve(source)
|
|
166
|
-
if (pack.dropPaths.has(absolute)) return false
|
|
167
|
-
// A *link* named node_modules inside the out root points at the real store, and following it
|
|
168
|
-
// copies the whole thing; a real directory there is the compiled module cache, whose artifacts
|
|
169
|
-
// mirror source paths — so one of them is literally `<out>/cache/.../node_modules/<pkg>/...`.
|
|
170
|
-
if (inOutRoot) return !(symlink && pack.prunedDirs.has(name))
|
|
171
|
-
return !pack.prunedDirs.has(name) || pack.keepPaths.has(absolute)
|
|
119
|
+
function shipsDir(pack: PackRules, name: string, source: string) {
|
|
120
|
+
return !pack.prunedDirs.has(name) || pack.keepPaths.has(path.resolve(source))
|
|
172
121
|
}
|
|
173
122
|
|
|
174
|
-
const isOutRoot = (pack: PackRules, dir: string) => path.resolve(dir) === pack.outRootPath
|
|
175
|
-
|
|
176
123
|
function shipsFile(pack: PackRules, name: string) {
|
|
177
124
|
return !pack.droppedSuffixes.some(suffix => name.endsWith(suffix))
|
|
178
125
|
}
|
|
@@ -192,12 +139,6 @@ export async function writeVercelOutput(
|
|
|
192
139
|
options: { verbose?: boolean; warm?: WarmChild } = {},
|
|
193
140
|
) {
|
|
194
141
|
const log = createVerboseLogger(options.verbose ?? false, 'vercel')
|
|
195
|
-
if (emulateRoot) {
|
|
196
|
-
console.warn(
|
|
197
|
-
`pnext: PNEXT_VERCEL_EMULATE is set — this output is built for ${FUNCTION_PLATFORM.os}-` +
|
|
198
|
-
`${FUNCTION_PLATFORM.cpu} and rooted at ${RUNTIME_ROOT}. It runs locally; do not deploy it.`,
|
|
199
|
-
)
|
|
200
|
-
}
|
|
201
142
|
const outputPath = path.join(config.root, '.vercel', 'output')
|
|
202
143
|
const staticFiles = manifest.staticFiles ?? {}
|
|
203
144
|
// Warming runs in its own process (see ./vercel-warm) and normally started
|
|
@@ -394,26 +335,14 @@ async function writeServerFunction(
|
|
|
394
335
|
)
|
|
395
336
|
|
|
396
337
|
// Baked absolute paths (compiled cache imports, manifest file paths) point
|
|
397
|
-
// at the build machine's workspace; rewrite them to the runtime root.
|
|
398
|
-
// `distDir` app moved its output away from the default out root, but the
|
|
399
|
-
// next.config bundle stays there and bakes paths of its own, so both trees go
|
|
400
|
-
// through the pass.
|
|
401
|
-
const bakedRoots = new Set(
|
|
402
|
-
[config.outPath, path.resolve(config.root, DEFAULT_OUT_DIR)].map(dir =>
|
|
403
|
-
path.join(functionPath, appRel, path.relative(config.root, dir)),
|
|
404
|
-
),
|
|
405
|
-
)
|
|
338
|
+
// at the build machine's workspace; rewrite them to the runtime root.
|
|
406
339
|
await log.step('rewrite baked paths', () =>
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
[workspaceRoot, RUNTIME_ROOT] as const,
|
|
414
|
-
]),
|
|
415
|
-
),
|
|
416
|
-
),
|
|
340
|
+
rewriteBakedPaths(path.join(functionPath, appRel, path.relative(config.root, config.outPath)), [
|
|
341
|
+
...(pnextInWorkspace
|
|
342
|
+
? []
|
|
343
|
+
: [[pnextRoot, toPosixPath(path.join(RUNTIME_ROOT, pnextTargetRel))] as const]),
|
|
344
|
+
[workspaceRoot, RUNTIME_ROOT] as const,
|
|
345
|
+
]),
|
|
417
346
|
)
|
|
418
347
|
|
|
419
348
|
// Bun's runtime onResolve plugins never see bare specifiers, so the compat aliases the dev pipeline
|
|
@@ -528,16 +457,13 @@ async function copyTree(
|
|
|
528
457
|
pack: PackRules,
|
|
529
458
|
excludeNames: string[] = [],
|
|
530
459
|
visited = new Set<string>([realDir(from) ?? path.resolve(from)]),
|
|
531
|
-
inOutRoot = pack.keepPaths.has(path.resolve(from)),
|
|
532
460
|
) {
|
|
533
461
|
const exclude = new Set(excludeNames)
|
|
534
462
|
const clone = directoryCloneEnabled ? await directoryCloner() : null
|
|
535
463
|
// Nothing to skip at this level: the whole tree clones in one syscall.
|
|
536
464
|
if (exclude.size === 0 && !existsSync(to)) {
|
|
537
465
|
await mkdir(path.dirname(to), { recursive: true })
|
|
538
|
-
if (clone?.(from, to))
|
|
539
|
-
return normalizeClone(to, pack, visited, inOutRoot, isOutRoot(pack, from))
|
|
540
|
-
}
|
|
466
|
+
if (clone?.(from, to)) return normalizeClone(to, pack, visited)
|
|
541
467
|
}
|
|
542
468
|
// The build output is still live while the walk runs — typegen rewrites
|
|
543
469
|
// `.pnext/types` under it — so a directory can vanish between the parent's
|
|
@@ -551,29 +477,23 @@ async function copyTree(
|
|
|
551
477
|
const target = path.join(to, entry.name)
|
|
552
478
|
// Matched by name before type: a symlinked `node_modules` must be pruned
|
|
553
479
|
// as the directory it points at, not followed.
|
|
554
|
-
if (
|
|
555
|
-
exclude.has(entry.name) ||
|
|
556
|
-
!shipsDir(pack, entry.name, source, inOutRoot, entry.isSymbolicLink())
|
|
557
|
-
) {
|
|
558
|
-
return
|
|
559
|
-
}
|
|
560
|
-
const childInOutRoot = inOutRoot || pack.keepPaths.has(path.resolve(source))
|
|
480
|
+
if (exclude.has(entry.name) || !shipsDir(pack, entry.name, source)) return
|
|
561
481
|
if (entry.isSymbolicLink()) {
|
|
562
482
|
const link = resolveLinkTarget(source)
|
|
563
483
|
if (!link) return
|
|
564
484
|
if (link.isDirectory) {
|
|
565
485
|
if (visited.has(link.path)) return
|
|
566
486
|
visited.add(link.path)
|
|
567
|
-
return copyTree(link.path, target, pack, [], visited
|
|
487
|
+
return copyTree(link.path, target, pack, [], visited)
|
|
568
488
|
}
|
|
569
489
|
return shipsFile(pack, entry.name) ? linkOrCopyFile(link.path, target) : undefined
|
|
570
490
|
}
|
|
571
491
|
// One syscall for the whole subtree beats one per file — the excluded
|
|
572
492
|
// names are stripped from the copy afterwards.
|
|
573
493
|
if (entry.isDirectory() && clone?.(source, target)) {
|
|
574
|
-
return normalizeClone(target, pack, visited
|
|
494
|
+
return normalizeClone(target, pack, visited)
|
|
575
495
|
}
|
|
576
|
-
if (entry.isDirectory()) return copyTree(source, target, pack, [], visited
|
|
496
|
+
if (entry.isDirectory()) return copyTree(source, target, pack, [], visited)
|
|
577
497
|
if (entry.isFile() && shipsFile(pack, entry.name)) return linkOrCopyFile(source, target)
|
|
578
498
|
}),
|
|
579
499
|
)
|
|
@@ -632,30 +552,18 @@ async function directoryCloner() {
|
|
|
632
552
|
* both paths emit the same tree. Reading directory entries costs nothing next
|
|
633
553
|
* to the per-file copies this replaces.
|
|
634
554
|
*/
|
|
635
|
-
async function normalizeClone(
|
|
636
|
-
dir
|
|
637
|
-
pack: PackRules,
|
|
638
|
-
visited: Set<string>,
|
|
639
|
-
inOutRoot = false,
|
|
640
|
-
atOutRoot = false,
|
|
641
|
-
) {
|
|
642
|
-
// `atOutRoot` only at the level the walk handed over, mirroring the absolute
|
|
643
|
-
// paths shipsDir drops: the scratch dirs exist at the out root's top level and
|
|
644
|
-
// their names (`types`, `dev`) are ordinary ones anywhere else.
|
|
645
|
-
const stack: [string, boolean, boolean][] = [[dir, inOutRoot, atOutRoot]]
|
|
555
|
+
async function normalizeClone(dir: string, pack: PackRules, visited: Set<string>) {
|
|
556
|
+
const stack = [dir]
|
|
646
557
|
const pending: Promise<unknown>[] = []
|
|
647
558
|
while (stack.length > 0) {
|
|
648
|
-
const
|
|
559
|
+
const current = stack.pop()!
|
|
649
560
|
for (const entry of readdirSync(current, { withFileTypes: true })) {
|
|
650
561
|
const full = path.join(current, entry.name)
|
|
651
|
-
// Matched by name before type, as the walk does:
|
|
652
|
-
//
|
|
653
|
-
//
|
|
562
|
+
// Matched by name before type, as the walk does: the pages-compat shim
|
|
563
|
+
// links `node_modules` at the app root, and following it would pull the
|
|
564
|
+
// whole store into the function. The clone is already inside the
|
|
654
565
|
// function, so the walk's keep-path exemption cannot apply here.
|
|
655
|
-
if (
|
|
656
|
-
(atRoot && pack.dropNames.has(entry.name)) ||
|
|
657
|
-
((!inside || entry.isSymbolicLink()) && pack.prunedDirs.has(entry.name))
|
|
658
|
-
) {
|
|
566
|
+
if (pack.prunedDirs.has(entry.name)) {
|
|
659
567
|
rmSync(full, { recursive: true, force: true })
|
|
660
568
|
} else if (entry.isSymbolicLink()) {
|
|
661
569
|
const link = resolveLinkTarget(full)
|
|
@@ -664,12 +572,12 @@ async function normalizeClone(
|
|
|
664
572
|
if (link.isDirectory) {
|
|
665
573
|
if (visited.has(link.path)) continue
|
|
666
574
|
visited.add(link.path)
|
|
667
|
-
pending.push(copyTree(link.path, full, pack, [], visited
|
|
575
|
+
pending.push(copyTree(link.path, full, pack, [], visited))
|
|
668
576
|
} else if (shipsFile(pack, entry.name)) {
|
|
669
577
|
pending.push(linkOrCopyFile(link.path, full))
|
|
670
578
|
}
|
|
671
579
|
} else if (entry.isDirectory()) {
|
|
672
|
-
stack.push(
|
|
580
|
+
stack.push(full)
|
|
673
581
|
} else if (!shipsFile(pack, entry.name)) {
|
|
674
582
|
rmSync(full, { force: true })
|
|
675
583
|
}
|
|
@@ -7,11 +7,12 @@
|
|
|
7
7
|
// - every local source file must still match the stat it was read at, so a font swapped while the
|
|
8
8
|
// server was not running re-resolves and re-emits.
|
|
9
9
|
// Nothing here is used by `pnext build`, which owns the directory it just wiped.
|
|
10
|
-
import { existsSync,
|
|
10
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
|
|
11
11
|
import { mkdir, stat } from 'node:fs/promises'
|
|
12
12
|
import { createHash } from 'node:crypto'
|
|
13
13
|
import path from 'node:path'
|
|
14
14
|
import type { ResolvedConfig } from '../../../config'
|
|
15
|
+
import { restartCacheEnabled } from '../../../dev/restart/enabled'
|
|
15
16
|
import { writeFileAtomic } from '../../../utils/fs'
|
|
16
17
|
import type { MetadataLink } from '../../../types'
|
|
17
18
|
|
|
@@ -60,10 +61,6 @@ function fontIndex(config: ResolvedConfig): FontIndex {
|
|
|
60
61
|
if (!created.dirty) return
|
|
61
62
|
created.dirty = false
|
|
62
63
|
try {
|
|
63
|
-
// The debounced write mkdirs; this path can be the FIRST write of the run
|
|
64
|
-
// (a build's warm child resolves fonts and exits before the timer fires),
|
|
65
|
-
// and a missing directory would silently cost the deployment its index.
|
|
66
|
-
mkdirSync(path.dirname(created.file), { recursive: true })
|
|
67
64
|
writeFileSync(created.file, serializeIndex(created.fonts))
|
|
68
65
|
} catch {
|
|
69
66
|
// Best effort: a missing index only costs the next boot a re-resolve.
|
|
@@ -77,6 +74,7 @@ export async function persistedFont(
|
|
|
77
74
|
config: ResolvedConfig,
|
|
78
75
|
key: string,
|
|
79
76
|
): Promise<PersistableFont | undefined> {
|
|
77
|
+
if (!restartCacheEnabled()) return undefined
|
|
80
78
|
const entry = fontIndex(config).fonts.get(key)
|
|
81
79
|
if (!entry) return undefined
|
|
82
80
|
if (!entry.files.every(file => existsSync(file))) return undefined
|
|
@@ -10,7 +10,6 @@ import { onExtensionHostReset, registerResponseFinalizers } from '../../../exten
|
|
|
10
10
|
import { getWorkUnit } from '../../../request/context'
|
|
11
11
|
import type { MetadataLink } from '../../../types'
|
|
12
12
|
import { persistFont, persistedFont } from './cache'
|
|
13
|
-
import { restartCacheEnabled } from '../../../dev/restart/enabled'
|
|
14
13
|
import { escapeRegex } from '../../../utils/code'
|
|
15
14
|
import {
|
|
16
15
|
familyStack,
|
|
@@ -114,16 +113,8 @@ let googleMetadataCache: Record<string, GoogleFontMetadata> | undefined
|
|
|
114
113
|
* Every font definition constructed so far, whether or not a render has read its `.className` yet.
|
|
115
114
|
* Definitions are created when the app's font module evaluates - well before the render that registers
|
|
116
115
|
* them - which is what makes the resolve prewarmable.
|
|
117
|
-
*
|
|
118
|
-
* Process-global rather than module-local: a compiled artifact imports this module through the build
|
|
119
|
-
* cache, so the app's font declarations land in a DIFFERENT instance than the one the orchestrator
|
|
120
|
-
* bootstrapped, and a prewarm reading a module-local map would find it empty.
|
|
121
116
|
*/
|
|
122
|
-
const
|
|
123
|
-
const declaredFonts = ((globalThis as Record<symbol, unknown>)[DECLARED_FONTS] ??= new Map<
|
|
124
|
-
string,
|
|
125
|
-
FontDefinition
|
|
126
|
-
>()) as Map<string, FontDefinition>
|
|
117
|
+
const declaredFonts = new Map<string, FontDefinition>()
|
|
127
118
|
|
|
128
119
|
/**
|
|
129
120
|
* Resolve the declared fonts ahead of the render that will ask for them. Fire-and-forget: this only
|
|
@@ -369,31 +360,25 @@ async function resolveFont(definition: FontDefinition, context: FontResolveConte
|
|
|
369
360
|
// A `pnext build` wiping the output directory under a running server must
|
|
370
361
|
// not leave cached font URLs pointing at deleted files; re-emit them.
|
|
371
362
|
// Font bytes stay cached in memory, so this never refetches the network.
|
|
372
|
-
|
|
373
|
-
// rejects the write; there is nothing on disk to go stale.
|
|
374
|
-
if (font.files.every(file => !file || existsSync(file))) return font
|
|
363
|
+
if (font.files.every(file => existsSync(file))) return font
|
|
375
364
|
const fresh = resolveAndPersist(definition, context, key)
|
|
376
365
|
resolvedFontCache.set(key, fresh)
|
|
377
366
|
return fresh
|
|
378
367
|
}
|
|
379
368
|
|
|
380
369
|
/**
|
|
381
|
-
*
|
|
382
|
-
*
|
|
383
|
-
*
|
|
384
|
-
* time has neither a writable output directory nor any need to reach Google again. A build re-resolves
|
|
385
|
-
* for real without a special case - it empties the output directory first, so the recorded files are
|
|
386
|
-
* gone and the entry is rejected.
|
|
370
|
+
* Dev reuses the persisted resolution when it still describes disk: a restart otherwise re-fetches every
|
|
371
|
+
* Google stylesheet and font file to re-derive URLs whose bytes are already emitted. A build always
|
|
372
|
+
* resolves for real - it owns the output directory it just emptied.
|
|
387
373
|
*/
|
|
388
374
|
async function resolveThroughCache(
|
|
389
375
|
definition: FontDefinition,
|
|
390
376
|
context: FontResolveContext,
|
|
391
377
|
key: string,
|
|
392
378
|
): Promise<ResolvedFont> {
|
|
393
|
-
if (!context.dev
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
}
|
|
379
|
+
if (!context.dev) return definition.resolve(context)
|
|
380
|
+
const persisted = await persistedFont(context.config, key)
|
|
381
|
+
if (persisted) return persisted
|
|
397
382
|
return resolveAndPersist(definition, context, key)
|
|
398
383
|
}
|
|
399
384
|
|
|
@@ -403,8 +388,9 @@ function resolveAndPersist(
|
|
|
403
388
|
key: string,
|
|
404
389
|
): Promise<ResolvedFont> {
|
|
405
390
|
const resolved = definition.resolve(context)
|
|
406
|
-
|
|
407
|
-
|
|
391
|
+
if (context.dev) {
|
|
392
|
+
void resolved.then(font => persistFont(context.config, key, font)).catch(() => undefined)
|
|
393
|
+
}
|
|
408
394
|
return resolved
|
|
409
395
|
}
|
|
410
396
|
|
|
@@ -731,7 +717,7 @@ async function emitRemoteFontFile(context: FontResolveContext, url: string, emit
|
|
|
731
717
|
googleFontFileCache.set(url, cached)
|
|
732
718
|
}
|
|
733
719
|
const bytes = await cached
|
|
734
|
-
return emitFontBytes(context, bytes, fontExt(url), emit
|
|
720
|
+
return emitFontBytes(context, bytes, fontExt(url), emit)
|
|
735
721
|
}
|
|
736
722
|
|
|
737
723
|
async function fetchFontFile(url: string) {
|
|
@@ -755,7 +741,6 @@ async function emitFontBytes(
|
|
|
755
741
|
ext: string,
|
|
756
742
|
emit: EmitFontOptions,
|
|
757
743
|
sourceFile?: string,
|
|
758
|
-
originUrl?: string,
|
|
759
744
|
) {
|
|
760
745
|
const hash = createHash('sha256').update(bytes).digest('hex').slice(0, 16)
|
|
761
746
|
// Next's loader names emitted files `[hash]-s.p.[ext]`: `-s` when a
|
|
@@ -766,39 +751,12 @@ async function emitFontBytes(
|
|
|
766
751
|
const mediaSegments = ['_next', 'static', 'media']
|
|
767
752
|
const outDir = path.join(context.config.outPath, 'public', ...mediaSegments)
|
|
768
753
|
const file = path.join(outDir, filename)
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
file,
|
|
772
|
-
type: fontMimeType(ext),
|
|
773
|
-
url: `/${mediaSegments.join('/')}/${filename}`,
|
|
774
|
-
}
|
|
775
|
-
if (existsSync(file)) return emitted
|
|
776
|
-
try {
|
|
777
|
-
await mkdir(outDir, { recursive: true })
|
|
754
|
+
await mkdir(outDir, { recursive: true })
|
|
755
|
+
if (!existsSync(file)) {
|
|
778
756
|
if (sourceFile) await copyFile(sourceFile, file)
|
|
779
757
|
else await writeFile(file, bytes)
|
|
780
|
-
return emitted
|
|
781
|
-
} catch (error) {
|
|
782
|
-
// A deployed server's filesystem is read-only, and a font first reached by a request that was
|
|
783
|
-
// never prerendered lands here. A Google font still renders from its origin; a local font has
|
|
784
|
-
// no such address, so that one is a real error.
|
|
785
|
-
if (!originUrl) throw error
|
|
786
|
-
warnFontSelfHostUnavailable()
|
|
787
|
-
// `file` empty, not the path that was just proven unwritable: the resolution memo re-runs
|
|
788
|
-
// whenever a recorded file is missing from disk, so naming one here would re-resolve (and
|
|
789
|
-
// re-attempt the write) on every render for the life of the process.
|
|
790
|
-
return { ...emitted, file: '', url: originUrl }
|
|
791
758
|
}
|
|
792
|
-
}
|
|
793
|
-
|
|
794
|
-
let warnedFontSelfHost = false
|
|
795
|
-
function warnFontSelfHostUnavailable() {
|
|
796
|
-
if (warnedFontSelfHost) return
|
|
797
|
-
warnedFontSelfHost = true
|
|
798
|
-
console.warn(
|
|
799
|
-
'pnext: next/font assets cannot be written on this filesystem; serving them from their origin ' +
|
|
800
|
-
'instead of self-hosting.',
|
|
801
|
-
)
|
|
759
|
+
return { ext, file, type: fontMimeType(ext), url: `/${mediaSegments.join('/')}/${filename}` }
|
|
802
760
|
}
|
|
803
761
|
|
|
804
762
|
function normalizeLocalSources(
|
|
@@ -875,9 +833,6 @@ function loadGoogleMetadata(): Record<string, GoogleFontMetadata> {
|
|
|
875
833
|
throw new Error(`Invalid Google font metadata file: ${override}`)
|
|
876
834
|
}
|
|
877
835
|
|
|
878
|
-
// Resolved by specifier, never bundled: the data is a megabyte of metadata and the package is
|
|
879
|
-
// optional. Deployment adapters ship it through `deploymentPackages` instead — the import scan
|
|
880
|
-
// cannot see a dynamic specifier, and request time has no way to install one.
|
|
881
836
|
const metadata =
|
|
882
837
|
tryLoadGoogleMetadata('next-font/google/font-data.json') ?? tryLoadGoogleMetadata('next-font')
|
|
883
838
|
if (metadata) return metadata
|