@kerf-js/start 0.1.2-nightly.20261118.85 → 0.1.3

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.
@@ -14,6 +14,7 @@ import { here, V, KIT_CHUNKS, INLINE_SHEETS, SHEET_PIECES, ROUTE_ASSET_BYTES } f
14
14
  export const configHook = (s) =>
15
15
  function (config, env) {
16
16
  s.root = config.root ? resolve(config.root) : s.root
17
+ s.resetPaths()
17
18
  s.dev = env.command === 'serve'
18
19
  s.scan()
19
20
  if (s.shell) {
@@ -21,13 +22,14 @@ export const configHook = (s) =>
21
22
  if (!s.dev) requireShellContracts(s.root, s.options.routesDir, s.manifest)
22
23
  }
23
24
  return {
25
+ ...(!s.dev && { build: { rolldownOptions: { experimental: { attachDebugInfo: 'none' } } } }),
24
26
  environments: {
25
27
  client: {
26
28
  ...(s.shell && { define: { __KERF_SHELL__: 'true' } }),
27
29
  build: {
28
30
  rollupOptions: {
29
31
  input: s.clientEntry(),
30
- output: { advancedChunks: { groups: KIT_CHUNKS } },
32
+ output: { codeSplitting: { groups: KIT_CHUNKS } },
31
33
  },
32
34
  },
33
35
  },
@@ -214,6 +216,7 @@ export const configResolved = (s) =>
214
216
  .slice(0, 8)
215
217
  if (s.dev) s.build = 'dev'
216
218
  s.root = config.root
219
+ s.resetPaths()
217
220
  const main = config.plugins.find((p) => p.name === 'kerf')
218
221
  s.words = config.plugins.find((p) => p.name === 'kerf:purge')?.api
219
222
  s.words?.add('data-kerf styled') // gate.css reveals a mark a static page's HTML may hold alone
@@ -1,9 +1,10 @@
1
- import { existsSync, readFileSync, watch } from 'node:fs'
1
+ import { existsSync, readFileSync } from 'node:fs'
2
2
  import { join, relative } from 'node:path'
3
3
  import { waitingForAFix, reaches, refresh } from './dev.mjs'
4
4
  import { serverExports } from './syntax.mjs'
5
5
  import { isServerModule } from './server-functions.mjs'
6
6
  import { SHEET, ASSETS, V } from './shared.mjs'
7
+ import { watchFailure, watchTree } from '../watch-tree.mjs'
7
8
 
8
9
  export const configureServer = (s) =>
9
10
  function (server) {
@@ -21,7 +22,8 @@ export const configureServer = (s) =>
21
22
  server.middlewares.use(waitingForAFix)
22
23
  // A route file added or removed changes the virtual modules; edits to existing ones are ordinary HMR/reloads.
23
24
  const dir = join(s.root, 'src')
24
- if (!existsSync(dir)) return
25
+ // A one-shot server (`kerf check`, `kerf routes --meta`, a build's contract) asks Vite to watch nothing: so does this.
26
+ if (!existsSync(dir) || server.config.server.watch === null) return
25
27
  const routesDir = relative(dir, join(s.root, s.manifest.dir)).split('\\').join('/')
26
28
  const shape = () =>
27
29
  JSON.stringify([
@@ -49,17 +51,23 @@ export const configureServer = (s) =>
49
51
  )
50
52
  server.ws.send({ type: 'full-reload' })
51
53
  }
52
- const w = watch(dir, { recursive: true }, (event, file) => {
53
- if (event === 'rename' && file) changed(file)
54
- })
54
+ const w = watchTree(
55
+ dir,
56
+ (event, file) => {
57
+ if (event === 'rename' && file) changed(file)
58
+ },
59
+ (error) =>
60
+ server.config.logger.warn(
61
+ `kerf: can't watch src/ (${watchFailure(error)}): Vite's own watcher still sees routes added or removed`,
62
+ { timestamp: true },
63
+ ),
64
+ )
55
65
  // Not every runtime's recursive watch reports a new file, and Vite's watcher does.
56
66
  for (const event of ['add', 'unlink'])
57
67
  server.watcher.on(event, (file) => {
58
68
  if (file.startsWith(dir)) changed(relative(dir, file))
59
69
  })
60
- // Close with the server (middleware mode, as `kerf routes --meta` runs it, has no httpServer to listen on).
61
- const close = server.close.bind(server)
62
- server.close = () => (w.close(), close())
70
+ s.closeRoutes = () => w?.close()
63
71
  }
64
72
 
65
73
  export const hotUpdate = (s) =>
@@ -4,7 +4,12 @@ import { join } from 'node:path'
4
4
  import { scanRequired } from '../live-target.mjs'
5
5
  import { here, V, purgeFile, INLINE_SHEETS, SHEET_PIECES, ROUTE_ASSET_BYTES } from './shared.mjs'
6
6
 
7
- export function serverEntry(clientEntry, dev, root, bootstrap) {
7
+ export function serverEntry(s) {
8
+ const { dev, root, bootstrap } = s
9
+ const clientEntry = s.clientEntry()
10
+ const assets = dev
11
+ ? `import assets from ${JSON.stringify(clientEntry + '?assets=client')}`
12
+ : `const assets = import.meta.vite.assets(${JSON.stringify({ import: s.assetSource(clientEntry), environment: 'client', asEntry: true })})`
8
13
  return `import { createHandler, serverLog } from ${JSON.stringify(join(here, 'server.tsx'))}
9
14
  import { chunks, lazy, manifest, modules, routeCss, statics } from '${V.routes}'
10
15
  import '${V.fns}'
@@ -27,7 +32,7 @@ import email from '${V.email}'
27
32
  import jobs from '${V.jobs}'
28
33
  import extensions from '${V.extensions}'
29
34
  import * as app from '${V.app}'
30
- import assets from '${clientEntry}?assets=client'
35
+ ${assets}
31
36
  import { preloads } from 'kerf:fonts/preloads'
32
37
  ${dev ? '' : `import { parse, purge } from ${JSON.stringify(purgeFile)}\n`}const fetch = createHandler({ ${bootstrap?.contract && bootstrap.provider ? 'bootstrap: { schema: bootstrap.schema, provide }, ' : ''}manifest: { ...manifest, http }, httpModules, handle: hooks.handle, startup: hooks.startup, modules, statics, chunks, lazy, context, auth, migrations, media, realtime, store: cache, cron, email, jobs, liveRequired: ${JSON.stringify(scanRequired(root).map((r) => r.name))}, extensions, site: app.site, build: app.build, dev: app.dev, fonts: app.fonts(), timeout: app.timeout, hold: app.hold, routeAssetBytes: ${dev ? 'null' : `'${ROUTE_ASSET_BYTES}'`}, assets: { entry: assets.entry, js: assets.js, get css() { return routeCss(assets.css) }, fonts: preloads, inline: ${dev ? 'undefined' : `'${INLINE_SHEETS}'`}, pieces: ${dev ? 'undefined' : `'${SHEET_PIECES}'`}, critical: ${dev ? 'undefined' : '{ parse, purge }'} },
33
38
  // H005–H008, Q002–Q014, A002–A004, F002–F003, M017 and R-codes found while serving: the server log, in dev and production.
@@ -34,6 +34,7 @@ import {
34
34
  functionContracts,
35
35
  } from './server-functions.mjs'
36
36
  import { here, V, DEFAULT_FONTS, ASSETS, ISLAND, ENTRY_SHEETS } from './shared.mjs'
37
+ import { normalizeAssetLookup } from './nitro-output.mjs'
37
38
 
38
39
  /** Virtual modules that are an app file's default export: `src/<name>.server.ts`, or `undefined` without one. */
39
40
  const CONFIG_FILES = new Set([V.context, V.auth, V.realtime, V.cache, V.cron, V.email, V.jobs])
@@ -43,6 +44,8 @@ export const resolveId = (s) => ({
43
44
  id: /^(virtual:kerf\/|@kerf-js\/start\/(db|auth|bus|list|rust|sidecar)(\/|$)|@kerf-js\/(realtime-(redis|nats|durable-object)|db-[\w-]+)$|sharp$)/,
44
45
  },
45
46
  handler(source, importer) {
47
+ const asset = s.assetSources?.get(source)
48
+ if (asset) return asset === V.client ? s.id(asset) : this.resolve(asset, importer)
46
49
  // Sharp's addon can't be bundled, so it stays external and Nitro traces it, which it can only do from the app.
47
50
  if (source === 'sharp') {
48
51
  if (s.dev || !/[\\/](@kerf-js[\\/]media|packages[\\/]media)[\\/]/.test(importer ?? '')) return
@@ -107,7 +110,7 @@ export const load = (s) => ({
107
110
  timeout: s.options.timeout,
108
111
  hold: s.options.hold,
109
112
  })
110
- if (which === V.server) return serverEntry(s.clientEntry(), s.dev, s.root, s.bootstrap)
113
+ if (which === V.server) return serverEntry(s)
111
114
  if (which === V.fns)
112
115
  return s.serverModules.map((f) => `import ${JSON.stringify(s.abs(f))}`).join('\n') + '\n'
113
116
  if (CONFIG_FILES.has(which)) return configModule(s, which)
@@ -124,9 +127,15 @@ export const load = (s) => ({
124
127
 
125
128
  export const transform = (s) => ({
126
129
  filter: {
127
- id: /\.[jt]sx?(\?kerf-assets)?$|\/[\s\S]+\.[cm][jt]s$|\/vite\/dist\/client\/client\.mjs$/,
130
+ id: /\.[jt]sx?(\?kerf-assets)?$|\/[\s\S]+\.[cm][jt]s$|\/vite\/dist\/client\/client\.mjs$|^\0virtual:fullstack\/assets\?|[?&]assets(?:[=&]|$)/,
128
131
  },
129
132
  async handler(code, file) {
133
+ if (
134
+ !s.dev &&
135
+ (file.startsWith('\0virtual:fullstack/assets?') ||
136
+ (/[?&]assets(?:[=&]|$)/.test(file) && code.includes('virtual:fullstack/assets-manifest')))
137
+ )
138
+ return { code: normalizeAssetLookup(code, s.assetKey), map: { mappings: '' } }
130
139
  const path = file.replace(/\?.*$/, '')
131
140
  if (file.endsWith(ASSETS))
132
141
  return { code: await assetsOnly(this, code, path, s.root, s.words), map: null }
@@ -211,7 +220,8 @@ function unusableSkeleton(ctx, s, root, file) {
211
220
 
212
221
  async function overrideModule(ctx, s, which, client) {
213
222
  if (!client || !which.endsWith('.tsx')) ctx.error('Invalid skeleton override request')
214
- const file = decodeURIComponent(which.slice('virtual:kerf/shape-override/'.length, -4))
223
+ const key = decodeURIComponent(which.slice('virtual:kerf/shape-override/'.length, -4))
224
+ const file = s.dev === false ? s.abs(key) : key
215
225
  const levels = [...s.manifest.layouts, ...s.manifest.routes]
216
226
  if (!levels.some((level) => s.abs(level.file) === file)) ctx.error('Unknown skeleton override')
217
227
  const imported = await resolveImportedOverride(ctx, file, s.root ?? dirname(file))
@@ -242,6 +252,7 @@ async function routesModule(ctx, s, client) {
242
252
  ? await devStyles(s.vite.environments.client, s.manifest, s.abs, s.clientEntry())
243
253
  : undefined,
244
254
  p,
255
+ s.assetSource,
245
256
  )
246
257
  }
247
258
 
@@ -319,6 +330,7 @@ async function clientRoutesModule(ctx, s, p, run) {
319
330
  entry: shared.styles,
320
331
  levels: new Map(files.map((file, i) => [file, sources[i].styles])),
321
332
  overrides,
333
+ production: s.dev === false,
322
334
  build: s.build || null,
323
335
  lazy: s.dev === false,
324
336
  retry: retryRouteModules(ctx, s),
@@ -0,0 +1,8 @@
1
+ export function buildDate(value: string | undefined): string | undefined
2
+ export function normalizePublicAssets(code: string, date?: string): string
3
+ export function normalizeAssetManifest(code: string, keyFor: (path: string) => string): string
4
+ export function normalizeAssetLookup(code: string, keyFor: (path: string) => string): string
5
+ export function stableServices(code: string, directory: string): string
6
+ export function normalizeRouting(code: string, pathFor: (path: string) => string): string
7
+ export function normalizeServerAssets(code: string, date?: string): string
8
+ export function finalizeBuild(output: { dir: string }, date?: string): Promise<void>
@@ -0,0 +1,291 @@
1
+ // Normalize Nitro's generated modules before bundling so the normalized data also
2
+ // controls the hashes, and finish the build descriptor after Nitro writes it.
3
+ import { readFile, readdir, writeFile } from 'node:fs/promises'
4
+ import { createHash } from 'node:crypto'
5
+ import { join, resolve } from 'node:path'
6
+ import { parseAst } from 'vite'
7
+ import { buildPaths, slash } from './build-paths.mjs'
8
+ import { normalizeCopiedMap, sourceMapOptions } from './output-manifests.mjs'
9
+
10
+ const publicAssets = '#nitro/virtual/public-assets-data'
11
+ const serverAssets = '#nitro/virtual/server-assets'
12
+ const viteServices = '#nitro/virtual/vite-services'
13
+ const assetManifest = '__fullstack_assets_manifest.js'
14
+ const assetImport = 'virtual:fullstack/assets-manifest'
15
+ const servicePrefix = '#kerf-built-service/'
16
+
17
+ const byKey = ([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)
18
+ const sorted = (entries) => Object.fromEntries([...entries].sort(byKey))
19
+ const fail = (name) =>
20
+ new Error(`Kerf could not normalize Nitro's ${name}: unexpected module shape`)
21
+
22
+ function defaultExport(code, name) {
23
+ const { body } = parseAst(code)
24
+ if (body.length !== 1 || body[0].type !== 'ExportDefaultDeclaration') throw fail(name)
25
+ return body[0].declaration
26
+ }
27
+
28
+ /** SOURCE_DATE_EPOCH is an integer count of seconds since the Unix epoch. */
29
+ export function buildDate(value) {
30
+ if (value === undefined) return undefined
31
+ const millis = Number(value) * 1000
32
+ if (!/^\d+$/.test(value) || millis > 8.64e15)
33
+ throw new Error('SOURCE_DATE_EPOCH must be a non-negative Unix timestamp in seconds')
34
+ return new Date(millis).toISOString()
35
+ }
36
+
37
+ /** Normalize the JSON-only module produced for Nitro's static middleware. */
38
+ export function normalizePublicAssets(code, date) {
39
+ const node = defaultExport(code, publicAssets)
40
+ if (node.type !== 'ObjectExpression') throw fail(publicAssets)
41
+ let data
42
+ try {
43
+ data = JSON.parse(code.slice(node.start, node.end))
44
+ } catch {
45
+ throw fail(publicAssets)
46
+ }
47
+ for (const [id, asset] of Object.entries(data)) {
48
+ if (
49
+ !id.startsWith('/') ||
50
+ typeof asset?.etag !== 'string' ||
51
+ typeof asset?.mtime !== 'string' ||
52
+ typeof asset?.path !== 'string' ||
53
+ typeof asset?.size !== 'number'
54
+ )
55
+ throw fail(publicAssets)
56
+ asset.mtime = date ?? asset.mtime
57
+ asset.path = slash(asset.path)
58
+ }
59
+ return `export default ${JSON.stringify(sorted(Object.entries(data)))};`
60
+ }
61
+
62
+ function assetProperties(node) {
63
+ if (node.type !== 'ObjectExpression') throw fail(assetManifest)
64
+ return node.properties.map((p) => {
65
+ if (p.type !== 'Property' || p.computed || typeof p.key.value !== 'string')
66
+ throw fail(assetManifest)
67
+ return [p.key.value, p.value]
68
+ })
69
+ }
70
+
71
+ /** Sort the two manifest indexes and keep the values, including runtime URL expressions. */
72
+ export function normalizeAssetManifest(code, keyFor) {
73
+ const entries = assetProperties(defaultExport(code, assetManifest))
74
+ const object = (fields) =>
75
+ `{${[...fields]
76
+ .sort(byKey)
77
+ .map(([key, value]) => `${JSON.stringify(key)}:${value}`)
78
+ .join(',')}}`
79
+ const environment = (table) => {
80
+ const files = assetProperties(table).map(([key, value]) => [
81
+ keyFor(key),
82
+ code.slice(value.start, value.end),
83
+ ])
84
+ if (new Set(files.map(([key]) => key)).size !== files.length) throw fail(assetManifest)
85
+ return object(files)
86
+ }
87
+ return `export default ${object(entries.map(([key, table]) => [key, environment(table)]))};`
88
+ }
89
+
90
+ /** Normalize the matching lookup while Nitro's generated asset proxy is still its own module. */
91
+ export function normalizeAssetLookup(code, keyFor) {
92
+ const { body } = parseAst(code)
93
+ const imported = body.find(
94
+ (statement) => statement.type === 'ImportDeclaration' && statement.source.value === assetImport,
95
+ )
96
+ const name = imported?.specifiers[0]?.local.name
97
+ if (!name) throw fail('Vite asset lookup')
98
+ let count = 0
99
+ const visit = (node) => {
100
+ if (
101
+ node.type === 'MemberExpression' &&
102
+ node.object.type === 'MemberExpression' &&
103
+ node.object.object.name === name
104
+ ) {
105
+ const key = node.property
106
+ if (!node.computed || typeof key.value !== 'string') throw fail('Vite asset lookup')
107
+ count++
108
+ return [key.start, key.end, JSON.stringify(keyFor(key.value))]
109
+ }
110
+ }
111
+ const edits = collectEdits({ body }, visit)
112
+ if (!count) throw fail('Vite asset lookup')
113
+ return editCode(code, edits)
114
+ }
115
+
116
+ function collectEdits(tree, replacement) {
117
+ const edits = []
118
+ const walk = (node) => {
119
+ if (!node || typeof node !== 'object') return
120
+ const edit = replacement(node)
121
+ if (edit !== undefined) {
122
+ edits.push(edit)
123
+ return
124
+ }
125
+ for (const value of Object.values(node)) {
126
+ if (Array.isArray(value)) value.forEach(walk)
127
+ else walk(value)
128
+ }
129
+ }
130
+ walk(tree)
131
+ return edits
132
+ }
133
+
134
+ function editCode(code, edits) {
135
+ for (const [start, end, text] of edits.sort(([a], [b]) => b - a))
136
+ code = code.slice(0, start) + text + code.slice(end)
137
+ return code
138
+ }
139
+
140
+ /** Give the generated service imports a stable specifier before mapping their source columns. */
141
+ export function stableServices(code, directory) {
142
+ const edits = collectEdits(parseAst(code), (node) => {
143
+ if (node.type !== 'ImportExpression') return
144
+ const source = slash(node.source.value ?? '')
145
+ if (!source.startsWith(directory + '/')) throw fail(viteServices)
146
+ const specifier = servicePrefix + source.slice(directory.length + 1)
147
+ return [node.source.start, node.source.end, JSON.stringify(specifier)]
148
+ })
149
+ return editCode(code, edits)
150
+ }
151
+
152
+ /** Nitro hashes the physical handler import, including its own runtime and app routes. */
153
+ export function normalizeRouting(code, pathFor) {
154
+ const tree = parseAst(code)
155
+ const names = new Map()
156
+ const record = (node, source) => {
157
+ if (!node?.name.startsWith('_') || typeof source !== 'string') return
158
+ const hash = createHash('sha256').update(pathFor(source)).digest('hex').slice(0, 16)
159
+ const kind = node.name.startsWith('_lazy_') ? '_lazy_' : '_handler_'
160
+ names.set(node.name, `${kind}${hash}${node.name.endsWith('Meta') ? 'Meta' : ''}`)
161
+ }
162
+ collectEdits(tree, (node) => {
163
+ if (node.type === 'ImportDeclaration') record(node.specifiers[0]?.local, node.source.value)
164
+ if (node.type === 'VariableDeclarator' && node.id.name?.startsWith('_lazy_')) {
165
+ const imports = collectEdits(node.init, (child) =>
166
+ child.type === 'ImportExpression' ? child.source.value : undefined,
167
+ )
168
+ if (imports.length !== 1) throw fail('routing')
169
+ record(node.id, imports[0])
170
+ }
171
+ })
172
+ const edits = collectEdits(tree, (node) => {
173
+ if (node.type === 'Identifier' && names.has(node.name))
174
+ return [node.start, node.end, names.get(node.name)]
175
+ })
176
+ return editCode(code, edits)
177
+ }
178
+
179
+ /** Normalize Nitro's private asset index without changing its bundled raw imports. */
180
+ export function normalizeServerAssets(code, date) {
181
+ const { body } = parseAst(code)
182
+ const table = body
183
+ .filter((node) => node.type === 'VariableDeclaration')
184
+ .flatMap((node) => node.declarations)
185
+ .find((node) => node.id.name === '_assets')?.init
186
+ if (table?.type !== 'ObjectExpression') throw fail(serverAssets)
187
+ const entries = table.properties.map((record) => {
188
+ if (typeof record.key?.value !== 'string' || record.value.type !== 'ObjectExpression')
189
+ throw fail(serverAssets)
190
+ const meta = record.value.properties.find((p) => p.key?.name === 'meta')?.value
191
+ if (!meta) throw fail(serverAssets)
192
+ const info = JSON.parse(code.slice(meta.start, meta.end))
193
+ if (typeof info.mtime !== 'string') throw fail(serverAssets)
194
+ return [
195
+ record.key.value,
196
+ code.slice(record.start, meta.start) +
197
+ JSON.stringify({ ...info, mtime: date ?? info.mtime }) +
198
+ code.slice(meta.end, record.end),
199
+ ]
200
+ })
201
+ return editCode(code, [
202
+ [
203
+ table.start,
204
+ table.end,
205
+ `{${entries
206
+ .sort(byKey)
207
+ .map(([, value]) => value)
208
+ .join(',')}}`,
209
+ ],
210
+ ])
211
+ }
212
+
213
+ /** Scope the adapters to Nitro's generated modules and resolve service paths only inside the build. */
214
+ export function nitroOutput({ options }, date) {
215
+ const services = slash(join(options.buildDir, 'vite/services'))
216
+ const pathFor = buildPaths(options.rootDir)
217
+ return {
218
+ name: 'kerf:start:nitro-output',
219
+ resolveId(id) {
220
+ if (id.startsWith(servicePrefix)) return resolve(services, id.slice(servicePrefix.length))
221
+ },
222
+ transform(code, id) {
223
+ if (id === publicAssets) return { code: normalizePublicAssets(code, date), map: null }
224
+ if (id === serverAssets)
225
+ return { code: normalizeServerAssets(code, date), map: { mappings: '' } }
226
+ if (id === '#nitro/virtual/routing' || id === '#nitro/virtual/routing-meta')
227
+ return { code: normalizeRouting(code, pathFor), map: { mappings: '' } }
228
+ if (id === viteServices)
229
+ return { code: stableServices(code, services), map: { mappings: '' } }
230
+ },
231
+ outputOptions(output) {
232
+ return sourceMapOptions(output, pathFor)
233
+ },
234
+ }
235
+ }
236
+
237
+ async function rewriteCopiedMaps(dir, client, pathFor) {
238
+ for (const path of (await readdir(dir, { recursive: true })).sort()) {
239
+ if (!path.endsWith('.map')) continue
240
+ const file = join(dir, path)
241
+ const destination = join(client, path)
242
+ const copied = await readOptional(destination)
243
+ if (copied === undefined || copied !== (await readFile(file, 'utf8'))) continue
244
+ await writeFile(destination, normalizeCopiedMap(copied, pathFor, file))
245
+ }
246
+ }
247
+
248
+ function readOptional(file) {
249
+ return readFile(file, 'utf8').catch((error) => {
250
+ if (error.code !== 'ENOENT') throw error
251
+ })
252
+ }
253
+
254
+ async function normalizeWrittenAssets(builder, state) {
255
+ const client = resolve(state.root, builder.environments.client.config.build.outDir)
256
+ for (const env of Object.values(builder.environments)) {
257
+ if (env.name === 'nitro' || env.config.consumer === 'client') continue
258
+ const dir = resolve(state.root, env.config.build.outDir)
259
+ const file = join(dir, assetManifest)
260
+ const code = await readOptional(file)
261
+ if (code === undefined) {
262
+ if (env.name === 'ssr' && state.assetSources.size) throw fail(assetManifest)
263
+ continue
264
+ }
265
+ await writeFile(file, normalizeAssetManifest(code, state.assetKey))
266
+ // The final server consumes the original service maps. Only Nitro's public copies need relabeling.
267
+ if (env.config.build.sourcemap) await rewriteCopiedMaps(dir, client, state.pathFor)
268
+ }
269
+ }
270
+
271
+ /** Normalize the manifest before both the prerenderer and the final server import it. */
272
+ export function normalizeViteAssets(state) {
273
+ return function (builder) {
274
+ const write = builder.writeAssetsManifest
275
+ if (state.dev || !write) return
276
+ let written
277
+ builder.writeAssetsManifest = () =>
278
+ (written ??= Promise.resolve(write.call(builder)).then(() =>
279
+ normalizeWrittenAssets(builder, state),
280
+ ))
281
+ }
282
+ }
283
+
284
+ /** Nitro's compiled hook runs before this descriptor exists. */
285
+ export async function finalizeBuild(output, date) {
286
+ if (date === undefined) return
287
+ const file = join(output.dir, 'nitro.json')
288
+ const info = JSON.parse(await readFile(file, 'utf8'))
289
+ if (typeof info.date !== 'string') throw fail('nitro.json')
290
+ await writeFile(file, JSON.stringify({ ...info, date }, null, 2))
291
+ }
@@ -0,0 +1,7 @@
1
+ export function manifestKey(pathFor: (path: string) => string, key: string): string
2
+ export function normalizeViteManifest(json: string, keyFor: (path: string) => string): string
3
+ export function normalizeCopiedMap(
4
+ json: string,
5
+ pathFor: (path: string) => string,
6
+ file: string,
7
+ ): string
@@ -0,0 +1,75 @@
1
+ // Vite's import lists carry dependency order. Normalize only identities and unordered indexes.
2
+ import { resolve, dirname } from 'node:path'
3
+
4
+ const byKey = ([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)
5
+
6
+ /** Manifest references use the same labels as their generated lookups. */
7
+ export function manifestKey(pathFor, key) {
8
+ const virtual =
9
+ /(?:^|[/\\])\0?((?:(?:virtual:|#nitro\/virtual\/).+|rolldown\/runtime\.js))$/.exec(key)
10
+ return virtual ? virtual[1] : pathFor(key)
11
+ }
12
+
13
+ /** Sort Vite's generated index and keep graph edges in their original order. */
14
+ export function normalizeViteManifest(json, keyFor) {
15
+ const entries = Object.entries(JSON.parse(json)).map(([key, item]) => {
16
+ if (!Array.isArray(item)) {
17
+ if (item.src) item.src = keyFor(item.src)
18
+ if (item.imports) item.imports = item.imports.map(keyFor)
19
+ if (item.dynamicImports) item.dynamicImports = item.dynamicImports.map(keyFor)
20
+ }
21
+ return [keyFor(key), item]
22
+ })
23
+ if (new Set(entries.map(([key]) => key)).size !== entries.length)
24
+ throw new Error('Duplicate module identity in Vite manifest')
25
+ return JSON.stringify(Object.fromEntries(entries.sort(byKey)), null, 2)
26
+ }
27
+
28
+ /** Run after Vite assembles its optional standard and SSR manifests. */
29
+ export function viteManifests(state) {
30
+ return {
31
+ order: 'post',
32
+ handler(_options, bundle) {
33
+ const { manifest, ssrManifest } = this.environment.config.build
34
+ for (const [value, fallback] of [
35
+ [manifest, '.vite/manifest.json'],
36
+ [ssrManifest, '.vite/ssr-manifest.json'],
37
+ ]) {
38
+ if (!value) continue
39
+ const file = bundle[value === true ? fallback : value]
40
+ if (file?.type === 'asset')
41
+ file.source = normalizeViteManifest(file.source.toString(), state.assetKey)
42
+ }
43
+ },
44
+ }
45
+ }
46
+
47
+ function mapSource(pathFor, source, file) {
48
+ return manifestKey(pathFor, source.startsWith('file:') ? source : resolve(dirname(file), source))
49
+ }
50
+
51
+ /** Relabel sources while preserving mappings, names and positional indices. */
52
+ export function normalizeCopiedMap(json, pathFor, file) {
53
+ const map = JSON.parse(json)
54
+ map.sources = map.sources.map((source) =>
55
+ source
56
+ ? mapSource(pathFor, source, resolve(dirname(file), map.sourceRoot ?? '', 'map'))
57
+ : source,
58
+ )
59
+ delete map.sourceRoot
60
+ delete map.sourcesContent
61
+ return JSON.stringify(map)
62
+ }
63
+
64
+ /** Rolldown runs this for both external and inline maps. Generated source can contain physical imports. */
65
+ export function sourceMapOptions(options, pathFor) {
66
+ if (!options.sourcemap) return
67
+ const configured = options.sourcemapPathTransform
68
+ return {
69
+ ...options,
70
+ sourcemapExcludeSources: true,
71
+ sourcemapPathTransform(source, map) {
72
+ return mapSource(pathFor, configured?.(source, map) ?? source, resolve(options.dir, map))
73
+ },
74
+ }
75
+ }
@@ -10,7 +10,7 @@ import { shapeOverride } from './shape-override.mjs'
10
10
  * the first `)`, which a path can hold). `meta` is read once per level that renders, before the first byte: that's
11
11
  * how the entry learns the request's levels (`routeCss`), outermost first, 404 and error pages included.
12
12
  */
13
- export function serverRoutes(manifest, abs, dev, plan) {
13
+ export function serverRoutes(manifest, abs, dev, plan, assetSource = (file) => file) {
14
14
  const files = [
15
15
  ...manifest.layouts.map((l) => l.file),
16
16
  ...manifest.routes.map((r) => r.file),
@@ -23,7 +23,7 @@ export function serverRoutes(manifest, abs, dev, plan) {
23
23
  const renders = (f) => levels.has(f) && /\bdefault\b/.test(readFileSync(abs(f), 'utf8'))
24
24
  const isStatic = (f) => plan?.statics.has(abs(f))
25
25
  const clientAssets = (file) =>
26
- `import.meta.vite.assets(${JSON.stringify({ import: file, environment: 'client' }).replaceAll(')', '\\u0029')})`
26
+ `import.meta.vite.assets(${JSON.stringify({ import: assetSource(file), environment: 'client' }).replaceAll(')', '\\u0029')})`
27
27
  const css = (f) =>
28
28
  dev
29
29
  ? JSON.stringify(dev.files[f] ?? [])
@@ -264,7 +264,7 @@ export function clientRoutes(manifest, abs, plan, css = {}) {
264
264
  if (!/\.[jt]sx$/.test(file))
265
265
  return `${id}: { kind: 'unavailable', reason: 'unsupported-file', css: null, bytes: null }`
266
266
  if (kind === 'custom') {
267
- const request = `virtual:kerf/shape-override/${encodeURIComponent(file)}.tsx`
267
+ const request = `virtual:kerf/shape-override/${encodeURIComponent(css.production ? r.file : file)}.tsx`
268
268
  return `${id}: ${shape(file, 'default', request, 'override')}`
269
269
  }
270
270
  return `${id}: ${shape(file)}`
@@ -72,8 +72,25 @@ const kitGroup = (name) => (id, ctx) => (packageLazy(id, (m) => ctx.getModuleInf
72
72
  export const KIT_CHUNKS = [
73
73
  {
74
74
  name: kitGroup('icons'),
75
+ debugName: 'icons',
75
76
  test: /[\\/]node_modules[\\/]@kerf-js[\\/]veneer-icons[\\/]/,
76
77
  priority: 2,
77
78
  },
78
- { name: kitGroup('kit'), test: OWN, minShareCount: 2, priority: 1 },
79
+ { name: kitGroup('kit'), debugName: 'kit', test: OWN, minShareCount: 2, priority: 1 },
79
80
  ]
81
+
82
+ /**
83
+ * A `debugName` for each code-splitting group named by a function, which Rolldown wants for its timing report and
84
+ * warns about without. Nitro's server build has one (a chunk per package) and names it no other way.
85
+ */
86
+ export function labelChunkGroups(config, prefix) {
87
+ const outputs = [config?.output ?? []].flat()
88
+ for (const output of outputs) {
89
+ const groups = output?.codeSplitting?.groups
90
+ if (!Array.isArray(groups)) continue
91
+ for (const [i, group] of groups.entries())
92
+ if (typeof group?.name === 'function' && group.debugName === undefined)
93
+ group.debugName = `${prefix} ${i}`
94
+ }
95
+ return config
96
+ }
@@ -20,7 +20,9 @@ export function inlineSheets(outDir, base, limit = INLINE_CSS_MAX) {
20
20
  const dir = join(outDir, 'assets')
21
21
  if (!existsSync(dir)) return {}
22
22
  const sheets = {}
23
- for (const name of readdirSync(dir).filter((f) => f.endsWith('.css'))) {
23
+ for (const name of readdirSync(dir)
24
+ .sort()
25
+ .filter((f) => f.endsWith('.css'))) {
24
26
  const css = readFileSync(join(dir, name), 'utf8')
25
27
  if (
26
28
  css.length <= limit &&
@@ -79,13 +81,16 @@ export function sheetPieces(outDir, base, plan, keep, root) {
79
81
  const sheets = names
80
82
  .map((n) => [href(n), readFileSync(join(outDir, n), 'utf8')])
81
83
  .filter(([, css]) => !/<\/style|<!--/i.test(css))
82
- const old = join(root, '.kerf/sheets')
83
- mkdirSync(old, { recursive: true })
84
- for (const f of Object.keys(plan.files))
85
- writeFileSync(join(old, f.replace('assets/', '')), plan.files[f])
86
- for (const f of readdirSync(old)) {
87
- if (Date.now() - statSync(join(old, f)).mtimeMs > KEEP_SHEETS_MS) rmSync(join(old, f))
88
- else if (!existsSync(join(dir, f))) writeFileSync(join(dir, f), readFileSync(join(old, f)))
84
+ // A pinned build's asset inventory comes from its inputs, including when this cache contains older releases.
85
+ if (process.env.SOURCE_DATE_EPOCH === undefined) {
86
+ const old = join(root, '.kerf/sheets')
87
+ mkdirSync(old, { recursive: true })
88
+ for (const f of Object.keys(plan.files))
89
+ writeFileSync(join(old, f.replace('assets/', '')), plan.files[f])
90
+ for (const f of readdirSync(old).sort()) {
91
+ if (Date.now() - statSync(join(old, f)).mtimeMs > KEEP_SHEETS_MS) rmSync(join(old, f))
92
+ else if (!existsSync(join(dir, f))) writeFileSync(join(dir, f), readFileSync(join(old, f)))
93
+ }
89
94
  }
90
95
  const shape = (s) => s && { href: href(s.file), has: s.has.map(href) }
91
96
  return { ...pieces(sheets, keep), shared: shape(plan.shared), routes: plan.routes.map(shape) }