@kerf-js/start 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/LICENSE +16 -0
  2. package/README.md +1468 -2
  3. package/crate/Cargo.lock +1347 -0
  4. package/crate/Cargo.toml +72 -0
  5. package/crate/README.md +322 -0
  6. package/crate/rust-toolchain.toml +3 -0
  7. package/crate/src/build/emit.rs +103 -0
  8. package/crate/src/build.rs +367 -0
  9. package/crate/src/ctx.rs +186 -0
  10. package/crate/src/envelope.rs +163 -0
  11. package/crate/src/functions.rs +173 -0
  12. package/crate/src/lib.rs +118 -0
  13. package/crate/src/native.rs +212 -0
  14. package/crate/src/otel.rs +62 -0
  15. package/crate/src/server.rs +203 -0
  16. package/package.json +123 -3
  17. package/src/app.mjs +136 -0
  18. package/src/asset-receipt.d.mts +13 -0
  19. package/src/asset-receipt.mjs +61 -0
  20. package/src/auth/better-auth.ts +280 -0
  21. package/src/auth/drizzle.ts +17 -0
  22. package/src/auth/emails.ts +44 -0
  23. package/src/auth.ts +62 -0
  24. package/src/boot.ts +57 -0
  25. package/src/builtin.tsx +19 -0
  26. package/src/bus/postgres.ts +104 -0
  27. package/src/bus.ts +51 -0
  28. package/src/cache.ts +4 -0
  29. package/src/capture.ts +50 -0
  30. package/src/changes-sql.d.mts +20 -0
  31. package/src/changes-sql.mjs +115 -0
  32. package/src/changes.ts +352 -0
  33. package/src/channel/connections.ts +216 -0
  34. package/src/channel/socket.ts +396 -0
  35. package/src/channel-fake.ts +70 -0
  36. package/src/channel.ts +250 -0
  37. package/src/client.tsx +27 -0
  38. package/src/contract/describe.mjs +237 -0
  39. package/src/contract.mjs +299 -0
  40. package/src/cron.ts +74 -0
  41. package/src/data/after.ts +57 -0
  42. package/src/data/cache.ts +354 -0
  43. package/src/data/definitions.ts +94 -0
  44. package/src/data/draft.ts +104 -0
  45. package/src/data/foundation.ts +95 -0
  46. package/src/data/live-api.ts +22 -0
  47. package/src/data/mutation.ts +138 -0
  48. package/src/data/primitives.ts +135 -0
  49. package/src/data/query.ts +106 -0
  50. package/src/data/transport.ts +123 -0
  51. package/src/data/types.ts +333 -0
  52. package/src/data.ts +125 -0
  53. package/src/db/bun-sqlite.d.ts +13 -0
  54. package/src/db/changes-mysql.ts +126 -0
  55. package/src/db/changes-postgres.ts +238 -0
  56. package/src/db/changes-sqlite.ts +183 -0
  57. package/src/db/core.ts +95 -0
  58. package/src/db/index.ts +43 -0
  59. package/src/db/mysql.ts +84 -0
  60. package/src/db/postgres.ts +102 -0
  61. package/src/db/sqlite.ts +166 -0
  62. package/src/derive.d.mts +19 -0
  63. package/src/derive.mjs +237 -0
  64. package/src/dev-runtime.mjs +46 -0
  65. package/src/email.ts +146 -0
  66. package/src/exec/errors.ts +87 -0
  67. package/src/exec/impl.ts +21 -0
  68. package/src/exec/landing.ts +66 -0
  69. package/src/exec/limit.ts +25 -0
  70. package/src/exec/once.ts +24 -0
  71. package/src/exec/scope.ts +328 -0
  72. package/src/exec/touch.ts +80 -0
  73. package/src/exec/validation.ts +176 -0
  74. package/src/exec/warm.ts +50 -0
  75. package/src/exec.ts +400 -0
  76. package/src/extension.ts +48 -0
  77. package/src/first-paint.ts +74 -0
  78. package/src/form/value.ts +15 -0
  79. package/src/form.tsx +223 -0
  80. package/src/gate.css +6 -0
  81. package/src/hub/channels.ts +102 -0
  82. package/src/hub/connections.ts +147 -0
  83. package/src/hub/delivery.ts +62 -0
  84. package/src/hub/feed.ts +168 -0
  85. package/src/hub/presence.ts +64 -0
  86. package/src/hub/route.ts +159 -0
  87. package/src/hub/subscriptions.ts +213 -0
  88. package/src/hub/topic.ts +98 -0
  89. package/src/hub/tracked.ts +12 -0
  90. package/src/hub/types.ts +190 -0
  91. package/src/hub/view.ts +147 -0
  92. package/src/hub.ts +196 -0
  93. package/src/index.ts +184 -0
  94. package/src/inline.mjs +359 -0
  95. package/src/inspect/compare.mjs +162 -0
  96. package/src/inspect/routes.mjs +154 -0
  97. package/src/inspect/samples.mjs +59 -0
  98. package/src/inspect/url.mjs +2 -0
  99. package/src/inspect.mjs +239 -0
  100. package/src/jobs.ts +223 -0
  101. package/src/link/election.ts +178 -0
  102. package/src/link/lines.ts +27 -0
  103. package/src/link.ts +385 -0
  104. package/src/list-drizzle.ts +136 -0
  105. package/src/list.ts +315 -0
  106. package/src/listen.ts +54 -0
  107. package/src/live/api.ts +18 -0
  108. package/src/live/backoff.ts +6 -0
  109. package/src/live/frames.ts +42 -0
  110. package/src/live/read.ts +77 -0
  111. package/src/live/sub-types.ts +24 -0
  112. package/src/live/transport.ts +86 -0
  113. package/src/live/types.ts +52 -0
  114. package/src/live-fake.ts +57 -0
  115. package/src/live-target.mjs +231 -0
  116. package/src/live.ts +390 -0
  117. package/src/media.ts +50 -0
  118. package/src/migrations.mjs +27 -0
  119. package/src/mux-session.ts +6 -0
  120. package/src/mux.ts +232 -0
  121. package/src/og/DefaultCard.tsx +91 -0
  122. package/src/og/fonts.mjs +72 -0
  123. package/src/og/images.mjs +124 -0
  124. package/src/og/index.mjs +222 -0
  125. package/src/og/native.mjs +36 -0
  126. package/src/range.mjs +31 -0
  127. package/src/router.ts +199 -0
  128. package/src/routes.mjs +193 -0
  129. package/src/run/admission.ts +67 -0
  130. package/src/run/boot.tsx +115 -0
  131. package/src/run/cache-presentation.ts +67 -0
  132. package/src/run/cache.ts +254 -0
  133. package/src/run/helpers.ts +197 -0
  134. package/src/run/listeners.ts +166 -0
  135. package/src/run/navigation.ts +385 -0
  136. package/src/run/page-skeleton.tsx +35 -0
  137. package/src/run/prefetch.ts +129 -0
  138. package/src/run/retain-view.ts +18 -0
  139. package/src/run/shape-preparation.ts +97 -0
  140. package/src/run/shape-styles.ts +72 -0
  141. package/src/run/source-context/pin.ts +124 -0
  142. package/src/run/source-context.ts +311 -0
  143. package/src/run.tsx +74 -0
  144. package/src/rust/common.ts +163 -0
  145. package/src/rust/native.ts +282 -0
  146. package/src/rust.ts +207 -0
  147. package/src/server/background.ts +34 -0
  148. package/src/server/card.tsx +65 -0
  149. package/src/server/compression.ts +115 -0
  150. package/src/server/core.ts +70 -0
  151. package/src/server/cron.ts +49 -0
  152. package/src/server/dispatch.ts +73 -0
  153. package/src/server/form.ts +92 -0
  154. package/src/server/functions.ts +133 -0
  155. package/src/server/handler.ts +57 -0
  156. package/src/server/head.ts +96 -0
  157. package/src/server/health.ts +36 -0
  158. package/src/server/jobs.ts +112 -0
  159. package/src/server/lifecycle.ts +48 -0
  160. package/src/server/log.ts +42 -0
  161. package/src/server/media.ts +61 -0
  162. package/src/server/navigation-cache.ts +75 -0
  163. package/src/server/navigation.tsx +86 -0
  164. package/src/server/page-cold.ts +96 -0
  165. package/src/server/page-stream.tsx +181 -0
  166. package/src/server/page-types.ts +51 -0
  167. package/src/server/page-warm.ts +131 -0
  168. package/src/server/page.ts +69 -0
  169. package/src/server/payload.ts +89 -0
  170. package/src/server/prerender.ts +64 -0
  171. package/src/server/preview.tsx +67 -0
  172. package/src/server/render.ts +197 -0
  173. package/src/server/request.ts +192 -0
  174. package/src/server/resolver.ts +228 -0
  175. package/src/server/routes.ts +150 -0
  176. package/src/server/security.ts +50 -0
  177. package/src/server/services.ts +69 -0
  178. package/src/server/shutdown.ts +23 -0
  179. package/src/server/text.ts +29 -0
  180. package/src/server/types.ts +170 -0
  181. package/src/server.tsx +138 -0
  182. package/src/shape.d.mts +3 -0
  183. package/src/shape.mjs +97 -0
  184. package/src/share/display.ts +50 -0
  185. package/src/share/network.ts +119 -0
  186. package/src/share/receive.ts +70 -0
  187. package/src/share/state.ts +30 -0
  188. package/src/share/tab-queue.ts +28 -0
  189. package/src/share-server.ts +293 -0
  190. package/src/share.ts +397 -0
  191. package/src/sheets.mjs +87 -0
  192. package/src/sidecar/build.mjs +170 -0
  193. package/src/sidecar/cargo.mjs +164 -0
  194. package/src/sidecar/common.mjs +17 -0
  195. package/src/sidecar/dev-build.mjs +91 -0
  196. package/src/sidecar/dev-watch.mjs +88 -0
  197. package/src/sidecar/manifest.mjs +19 -0
  198. package/src/sidecar/process.mjs +58 -0
  199. package/src/sidecar/refresh.mjs +19 -0
  200. package/src/sidecar.mjs +162 -0
  201. package/src/socket/check.ts +50 -0
  202. package/src/socket/deliver.ts +16 -0
  203. package/src/socket/publish.ts +56 -0
  204. package/src/socket/rooms.ts +41 -0
  205. package/src/socket/route.ts +79 -0
  206. package/src/socket/shared.ts +26 -0
  207. package/src/socket/types.ts +48 -0
  208. package/src/socket.ts +400 -0
  209. package/src/stream.ts +22 -0
  210. package/src/verify/app.ts +39 -0
  211. package/src/verify/cleanup.ts +27 -0
  212. package/src/verify/database.ts +11 -0
  213. package/src/verify/live.ts +63 -0
  214. package/src/verify/notify.ts +35 -0
  215. package/src/verify/skip.ts +19 -0
  216. package/src/verify/support.ts +149 -0
  217. package/src/verify/timing.ts +15 -0
  218. package/src/verify/trigger.ts +14 -0
  219. package/src/verify.ts +152 -0
  220. package/src/view.tsx +132 -0
  221. package/src/vite/asset-bytes.mjs +95 -0
  222. package/src/vite/assets.mjs +117 -0
  223. package/src/vite/config-hooks.mjs +166 -0
  224. package/src/vite/dev-hooks.mjs +103 -0
  225. package/src/vite/dev.mjs +102 -0
  226. package/src/vite/entries.mjs +149 -0
  227. package/src/vite/module-hooks.mjs +290 -0
  228. package/src/vite/route-modules.mjs +289 -0
  229. package/src/vite/server-functions.mjs +222 -0
  230. package/src/vite/shape-entry-css.mjs +187 -0
  231. package/src/vite/shape-override.mjs +226 -0
  232. package/src/vite/shared.mjs +55 -0
  233. package/src/vite/sheets.mjs +92 -0
  234. package/src/vite/state.mjs +89 -0
  235. package/src/vite/syntax.mjs +139 -0
  236. package/src/vite.mjs +202 -0
@@ -0,0 +1,149 @@
1
+ import { existsSync, readFileSync } from 'node:fs'
2
+ import { createRequire } from 'node:module'
3
+ import { join } from 'node:path'
4
+ import { scanRequired } from '../live-target.mjs'
5
+ import { here, V, purgeFile, INLINE_SHEETS, SHEET_PIECES, ROUTE_ASSET_BYTES } from './shared.mjs'
6
+
7
+ export function serverEntry(clientEntry, dev, root) {
8
+ return `import { createHandler, serverLog } from ${JSON.stringify(join(here, 'server.tsx'))}
9
+ import { chunks, lazy, manifest, modules, routeCss, statics } from '${V.routes}'
10
+ import '${V.fns}'
11
+ import context from '${V.context}'
12
+ import auth from '${V.auth}'
13
+ import migrations from '${V.migrations}'
14
+ import media from '${V.media}'
15
+ import realtime from '${V.realtime}'
16
+ import cache from '${V.cache}'
17
+ import cron from '${V.cron}'
18
+ import email from '${V.email}'
19
+ import jobs from '${V.jobs}'
20
+ import extensions from '${V.extensions}'
21
+ import * as app from '${V.app}'
22
+ import assets from '${clientEntry}?assets=client'
23
+ import { preloads } from 'kerf:fonts/preloads'
24
+ ${dev ? '' : `import { parse, purge } from ${JSON.stringify(purgeFile)}\n`}const fetch = createHandler({ manifest, 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 }'} },
25
+ // H005–H008, Q002–Q014, A002–A004, F002–F003, M017 and R-codes found while serving: the server log, in dev and production.
26
+ onDiagnostic: serverLog(app.site) })
27
+ export default { fetch }
28
+ ${dev ? "import { acceptScopeReruns } from '@kerf-js/core/hmr'\nacceptScopeReruns()\n" : ''}`
29
+ }
30
+
31
+ /**
32
+ * A `server.extension` provider runs only for an app with `src/<key>.server.ts`, the file that says it wants it (P118):
33
+ * the provider is loaded on the first request and handed that file's default export. No provider gives an empty list.
34
+ */
35
+ export function extensionsModule(root, abs) {
36
+ const slot = join(root, '.kerf', 'slots', 'server.extension.ts')
37
+ const keys = existsSync(slot)
38
+ ? Object.entries(
39
+ JSON.parse(/providers = (\{.*\}) as const/.exec(readFileSync(slot, 'utf8'))?.[1] ?? '{}'),
40
+ )
41
+ .filter(([, name]) => name)
42
+ .map(([key]) => key)
43
+ : []
44
+ const files = keys.flatMap((key) => {
45
+ const f = ['ts', 'mts', 'js', 'mjs']
46
+ .map((x) => `src/${key}.server.${x}`)
47
+ .find((x) => existsSync(abs(x)))
48
+ return f ? [[key, abs(f)]] : []
49
+ })
50
+ if (!files.length) return 'export default []\n'
51
+ return `import { load } from 'kerf:slot/server.extension'\n${files.map(([, f], i) => `import app${i} from ${JSON.stringify(f)}\n`).join('')}export default [${files.map(([key], i) => `{ key: ${JSON.stringify(key)}, load: () => load(${JSON.stringify(key)}).then(extend => extend(app${i})) }`).join(', ')}]\n`
52
+ }
53
+
54
+ /** Dev serves from the project; a built server from the directory it runs in (or `KERF_MEDIA_DIR`). */
55
+ export function mediaModule(root, dev) {
56
+ const slot = join(root, '.kerf', 'slots', 'media.server.ts')
57
+ if (!existsSync(slot) || readFileSync(slot, 'utf8').includes('provider = null'))
58
+ return 'export default undefined\n'
59
+ const at = dev ? JSON.stringify(root) : 'undefined'
60
+ if (!existsSync(join(root, '.kerf', 'slots', 'media.encode.ts')))
61
+ return `import { load } from 'kerf:slot/media.server'\nexport default () => load().then(m => m.at(${at}))\n`
62
+ return `import { load } from 'kerf:slot/media.server'
63
+ import { load as encoder, providers } from 'kerf:slot/media.encode'
64
+ const encode = async () => Object.fromEntries(await Promise.all(Object.keys(providers).filter(k => providers[k]).map(async k => [k, await encoder(k)])))
65
+ export default () => Promise.all([load(), encode()]).then(([m, e]) => m.at(${at}, e))
66
+ `
67
+ }
68
+
69
+ export const busBound = (root) => {
70
+ const slot = join(root, '.kerf', 'slots', 'realtime.bus.ts')
71
+ return existsSync(slot) && readFileSync(slot, 'utf8').includes('provider = {')
72
+ }
73
+
74
+ /** A bus in `src/realtime.server.ts` wins over the plugin's, like any explicit choice. */
75
+ export const busModule = (file, from) => `import { load, provider } from 'kerf:slot/realtime.bus'
76
+ import { slotBus } from ${JSON.stringify(join(from, 'bus.ts'))}
77
+ ${file ? `import own from ${JSON.stringify(file)}` : 'const own = undefined'}
78
+ export default { ...own, bus: own?.bus ?? slotBus(provider.plugin, load) }
79
+ `
80
+
81
+ export function appModule({ site, build, dev, fonts, timeout, hold }) {
82
+ return `export const site = ${JSON.stringify(site)}
83
+ export const build = ${JSON.stringify(build)}
84
+ export const dev = ${dev}
85
+ export const timeout = ${timeout ?? 'undefined'}
86
+ export const hold = ${hold ?? 'undefined'}
87
+ const raw = ${JSON.stringify(fonts)}
88
+ let decoded
89
+ export function fonts() {
90
+ return (decoded ??= raw.map(f => ({ ...f, data: Uint8Array.from(atob(f.data), c => c.charCodeAt(0)) })))
91
+ }
92
+ `
93
+ }
94
+
95
+ /**
96
+ * The fonts every card can use, resolved at build and shipped inside the server bundle (research 20 §4.2: a render
97
+ * never fetches fonts). `Inter:400,700` → `@fontsource/inter`'s latin WOFF2 files, from the app or from @kerf-js/start.
98
+ */
99
+ export function cardFonts(manifest, abs, defaults, root, own = {}) {
100
+ const specs = new Set(defaults)
101
+ for (const f of [...manifest.routes.map((r) => r.card), manifest.defaultCard].filter(Boolean)) {
102
+ const m = /export\s+const\s+fonts\s*=\s*\[([^\]]*)\]/.exec(readFileSync(abs(f), 'utf8'))
103
+ if (m) for (const s of m[1].matchAll(/['"]([^'"]+)['"]/g)) specs.add(s[1])
104
+ }
105
+ const requires = [
106
+ createRequire(join(root, 'package.json')),
107
+ createRequire(join(here, 'vite.mjs')),
108
+ ]
109
+ const out = []
110
+ // The app's own faces (`site.card.fonts`, filled in by the text plugin): the card's title and text look like the app.
111
+ for (const f of [own.display, own.body].filter(Boolean)) {
112
+ const path = join(root, f.src)
113
+ if (existsSync(path) && !out.some((x) => x.name === f.family))
114
+ out.push({
115
+ name: f.family,
116
+ weight: f.weight ?? 400,
117
+ style: 'normal',
118
+ data: readFileSync(path).toString('base64'),
119
+ })
120
+ }
121
+ for (const spec of specs) {
122
+ const [family, weights = '400'] = spec.split(':')
123
+ const pkg = family.toLowerCase().replace(/\s+/g, '-')
124
+ for (const w of weights.split(',')) {
125
+ const [weight, italic] = [Number.parseInt(w), /i(talic)?$/.test(w)]
126
+ const file = `@fontsource/${pkg}/files/${pkg}-latin-${weight}-${italic ? 'italic' : 'normal'}.woff2`
127
+ const path = requires
128
+ .map((r) => {
129
+ try {
130
+ return r.resolve(file)
131
+ } catch {
132
+ return undefined
133
+ }
134
+ })
135
+ .find(Boolean)
136
+ if (!path)
137
+ throw new Error(
138
+ `kerf: card font \`${spec}\` needs \`@fontsource/${pkg}\` installed (looked for ${file})`,
139
+ )
140
+ out.push({
141
+ name: family,
142
+ weight,
143
+ style: italic ? 'italic' : 'normal',
144
+ data: readFileSync(path).toString('base64'),
145
+ })
146
+ }
147
+ }
148
+ return out
149
+ }
@@ -0,0 +1,290 @@
1
+ import { existsSync, readFileSync } from 'node:fs'
2
+ import { createRequire } from 'node:module'
3
+ import { dirname, join, relative, resolve } from 'node:path'
4
+ import { readMigrations } from '../migrations.mjs'
5
+ import { routeTypes } from '../routes.mjs'
6
+ import { assetsOnly } from './assets.mjs'
7
+ import { entryCss, projectParent, watchEntryCandidates } from './shape-entry-css.mjs'
8
+ import { resolveImportedOverride, shapeOverride } from './shape-override.mjs'
9
+ import {
10
+ clientRoutes,
11
+ serverRoutes,
12
+ devStyles,
13
+ markLinks,
14
+ skeletonExport,
15
+ } from './route-modules.mjs'
16
+ import {
17
+ serverEntry,
18
+ extensionsModule,
19
+ mediaModule,
20
+ busBound,
21
+ busModule,
22
+ appModule,
23
+ cardFonts,
24
+ } from './entries.mjs'
25
+ import { stripServerExports, serverExports } from './syntax.mjs'
26
+ import { isServerModule, definesFns, withIds, clientStubs } from './server-functions.mjs'
27
+ import { here, V, DEFAULT_FONTS, ASSETS, ISLAND, ENTRY_SHEETS } from './shared.mjs'
28
+
29
+ /** Virtual modules that are an app file's default export: `src/<name>.server.ts`, or `undefined` without one. */
30
+ const CONFIG_FILES = new Set([V.context, V.auth, V.realtime, V.cache, V.cron, V.email, V.jobs])
31
+
32
+ export const resolveId = (s) => ({
33
+ filter: {
34
+ id: /^(virtual:kerf\/|@kerf-js\/start\/(db|auth|bus|list|rust|sidecar)(\/|$)|@kerf-js\/(realtime-(redis|nats|durable-object)|db-[\w-]+)$|sharp$)/,
35
+ },
36
+ handler(source, importer) {
37
+ // Sharp's addon can't be bundled, so it stays external and Nitro traces it, which it can only do from the app.
38
+ if (source === 'sharp') {
39
+ if (s.dev || !/[\\/](@kerf-js[\\/]media|packages[\\/]media)[\\/]/.test(importer ?? '')) return
40
+ try {
41
+ createRequire(join(s.root, 'package.json')).resolve('sharp')
42
+ } catch {
43
+ this.warn(
44
+ "M017: `sharp` isn't a dependency of this app, so the built server can't load it for the media route.\n fix: add `sharp` to dependencies",
45
+ )
46
+ return
47
+ }
48
+ return { id: 'sharp', external: true }
49
+ }
50
+ if (source.startsWith('@kerf-js/')) {
51
+ if (this.environment?.config.consumer === 'client')
52
+ this.error(
53
+ `Q012: \`${source}\` reached the client graph${importer ? ` from ${relative(s.root, importer)}` : ''}: the database, auth and buses run on the server only.\n fix: import it from a server module (src/server/**, *.server.ts) or a route's \`load\``,
54
+ )
55
+ return
56
+ }
57
+ const base = source.replace(/\?.*$/, '')
58
+ if (
59
+ Object.values(V).includes(base) ||
60
+ base.startsWith(ISLAND) ||
61
+ base.startsWith('virtual:kerf/shape-override/')
62
+ )
63
+ return s.id(source)
64
+ },
65
+ })
66
+
67
+ export const load = (s) => ({
68
+ filter: { id: /^\0virtual:kerf\// },
69
+ async handler(raw) {
70
+ // `virtual:kerf/entry-client?assets=client` (no src/entry.client.ts) is Nitro's assets plugin's to load.
71
+ if (/[?&]assets\b/.test(raw)) return
72
+ const which = raw.slice(1).replace(/\?.*$/, '')
73
+ const client = this.environment?.config.consumer === 'client'
74
+ if (which.startsWith('virtual:kerf/shape-override/'))
75
+ return overrideModule(this, s, which, client)
76
+ if (which.startsWith(ISLAND)) {
77
+ const { islands } = await s.hydration(this)
78
+ const i = islands[Number(which.slice(ISLAND.length))]
79
+ return `export { $i${i.index} as default } from ${JSON.stringify(i.file)}\n`
80
+ }
81
+ if (which === V.routes) return routesModule(this, s, client)
82
+ if (which === V.app)
83
+ return appModule({
84
+ site: s.options.site ?? {},
85
+ build: s.build,
86
+ dev: s.dev,
87
+ fonts: cardFonts(
88
+ s.manifest,
89
+ s.abs,
90
+ s.options.fonts ?? DEFAULT_FONTS,
91
+ s.root,
92
+ s.options.site?.card?.fonts,
93
+ ),
94
+ timeout: s.options.timeout,
95
+ hold: s.options.hold,
96
+ })
97
+ if (which === V.server) return serverEntry(s.clientEntry(), s.dev, s.root)
98
+ if (which === V.fns)
99
+ return s.serverModules.map((f) => `import ${JSON.stringify(s.abs(f))}`).join('\n') + '\n'
100
+ if (CONFIG_FILES.has(which)) return configModule(s, which)
101
+ if (which === V.extensions) return extensionsModule(s.root, s.abs)
102
+ if (which === V.migrations)
103
+ return s.dev
104
+ ? `import { readMigrations } from ${JSON.stringify(join(here, 'migrations.mjs'))}\nexport default () => readMigrations(${JSON.stringify(s.root)})\n`
105
+ : `const list = ${JSON.stringify(readMigrations(s.root))}\nexport default () => list\n`
106
+ if (which === V.media) return mediaModule(s.root, s.dev)
107
+ if (which === V.client)
108
+ return `import { start } from ${JSON.stringify(join(here, 'client.tsx'))}\nimport * as routes from '${V.routes}'\n${ENTRY_SHEETS}start(routes)\n`
109
+ },
110
+ })
111
+
112
+ export const transform = (s) => ({
113
+ filter: { id: /\.[jt]sx?(\?kerf-assets)?$|\/vite\/dist\/client\/client\.mjs$/ },
114
+ async handler(code, file) {
115
+ const path = file.replace(/\?.*$/, '')
116
+ if (file.endsWith(ASSETS))
117
+ return { code: await assetsOnly(this, code, path, s.root, s.words), map: null }
118
+ if (path.endsWith('/client.mjs')) return s.dev ? markLinks(s.root) + code : undefined
119
+ if (path.includes('/node_modules/')) return
120
+ const client = this.environment?.config.consumer === 'client'
121
+ if (client && path === s.clientEntry()) return { code: ENTRY_SHEETS + code, map: null }
122
+ const rel = relative(s.root, path).split('\\').join('/')
123
+ if (isServerModule(rel)) {
124
+ const out = client
125
+ ? clientStubs(code, path, rel, await s.shapeTable(this))
126
+ : withIds(code, path, rel)
127
+ if (client && s.dev) s.stubs.set(path, out)
128
+ return out === code ? undefined : { code: out, map: null }
129
+ }
130
+ if (client && !rel.startsWith('..')) {
131
+ const q003 = definesFns(code, path)
132
+ if (q003)
133
+ this.error(
134
+ `Q003: ${rel} defines \`${q003.name}\` with \`${q003.kind}()\`, but it isn't a server module: its \`run\` and imports would ship to the client.\n fix: move it to src/server/ or a *.server.ts file`,
135
+ )
136
+ }
137
+ if (!client) return
138
+ if (
139
+ !s.manifest.routes.some((r) => r.file === rel) &&
140
+ !s.manifest.layouts.some((l) => l.file === rel)
141
+ )
142
+ return
143
+ if (s.dev) s.loaders.set(file, serverExports(code, file))
144
+ const out = stripServerExports(code, file)
145
+ // @kerf-js/core/hmr saw the server exports and left this to Vite, but they're gone and the rest is components.
146
+ if (
147
+ s.dev &&
148
+ out !== code &&
149
+ !/^export (?!default\b|\{ \S+\$shape as default\$shape \})/m.test(out) &&
150
+ !out.includes('import.meta.hot.accept(')
151
+ )
152
+ return { code: `${out}\nif (import.meta.hot) import.meta.hot.accept();\n`, map: null }
153
+ return out === code ? undefined : { code: out, map: null }
154
+ },
155
+ })
156
+
157
+ export const api = (s) => ({
158
+ manifest: () => s.manifest ?? s.scan(),
159
+ types: () => routeTypes(s.manifest ?? s.scan()),
160
+ serverModules: () => (s.manifest ?? s.scan(), s.serverModules),
161
+ })
162
+
163
+ /** What a route's imported skeleton gave: a file to watch, an override to use, or nothing (said so). */
164
+ function took(ctx, { s, root, file, found, depend, overrides }) {
165
+ if (found?.file) depend(found.file, file)
166
+ if (found?.code) overrides.set(file, found.code)
167
+ // An imported function that isn't plain markup is as unusable as a local one.
168
+ else unusableSkeleton(ctx, s, root, file)
169
+ }
170
+
171
+ /** A route that exports `skeleton` in a form navigation can't use gets none at all: say so once, with what works. */
172
+ function unusableSkeleton(ctx, s, root, file) {
173
+ if (!/export\s+const\s+skeleton\b/.test(readFileSync(file, 'utf8'))) return
174
+ const warned = (s.skeletonWarned ??= new Set())
175
+ if (warned.has(file)) return
176
+ warned.add(file)
177
+ ctx.warn(
178
+ `${relative(root, file)}: \`export const skeleton\` can't be used, so this route shows no skeleton. ` +
179
+ 'Name a function in this file (or one imported from its own file) whose JSX is plain markup: div, span, section, ' +
180
+ 'article, main, header, footer, p, h1-h6, ul, ol, li, with only string class and data-* attributes. ' +
181
+ '`export const skeleton = false` turns it off. `kerf docs start` has an example.',
182
+ )
183
+ }
184
+
185
+ async function overrideModule(ctx, s, which, client) {
186
+ if (!client || !which.endsWith('.tsx')) ctx.error('Invalid skeleton override request')
187
+ const file = decodeURIComponent(which.slice('virtual:kerf/shape-override/'.length, -4))
188
+ const levels = [...s.manifest.layouts, ...s.manifest.routes]
189
+ if (!levels.some((level) => s.abs(level.file) === file)) ctx.error('Unknown skeleton override')
190
+ const imported = await resolveImportedOverride(ctx, file, s.root ?? dirname(file))
191
+ const code = shapeOverride(file) ?? imported?.code
192
+ if (!code) ctx.error(`Unsafe or missing skeleton override: ${file}`)
193
+ ctx.addWatchFile(file)
194
+ if (imported?.file) ctx.addWatchFile(imported.file)
195
+ return code
196
+ }
197
+
198
+ function configModule(s, which) {
199
+ const name = which.slice('virtual:kerf/'.length)
200
+ const f = ['ts', 'mts', 'js', 'mjs']
201
+ .map((x) => `src/${name}.server.${x}`)
202
+ .find((x) => existsSync(s.abs(x)))
203
+ if (which === V.realtime && busBound(s.root)) return busModule(f && s.abs(f), here)
204
+ return f ? `export { default } from ${JSON.stringify(s.abs(f))}\n` : 'export default undefined\n'
205
+ }
206
+
207
+ async function routesModule(ctx, s, client) {
208
+ const run = { owner: s.shapeEntryOwner, scan: undefined }
209
+ if (client && s.shapeEntryClosed) throw new Error('entry style scan outlived its server')
210
+ if (client)
211
+ run.scan = s.shapeScanActive = s.shapeScanGeneration = (s.shapeScanGeneration ?? 0) + 1
212
+ try {
213
+ const p = await s.hydration(ctx)
214
+ if (client) return await clientRoutesModule(ctx, s, p, run)
215
+ return serverRoutes(
216
+ s.manifest,
217
+ s.abs,
218
+ s.dev
219
+ ? await devStyles(s.vite.environments.client, s.manifest, s.abs, s.clientEntry())
220
+ : undefined,
221
+ p,
222
+ )
223
+ } finally {
224
+ if (client && s.shapeScanActive === run.scan) delete s.shapeScanActive
225
+ }
226
+ }
227
+
228
+ async function scanOverrides(ctx, s, all, root) {
229
+ const overrides = new Map()
230
+ const dependencies = new Map()
231
+ const missing = new Set()
232
+ const depend = (target, file) => {
233
+ if (!dependencies.has(target)) dependencies.set(target, new Set())
234
+ dependencies.get(target).add(file)
235
+ }
236
+ for (const file of all) {
237
+ if (!/\.[jt]sx$/.test(file) || skeletonExport(file) !== 'unavailable') continue
238
+ const found = await resolveImportedOverride(ctx, file, root, (spec) => {
239
+ const candidate = resolve(dirname(file), spec)
240
+ if (projectParent(root, candidate)) {
241
+ const path = candidate.replace(/\\/g, '/')
242
+ missing.add(path)
243
+ depend(path, file)
244
+ }
245
+ })
246
+ took(ctx, { s, root, file, found, depend, overrides })
247
+ }
248
+ return { overrides, dependencies, missing }
249
+ }
250
+
251
+ async function clientRoutesModule(ctx, s, p, run) {
252
+ const entry = s.clientEntry()
253
+ const entryFile = entry.startsWith('virtual:') ? join(here, 'client.tsx') : entry
254
+ const levels = [...s.manifest.layouts, ...s.manifest.routes]
255
+ const all = [...new Set(levels.map((r) => s.abs(r.file)))]
256
+ const root = s.root ?? dirname(entryFile)
257
+ const { overrides, dependencies, missing } = await scanOverrides(ctx, s, all, root)
258
+ const files = all.filter(
259
+ (file) =>
260
+ /\.[jt]sx$/.test(file) &&
261
+ (overrides.has(file) || ['generated', 'custom'].includes(skeletonExport(file))),
262
+ )
263
+ const sources = await Promise.all(files.map((file) => entryCss(ctx, file, root)))
264
+ const shared = await entryCss(ctx, entryFile, root)
265
+ if (run.owner && run.owner !== s.shapeEntryOwner)
266
+ throw new Error('entry style scan outlived its server')
267
+ if (run.scan !== s.shapeScanGeneration) throw new Error('entry style scan superseded')
268
+ for (const source of sources) {
269
+ for (const [file, signature] of source.signatures) shared.signatures.set(file, signature)
270
+ for (const file of source.candidates) shared.candidates.add(file)
271
+ for (const file of source.missing) shared.missing.add(file)
272
+ }
273
+ for (const file of missing) {
274
+ shared.candidates.add(file)
275
+ shared.missing.add(file)
276
+ }
277
+ const css = {
278
+ entry: shared.styles,
279
+ levels: new Map(files.map((file, i) => [file, sources[i].styles])),
280
+ overrides,
281
+ build: s.build || null,
282
+ }
283
+ const output = clientRoutes(s.manifest, s.abs, p, css)
284
+ s.shapeEntrySignatures = shared.signatures
285
+ s.shapeEntryCandidates = shared.candidates
286
+ s.shapeEntryMissing = shared.missing
287
+ s.shapeOverrideDependencies = dependencies
288
+ if (s.dev) watchEntryCandidates(s.vite, shared.missing, root)
289
+ return output
290
+ }