@c9up/ream 0.2.23 → 0.2.25
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/dist/Codemods.d.ts +1 -0
- package/dist/Codemods.d.ts.map +1 -1
- package/dist/Codemods.js +44 -0
- package/dist/Codemods.js.map +1 -1
- package/dist/Ignitor.d.ts +50 -0
- package/dist/Ignitor.d.ts.map +1 -1
- package/dist/Ignitor.js +15 -15
- package/dist/Ignitor.js.map +1 -1
- package/dist/dev/fullReload.d.ts +23 -0
- package/dist/dev/fullReload.d.ts.map +1 -0
- package/dist/dev/fullReload.js +26 -0
- package/dist/dev/fullReload.js.map +1 -0
- package/dist/dev/hmr.d.ts +52 -4
- package/dist/dev/hmr.d.ts.map +1 -1
- package/dist/dev/hmr.js +75 -9
- package/dist/dev/hmr.js.map +1 -1
- package/dist/dev/hotGlob.d.ts +35 -0
- package/dist/dev/hotGlob.d.ts.map +1 -0
- package/dist/dev/hotGlob.js +92 -0
- package/dist/dev/hotGlob.js.map +1 -0
- package/dist/dev/hotGraph.d.ts +58 -0
- package/dist/dev/hotGraph.d.ts.map +1 -0
- package/dist/dev/hotGraph.js +91 -0
- package/dist/dev/hotGraph.js.map +1 -0
- package/dist/dev/hotWatcher.d.ts +34 -0
- package/dist/dev/hotWatcher.d.ts.map +1 -0
- package/dist/dev/hotWatcher.js +72 -0
- package/dist/dev/hotWatcher.js.map +1 -0
- package/dist/env/loadEnvFiles.d.ts +13 -0
- package/dist/env/loadEnvFiles.d.ts.map +1 -1
- package/dist/env/loadEnvFiles.js +65 -13
- package/dist/env/loadEnvFiles.js.map +1 -1
- package/dist/hot.d.ts +13 -16
- package/dist/hot.d.ts.map +1 -1
- package/dist/hot.js +161 -84
- package/dist/hot.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/events.darwin-arm64.node +0 -0
- package/events.darwin-x64.node +0 -0
- package/events.linux-arm64-gnu.node +0 -0
- package/events.linux-x64-gnu.node +0 -0
- package/events.win32-x64-msvc.node +0 -0
- package/index.darwin-arm64.node +0 -0
- package/index.darwin-x64.node +0 -0
- package/index.linux-arm64-gnu.node +0 -0
- package/index.linux-x64-gnu.node +0 -0
- package/index.win32-x64-msvc.node +0 -0
- package/package.json +4 -7
- package/scheduler.darwin-arm64.node +0 -0
- package/scheduler.darwin-x64.node +0 -0
- package/scheduler.linux-arm64-gnu.node +0 -0
- package/scheduler.linux-x64-gnu.node +0 -0
- package/scheduler.win32-x64-msvc.node +0 -0
- package/src/Codemods.ts +53 -0
- package/src/Ignitor.ts +68 -14
- package/src/dev/fullReload.ts +34 -0
- package/src/dev/hmr.ts +102 -9
- package/src/dev/hotGlob.ts +91 -0
- package/src/dev/hotGraph.ts +109 -0
- package/src/dev/hotWatcher.ts +89 -0
- package/src/env/loadEnvFiles.ts +69 -14
- package/src/hot.ts +169 -102
- package/src/index.ts +1 -1
package/src/Codemods.ts
CHANGED
|
@@ -3,6 +3,7 @@ import * as path from 'node:path'
|
|
|
3
3
|
|
|
4
4
|
export interface Codemods {
|
|
5
5
|
addProvider(importPath: string): Promise<void>
|
|
6
|
+
addMetaFile(pattern: string, reloadServer?: boolean): Promise<void>
|
|
6
7
|
addEnvVars(vars: Record<string, string>): Promise<void>
|
|
7
8
|
writeFile(filePath: string, content: string, options?: { force?: boolean }): Promise<void>
|
|
8
9
|
registerCommand(importPath: string): Promise<void>
|
|
@@ -120,6 +121,58 @@ export function createCodemods(options?: { force?: boolean; cwd?: string }): Cod
|
|
|
120
121
|
fs.writeFileSync(rcPath, content)
|
|
121
122
|
},
|
|
122
123
|
|
|
124
|
+
/**
|
|
125
|
+
* Record a non-module file the application owns.
|
|
126
|
+
*
|
|
127
|
+
* A package calls this from `configure()` so its files reach the build:
|
|
128
|
+
* `addMetaFile('resources/lang/**\/*.json', false)`. The second argument
|
|
129
|
+
* is DELIBERATELY explicit at every call site — whether an edit costs a
|
|
130
|
+
* development restart is the decision the entry exists to record.
|
|
131
|
+
*
|
|
132
|
+
* Same regex codemod as `addProvider`, and the same limits: a `metaFiles`
|
|
133
|
+
* assembled by a spread or extracted into a `const` above the config is not
|
|
134
|
+
* rewritten. The block is created when absent, which `addProvider` cannot
|
|
135
|
+
* do — `providers` is always there, `metaFiles` usually is not.
|
|
136
|
+
*/
|
|
137
|
+
async addMetaFile(pattern: string, reloadServer = false): Promise<void> {
|
|
138
|
+
const rcPath = path.join(root, 'reamrc.ts')
|
|
139
|
+
if (!fs.existsSync(rcPath)) {
|
|
140
|
+
throw new Error(
|
|
141
|
+
`[configure] reamrc.ts not found — cannot register meta file ${pattern}. Run 'ream new' first.`,
|
|
142
|
+
)
|
|
143
|
+
}
|
|
144
|
+
assertCanonicallyInside(root, rcPath, 'reamrc.ts')
|
|
145
|
+
|
|
146
|
+
let content = fs.readFileSync(rcPath, 'utf8')
|
|
147
|
+
// Dedup on the PATTERN alone: the same glob registered twice with
|
|
148
|
+
// different flags is a contradiction, and the first one wins rather than
|
|
149
|
+
// both being written.
|
|
150
|
+
if (content.includes(`'${pattern}'`) || content.includes(`"${pattern}"`)) return
|
|
151
|
+
|
|
152
|
+
const eol = detectLineEnding(content)
|
|
153
|
+
const entry = ` { pattern: '${pattern}', reloadServer: ${reloadServer} },`
|
|
154
|
+
|
|
155
|
+
const existing = /metaFiles\s*:\s*(?:\/\*[\s\S]*?\*\/\s*)?\[/.exec(content)
|
|
156
|
+
if (existing !== null) {
|
|
157
|
+
const insertAt = existing.index + existing[0].length
|
|
158
|
+
content = `${content.slice(0, insertAt)}${eol}${entry}${content.slice(insertAt)}`
|
|
159
|
+
fs.writeFileSync(rcPath, content)
|
|
160
|
+
return
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// No block yet — open one beside `providers`, which every rc file has.
|
|
164
|
+
const providers = /providers\s*:\s*(?:\/\*[\s\S]*?\*\/\s*)?\[/.exec(content)
|
|
165
|
+
if (providers === null) {
|
|
166
|
+
throw new Error(
|
|
167
|
+
`[configure] Could not find 'providers: [' in reamrc.ts — meta file ${pattern} not added. Check your reamrc.ts format.`,
|
|
168
|
+
)
|
|
169
|
+
}
|
|
170
|
+
const blockAt = providers.index
|
|
171
|
+
const block = `metaFiles: [${eol}${entry}${eol} ],${eol} `
|
|
172
|
+
content = `${content.slice(0, blockAt)}${block}${content.slice(blockAt)}`
|
|
173
|
+
fs.writeFileSync(rcPath, content)
|
|
174
|
+
},
|
|
175
|
+
|
|
123
176
|
async addEnvVars(vars: Record<string, string>): Promise<void> {
|
|
124
177
|
const envPath = path.join(root, '.env')
|
|
125
178
|
// A symlinked .env must not redirect the write outside the root.
|
package/src/Ignitor.ts
CHANGED
|
@@ -17,7 +17,7 @@ import { Application } from './Application.js'
|
|
|
17
17
|
import type { Console } from './console/Console.js'
|
|
18
18
|
import type { CommandLoader, Kernel as ConsoleKernelInstance } from './console/Kernel.js'
|
|
19
19
|
import { type CommandClass, isCommandClass } from './console/types.js'
|
|
20
|
-
import {
|
|
20
|
+
import { hmrClientScript, hmrEndpoint } from './dev/hmr.js'
|
|
21
21
|
import type { DirectoriesNode } from './directories.js'
|
|
22
22
|
import type { ErrorEvent } from './ErrorBoundary.js'
|
|
23
23
|
import { ErrorBoundary } from './ErrorBoundary.js'
|
|
@@ -63,6 +63,18 @@ import type { AppEnvironment } from './Application.js'
|
|
|
63
63
|
/**
|
|
64
64
|
* Reamrc config — like AdonisJS adonisrc.ts with defineConfig().
|
|
65
65
|
*/
|
|
66
|
+
/** A command the CLI runs on the application's behalf. */
|
|
67
|
+
export interface AssetsCommand {
|
|
68
|
+
command: string
|
|
69
|
+
args?: string[]
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** What `assets` declares: a watcher for `dev`, a one-shot for `build`. */
|
|
73
|
+
export interface AssetsConfig {
|
|
74
|
+
devServer?: AssetsCommand
|
|
75
|
+
build?: AssetsCommand
|
|
76
|
+
}
|
|
77
|
+
|
|
66
78
|
export interface ReamrcConfig {
|
|
67
79
|
providers?: Array<
|
|
68
80
|
| (() => Promise<{ default: new (app: AppContext) => ProviderContract }>)
|
|
@@ -113,6 +125,47 @@ export interface ReamrcConfig {
|
|
|
113
125
|
}
|
|
114
126
|
/** Test suites and runner settings — the `tests` block of adonisrc.ts. */
|
|
115
127
|
tests?: TestsConfig
|
|
128
|
+
/**
|
|
129
|
+
* The asset pipeline `ream dev` and `ream build` drive alongside the app.
|
|
130
|
+
*
|
|
131
|
+
* `devServer` is started beside the development server and killed with it;
|
|
132
|
+
* `build` runs once, before the TypeScript build, and a non-zero exit stops
|
|
133
|
+
* the build rather than shipping a bundle nobody rebuilt.
|
|
134
|
+
*
|
|
135
|
+
* Declared here because the CLI already reads it: without the type an app
|
|
136
|
+
* that configures its asset build gets an excess-property error from
|
|
137
|
+
* `defineConfig`, which is a strange way to learn that the option exists.
|
|
138
|
+
*/
|
|
139
|
+
assets?: AssetsConfig
|
|
140
|
+
/**
|
|
141
|
+
* Files that are not modules but belong to the application.
|
|
142
|
+
*
|
|
143
|
+
* Translations, view templates, a mail signature: the build has no reason to
|
|
144
|
+
* know about them, and without being told it ships a `dist/` that boots and
|
|
145
|
+
* then cannot find them. Every pattern here is copied into the build output,
|
|
146
|
+
* keeping its path relative to the project root.
|
|
147
|
+
*
|
|
148
|
+
* `reloadServer` decides what a change does in DEVELOPMENT, and the default
|
|
149
|
+
* is the interesting half. Upstream registers translations with `false` —
|
|
150
|
+
* the files are watched so the build copies them, and an edit does NOT
|
|
151
|
+
* restart the server. A package that genuinely needs a restart asks for one
|
|
152
|
+
* by passing `true`.
|
|
153
|
+
*/
|
|
154
|
+
metaFiles?: MetaFileConfig[]
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* One `metaFiles` entry.
|
|
159
|
+
*
|
|
160
|
+
* `reloadServer` is required rather than defaulted: whether an edit costs a
|
|
161
|
+
* restart is the whole decision this entry exists to record, and a default
|
|
162
|
+
* would let it be made by accident.
|
|
163
|
+
*/
|
|
164
|
+
export interface MetaFileConfig {
|
|
165
|
+
/** Glob, relative to the project root — `resources/lang/**\/*.json`. */
|
|
166
|
+
pattern: string
|
|
167
|
+
/** Restart the development server when a matching file changes. */
|
|
168
|
+
reloadServer: boolean
|
|
116
169
|
}
|
|
117
170
|
|
|
118
171
|
/** One test suite, as declared in the rc file (AdonisJS `tests.suites[]`). */
|
|
@@ -685,7 +738,6 @@ export class Ignitor {
|
|
|
685
738
|
// anything. Registered in `ready()` it came up after the server was already
|
|
686
739
|
// serving, so a page loaded in that window polled a route that did not
|
|
687
740
|
// exist yet.
|
|
688
|
-
this.#registerDevReloadRoute()
|
|
689
741
|
|
|
690
742
|
// Providers start BEFORE the preload files, matching upstream's warm-up
|
|
691
743
|
// order (`providers.start()` → `starting` hooks → preloads). A preload is
|
|
@@ -773,7 +825,10 @@ export class Ignitor {
|
|
|
773
825
|
container: this.#app.container,
|
|
774
826
|
exceptionHandler:
|
|
775
827
|
this.#server.getErrorHandler() ?? new ExceptionHandler(!this.#app.inProduction),
|
|
776
|
-
serverMiddleware:
|
|
828
|
+
serverMiddleware: [
|
|
829
|
+
...this.#frameworkServerMiddleware(),
|
|
830
|
+
...this.#server.getServerMiddleware(),
|
|
831
|
+
],
|
|
777
832
|
routerMiddleware: this.#router.getRouterMiddleware(),
|
|
778
833
|
devReloadScript: this.#devReloadScript(),
|
|
779
834
|
onError: (error, ctx) => {
|
|
@@ -1264,19 +1319,18 @@ export class Ignitor {
|
|
|
1264
1319
|
}
|
|
1265
1320
|
|
|
1266
1321
|
/**
|
|
1267
|
-
*
|
|
1322
|
+
* The server middleware the framework itself contributes, ahead of the
|
|
1323
|
+
* application's.
|
|
1268
1324
|
*
|
|
1269
|
-
*
|
|
1270
|
-
*
|
|
1271
|
-
*
|
|
1325
|
+
* Only the hot-reload token, and only in development. It answers first
|
|
1326
|
+
* because the poll arrives once a second per open tab and its content
|
|
1327
|
+
* depends on nothing — no user, no session, no body. Behind an application's
|
|
1328
|
+
* middleware it paid for the whole stack each time, which for anything that
|
|
1329
|
+
* resolves a user from a cookie meant a `SELECT` per second for a string
|
|
1330
|
+
* holding a process id and a counter.
|
|
1272
1331
|
*/
|
|
1273
|
-
#
|
|
1274
|
-
|
|
1275
|
-
this.#router.get(HMR_PATH, ({ response }) => {
|
|
1276
|
-
response.header('cache-control', 'no-store')
|
|
1277
|
-
response.header('content-type', 'text/plain; charset=utf-8')
|
|
1278
|
-
response.send(hmrToken())
|
|
1279
|
-
})
|
|
1332
|
+
#frameworkServerMiddleware(): MiddlewareFunction[] {
|
|
1333
|
+
return this.isDevMode() ? [hmrEndpoint()] : []
|
|
1280
1334
|
}
|
|
1281
1335
|
|
|
1282
1336
|
getPhase(): string {
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Saying why the process is about to restart.
|
|
3
|
+
*
|
|
4
|
+
* A change the loader cannot swap in place becomes an exit code the dev server
|
|
5
|
+
* restarts on. From the terminal the only trace of it was the boot banner
|
|
6
|
+
* printing itself a second time — which reads as a server rebooting on its own
|
|
7
|
+
* rather than as a file that fell outside `hotHook.boundaries`. Upstream's dev
|
|
8
|
+
* server logs the file it reloaded for; this is that line.
|
|
9
|
+
*
|
|
10
|
+
* Kept apart from the loader entry so it can be tested: importing that entry
|
|
11
|
+
* registers module hooks, which a test cannot undo.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** Why a change could not be swapped in place. */
|
|
15
|
+
export type ReloadReason = 'outside-boundaries' | 'restart-list'
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The line to print before restarting.
|
|
19
|
+
*
|
|
20
|
+
* @param file - absolute path of the file that changed.
|
|
21
|
+
* @param relativise - turns it into the path the editor shows, so the line can
|
|
22
|
+
* be read at a glance.
|
|
23
|
+
*/
|
|
24
|
+
export function fullReloadNotice(
|
|
25
|
+
file: string,
|
|
26
|
+
reason: ReloadReason,
|
|
27
|
+
relativise: (file: string) => string,
|
|
28
|
+
): string {
|
|
29
|
+
const why =
|
|
30
|
+
reason === 'restart-list'
|
|
31
|
+
? ' (it is on `hotHook.restart`, which always restarts)'
|
|
32
|
+
: ' (nothing importing it is inside a `hotHook.boundaries` entry, so it could not be swapped)'
|
|
33
|
+
return `[ream] full reload — ${relativise(file)}${why}`
|
|
34
|
+
}
|
package/src/dev/hmr.ts
CHANGED
|
@@ -45,6 +45,90 @@ function holder(): CounterHolder {
|
|
|
45
45
|
export function hotReloadHappened(): void {
|
|
46
46
|
const store = holder()
|
|
47
47
|
store[COUNTER] = (store[COUNTER] ?? 0) + 1
|
|
48
|
+
notifyClients()
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The dev clients currently listening.
|
|
53
|
+
*
|
|
54
|
+
* A `Set` and not a count: each entry is pushed to on a swap, and dropped when
|
|
55
|
+
* the tab closes. `unknown`-typed on purpose — this module must not import the
|
|
56
|
+
* HTTP layer, which imports it back.
|
|
57
|
+
*/
|
|
58
|
+
interface DevClient {
|
|
59
|
+
send: (event: string, data: unknown) => Promise<boolean>
|
|
60
|
+
onClose: (callback: () => void) => void
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const clients = new Set<DevClient>()
|
|
64
|
+
|
|
65
|
+
/** The event name the injected script listens for. */
|
|
66
|
+
const HMR_EVENT = 'ream:hmr'
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Answer the dev client BEFORE any application middleware runs, and PUSH.
|
|
70
|
+
*
|
|
71
|
+
* Two problems, one change.
|
|
72
|
+
*
|
|
73
|
+
* It used to be an ordinary route polled once a second, per open tab, and a
|
|
74
|
+
* route runs the whole middleware stack. An application that resolves a user
|
|
75
|
+
* from a session cookie therefore ran `SELECT * FROM users` once a second for
|
|
76
|
+
* a response whose entire content is a process id and a counter, and which
|
|
77
|
+
* depends on no user, no session and no body.
|
|
78
|
+
*
|
|
79
|
+
* It is a stream now, so the cost is paid ONCE per tab instead of once a
|
|
80
|
+
* second, and a change reaches the browser immediately rather than up to a
|
|
81
|
+
* second later. Upstream gets the same thing from Vite's websocket; this needs
|
|
82
|
+
* no bundler, because the server already speaks SSE.
|
|
83
|
+
*
|
|
84
|
+
* Registered FIRST rather than merely outside the router: middleware that
|
|
85
|
+
* authenticates lives at either tier, and an application is free to put it in
|
|
86
|
+
* `server.use([...])` — many do, because it must run before routing.
|
|
87
|
+
*
|
|
88
|
+
* Development only. In production nothing injects the script and nothing
|
|
89
|
+
* registers this.
|
|
90
|
+
*/
|
|
91
|
+
export function hmrEndpoint(): (
|
|
92
|
+
ctx: {
|
|
93
|
+
request: { url: () => string }
|
|
94
|
+
response: { sse: () => Promise<DevClient> }
|
|
95
|
+
},
|
|
96
|
+
next: () => Promise<void>,
|
|
97
|
+
) => Promise<void> {
|
|
98
|
+
return async (ctx, next) => {
|
|
99
|
+
// `url()` carries the query string; a client may append a cache-buster.
|
|
100
|
+
const path = ctx.request.url().split('?')[0]
|
|
101
|
+
if (path !== HMR_PATH) {
|
|
102
|
+
await next()
|
|
103
|
+
return
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
let stream: DevClient
|
|
107
|
+
try {
|
|
108
|
+
stream = await ctx.response.sse()
|
|
109
|
+
} catch {
|
|
110
|
+
// A host without the streaming NAPI — a mock server in a test, say.
|
|
111
|
+
// Losing the reload is fine; failing the request is not.
|
|
112
|
+
await next()
|
|
113
|
+
return
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
clients.add(stream)
|
|
117
|
+
stream.onClose(() => clients.delete(stream))
|
|
118
|
+
// Immediately, so a tab that connects after a restart compares against the
|
|
119
|
+
// CURRENT token rather than waiting for the next swap to learn anything.
|
|
120
|
+
await stream.send(HMR_EVENT, hmrToken())
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Tell every open tab the token moved. */
|
|
125
|
+
function notifyClients(): void {
|
|
126
|
+
const token = hmrToken()
|
|
127
|
+
for (const client of clients) {
|
|
128
|
+
// Detached: a swap must not wait on a socket, and a dead one is dropped by
|
|
129
|
+
// its own close handler.
|
|
130
|
+
void client.send(HMR_EVENT, token).catch(() => clients.delete(client))
|
|
131
|
+
}
|
|
48
132
|
}
|
|
49
133
|
|
|
50
134
|
/** How many hot swaps this process has seen. */
|
|
@@ -63,10 +147,15 @@ export function hmrToken(): string {
|
|
|
63
147
|
/**
|
|
64
148
|
* The script injected into HTML pages in dev.
|
|
65
149
|
*
|
|
66
|
-
*
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
*
|
|
150
|
+
* An `EventSource`, not a poll. The server pushes the token, so a change
|
|
151
|
+
* reaches the page immediately and an idle tab costs one open connection
|
|
152
|
+
* rather than a request per second through the whole middleware stack.
|
|
153
|
+
*
|
|
154
|
+
* It reloads when the token CHANGES, never when the connection fails: a
|
|
155
|
+
* restarting server is unreachable for a moment, and reloading then would only
|
|
156
|
+
* show the browser's error page. `EventSource` reconnects on its own, and the
|
|
157
|
+
* server greets the new connection with its token — which after a restart is a
|
|
158
|
+
* different boot id, so the reload happens then, once the server can serve it.
|
|
70
159
|
*/
|
|
71
160
|
export function hmrClientScript(nonce?: string): string {
|
|
72
161
|
// A nonce-based CSP — which the scaffold ships, via `@c9up/blackhole` —
|
|
@@ -75,9 +164,13 @@ export function hmrClientScript(nonce?: string): string {
|
|
|
75
164
|
// are escaped because a nonce is generated, not user input, but a broken
|
|
76
165
|
// attribute would silently disable the tag rather than fail loudly.
|
|
77
166
|
const attribute = nonce === undefined ? '' : ` nonce="${nonce.replace(/"/g, '"')}"`
|
|
78
|
-
//
|
|
79
|
-
//
|
|
80
|
-
//
|
|
81
|
-
//
|
|
82
|
-
return `<script${attribute}>(()=>{let t=null;const
|
|
167
|
+
// `addEventListener(HMR_EVENT)`, NOT `onmessage`: the stream names its
|
|
168
|
+
// events, and `onmessage` fires only for unnamed ones — a client wired that
|
|
169
|
+
// way receives nothing at all, silently, which is a mistake this codebase
|
|
170
|
+
// has already made once with relay.
|
|
171
|
+
return `<script${attribute}>(()=>{let t=null;const s=new EventSource(${JSON.stringify(
|
|
172
|
+
HMR_PATH,
|
|
173
|
+
)});s.addEventListener(${JSON.stringify(
|
|
174
|
+
HMR_EVENT,
|
|
175
|
+
)},e=>{let n;try{n=JSON.parse(e.data)}catch(_){n=e.data}if(t===null){t=n}else if(n!==t){s.close();location.reload()}})})()</script>`
|
|
83
176
|
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Matching the globs an application declares under `hotHook.boundaries`.
|
|
3
|
+
*
|
|
4
|
+
* A dependency for this would be `picomatch` plus `fast-glob`, which is two
|
|
5
|
+
* packages and their trees for the three wildcards these patterns actually use.
|
|
6
|
+
* The patterns are written by hand in a `package.json` and read once at boot;
|
|
7
|
+
* what they need is to be right, not fast.
|
|
8
|
+
*
|
|
9
|
+
* The dialect is the one those files already use:
|
|
10
|
+
* * any run of characters inside one path segment
|
|
11
|
+
* ** any number of segments, including none
|
|
12
|
+
* ? exactly one character inside a segment
|
|
13
|
+
* {a,b} either alternative
|
|
14
|
+
*
|
|
15
|
+
* The brace form is the one a `metaFiles` entry uses —
|
|
16
|
+
* `resources/lang/**\/*.{json,yaml,yml}` — and it has to be understood on this
|
|
17
|
+
* side too: the CLI matches the same pattern when it copies those files into
|
|
18
|
+
* the build, and a dialect that differed between the two would let an entry
|
|
19
|
+
* copy at build time and never fire in development, or the reverse.
|
|
20
|
+
*
|
|
21
|
+
* A leading `./` is optional, and matching is done on POSIX-shaped paths
|
|
22
|
+
* relative to the project root, so a Windows checkout and a Linux one read the
|
|
23
|
+
* same pattern the same way.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
/** Turn one glob into an anchored regular expression. */
|
|
27
|
+
export function globToRegExp(pattern: string): RegExp {
|
|
28
|
+
const cleaned = pattern.replace(/^\.\//, '')
|
|
29
|
+
let out = ''
|
|
30
|
+
for (let i = 0; i < cleaned.length; i += 1) {
|
|
31
|
+
const char = cleaned[i]
|
|
32
|
+
if (char === '*') {
|
|
33
|
+
if (cleaned[i + 1] === '*') {
|
|
34
|
+
// `**/` swallows the separator so that `a/**/b` also matches `a/b`;
|
|
35
|
+
// a trailing `**` simply matches the rest.
|
|
36
|
+
i += 1
|
|
37
|
+
if (cleaned[i + 1] === '/') {
|
|
38
|
+
i += 1
|
|
39
|
+
out += '(?:[^/]+/)*'
|
|
40
|
+
} else {
|
|
41
|
+
out += '.*'
|
|
42
|
+
}
|
|
43
|
+
continue
|
|
44
|
+
}
|
|
45
|
+
out += '[^/]*'
|
|
46
|
+
continue
|
|
47
|
+
}
|
|
48
|
+
if (char === '?') {
|
|
49
|
+
out += '[^/]'
|
|
50
|
+
continue
|
|
51
|
+
}
|
|
52
|
+
if (char === '{') {
|
|
53
|
+
const close = cleaned.indexOf('}', i)
|
|
54
|
+
if (close !== -1) {
|
|
55
|
+
// Alternatives are literal text, never nested globs: that is the whole
|
|
56
|
+
// of the form these patterns use, and a recursive reading would accept
|
|
57
|
+
// shapes the CLI's matcher does not.
|
|
58
|
+
const options = cleaned
|
|
59
|
+
.slice(i + 1, close)
|
|
60
|
+
.split(',')
|
|
61
|
+
.map((option) => option.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
|
|
62
|
+
out += `(?:${options.join('|')})`
|
|
63
|
+
i = close
|
|
64
|
+
continue
|
|
65
|
+
}
|
|
66
|
+
// Unclosed: read literally rather than throwing. A pattern is a string in
|
|
67
|
+
// a config file, and a malformed one should match nothing, not take the
|
|
68
|
+
// dev server down at boot.
|
|
69
|
+
}
|
|
70
|
+
// Everything else is literal, including the characters a regular
|
|
71
|
+
// expression would otherwise read as syntax.
|
|
72
|
+
out += (char ?? '').replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
|
73
|
+
}
|
|
74
|
+
return new RegExp(`^${out}$`)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* A matcher over several globs.
|
|
79
|
+
*
|
|
80
|
+
* Returns a predicate rather than a class: the graph takes a function, and a
|
|
81
|
+
* project with no boundaries gets one that is honestly always false instead of
|
|
82
|
+
* an empty object that has to be checked for.
|
|
83
|
+
*/
|
|
84
|
+
export function globMatcher(patterns: readonly string[]): (path: string) => boolean {
|
|
85
|
+
const expressions = patterns.map(globToRegExp)
|
|
86
|
+
if (expressions.length === 0) return () => false
|
|
87
|
+
return (path: string) => {
|
|
88
|
+
const normalised = path.replace(/\\/g, '/').replace(/^\.\//, '')
|
|
89
|
+
return expressions.some((expression) => expression.test(normalised))
|
|
90
|
+
}
|
|
91
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The import graph a hot reload reasons over, and what it decides.
|
|
3
|
+
*
|
|
4
|
+
* Owned here rather than taken from `hot-hook`, which used to do this job. The
|
|
5
|
+
* package is 655 lines and four npm dependencies, and it had to be installed by
|
|
6
|
+
* every application because a dev-only loader has no business in a production
|
|
7
|
+
* install of the framework — so a project created before that convention simply
|
|
8
|
+
* lost hot reloading and was told nothing. The part that genuinely needs a
|
|
9
|
+
* library is the part Node now provides itself: `module.registerHooks` for the
|
|
10
|
+
* graph, `fs.watch` for the changes.
|
|
11
|
+
*
|
|
12
|
+
* NO node_modules dependency, deliberately: everything below is arithmetic on
|
|
13
|
+
* paths.
|
|
14
|
+
*
|
|
15
|
+
* The graph is built by the resolver as the program runs, never by reading
|
|
16
|
+
* files. A `resolve` hook is handed the importer and the imported, which is
|
|
17
|
+
* exactly an edge, and it sees dynamic imports as they happen — a static parse
|
|
18
|
+
* of the source could only guess at those.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/** A module's place in the graph: who imports it, and which version is live. */
|
|
22
|
+
interface Node {
|
|
23
|
+
/** Modules that imported this one. The graph is walked upward, so this is the direction stored. */
|
|
24
|
+
readonly importers: Set<string>
|
|
25
|
+
/** Bumped on invalidation; appended to the URL so the loader fetches the file again. */
|
|
26
|
+
version: number
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** What a change to one file means. */
|
|
30
|
+
export type Decision =
|
|
31
|
+
| { kind: 'swap'; invalidated: string[] }
|
|
32
|
+
| { kind: 'reload'; file: string; reason: 'outside-boundaries' | 'restart-list' }
|
|
33
|
+
| { kind: 'ignore' }
|
|
34
|
+
|
|
35
|
+
export class HotGraph {
|
|
36
|
+
readonly #nodes = new Map<string, Node>()
|
|
37
|
+
readonly #isBoundary: (file: string) => boolean
|
|
38
|
+
readonly #isRestart: (file: string) => boolean
|
|
39
|
+
|
|
40
|
+
constructor(options: {
|
|
41
|
+
isBoundary: (file: string) => boolean
|
|
42
|
+
isRestart: (file: string) => boolean
|
|
43
|
+
}) {
|
|
44
|
+
this.#isBoundary = options.isBoundary
|
|
45
|
+
this.#isRestart = options.isRestart
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
#node(file: string): Node {
|
|
49
|
+
let node = this.#nodes.get(file)
|
|
50
|
+
if (node === undefined) {
|
|
51
|
+
node = { importers: new Set(), version: 0 }
|
|
52
|
+
this.#nodes.set(file, node)
|
|
53
|
+
}
|
|
54
|
+
return node
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Record that `importer` imported `file`. Called from the resolve hook. */
|
|
58
|
+
link(file: string, importer: string | undefined): void {
|
|
59
|
+
const node = this.#node(file)
|
|
60
|
+
if (importer !== undefined && importer !== file) node.importers.add(importer)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The version to hang off the URL, or 0 while the module has never been invalidated. */
|
|
64
|
+
version(file: string): number {
|
|
65
|
+
return this.#nodes.get(file)?.version ?? 0
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Whether the resolver has ever seen this file. */
|
|
69
|
+
knows(file: string): boolean {
|
|
70
|
+
return this.#nodes.has(file)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* What to do about `file` having changed.
|
|
75
|
+
*
|
|
76
|
+
* Walks up from the changed file collecting what has to be re-imported, and
|
|
77
|
+
* stops at each boundary: a boundary is imported dynamically, so the next
|
|
78
|
+
* import of it re-resolves, and with it everything below that was collected
|
|
79
|
+
* on the way. A path that reaches a module nobody imports without crossing a
|
|
80
|
+
* boundary cannot be re-imported by anyone, and that is a full reload.
|
|
81
|
+
*
|
|
82
|
+
* Deciding before invalidating matters: a decision that turns out to be a
|
|
83
|
+
* full reload must leave no version bumped behind, or a later swap would
|
|
84
|
+
* hand the caller a URL for a module the process never re-imported.
|
|
85
|
+
*/
|
|
86
|
+
decide(file: string): Decision {
|
|
87
|
+
if (this.#isRestart(file)) return { kind: 'reload', file, reason: 'restart-list' }
|
|
88
|
+
if (!this.#nodes.has(file)) return { kind: 'ignore' }
|
|
89
|
+
|
|
90
|
+
const collected = new Set<string>()
|
|
91
|
+
const queue = [file]
|
|
92
|
+
while (queue.length > 0) {
|
|
93
|
+
const current = queue.pop()
|
|
94
|
+
if (current === undefined || collected.has(current)) continue
|
|
95
|
+
collected.add(current)
|
|
96
|
+
// A boundary is where the walk stops: whoever imports it does so
|
|
97
|
+
// dynamically and will ask for it again.
|
|
98
|
+
if (this.#isBoundary(current)) continue
|
|
99
|
+
const importers = this.#nodes.get(current)?.importers
|
|
100
|
+
if (importers === undefined || importers.size === 0) {
|
|
101
|
+
return { kind: 'reload', file, reason: 'outside-boundaries' }
|
|
102
|
+
}
|
|
103
|
+
for (const importer of importers) queue.push(importer)
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
for (const path of collected) this.#node(path).version += 1
|
|
107
|
+
return { kind: 'swap', invalidated: [...collected] }
|
|
108
|
+
}
|
|
109
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Watching the project for the changes a hot reload reacts to.
|
|
3
|
+
*
|
|
4
|
+
* `fs.watch` with `recursive: true`, which Node implements on Linux, macOS and
|
|
5
|
+
* Windows alike — the reason a watcher used to be a dependency here, and is not
|
|
6
|
+
* any more.
|
|
7
|
+
*
|
|
8
|
+
* Two behaviours are worth stating because they are not obvious from the API:
|
|
9
|
+
*
|
|
10
|
+
* A save is rarely one event. Editors write, rename and touch, and a single
|
|
11
|
+
* Ctrl-S can arrive as several notifications for the same file within a few
|
|
12
|
+
* milliseconds. Each one would walk the graph and bump a version, so they are
|
|
13
|
+
* coalesced.
|
|
14
|
+
*
|
|
15
|
+
* `ream dev` also watches from the outside, in Rust. That is not a duplicate:
|
|
16
|
+
* this watcher dies with the process it lives in, so a server that crashed on a
|
|
17
|
+
* syntax error has nothing left to notice the fix. The outer one covers exactly
|
|
18
|
+
* that window, and hands back over by restarting the process.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { type FSWatcher, watch } from 'node:fs'
|
|
22
|
+
import { join, resolve } from 'node:path'
|
|
23
|
+
|
|
24
|
+
/** How long to wait for a save to finish arriving before acting on it. */
|
|
25
|
+
const SETTLE_MS = 40
|
|
26
|
+
|
|
27
|
+
export interface WatcherOptions {
|
|
28
|
+
/** Project root; every reported path is absolute, resolved against it. */
|
|
29
|
+
root: string
|
|
30
|
+
/** Directories under the root to watch, when they exist. */
|
|
31
|
+
directories: readonly string[]
|
|
32
|
+
/** Individual files to watch — env files sit at the root, so no directory covers them. */
|
|
33
|
+
files: readonly string[]
|
|
34
|
+
/** Called once per settled change, with an absolute path. */
|
|
35
|
+
onChange: (file: string) => void
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface Watcher {
|
|
39
|
+
close: () => void
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function watchProject(options: WatcherOptions): Watcher {
|
|
43
|
+
const watchers: FSWatcher[] = []
|
|
44
|
+
const pending = new Map<string, NodeJS.Timeout>()
|
|
45
|
+
|
|
46
|
+
const report = (file: string): void => {
|
|
47
|
+
const existing = pending.get(file)
|
|
48
|
+
if (existing !== undefined) clearTimeout(existing)
|
|
49
|
+
const timer = setTimeout(() => {
|
|
50
|
+
pending.delete(file)
|
|
51
|
+
options.onChange(file)
|
|
52
|
+
}, SETTLE_MS)
|
|
53
|
+
// The dev server must still be able to exit while a save is settling.
|
|
54
|
+
timer.unref?.()
|
|
55
|
+
pending.set(file, timer)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
for (const directory of options.directories) {
|
|
59
|
+
const absolute = resolve(options.root, directory)
|
|
60
|
+
try {
|
|
61
|
+
watchers.push(
|
|
62
|
+
watch(absolute, { recursive: true }, (_event, name) => {
|
|
63
|
+
if (typeof name !== 'string' || name === '') return
|
|
64
|
+
report(join(absolute, name))
|
|
65
|
+
}),
|
|
66
|
+
)
|
|
67
|
+
} catch {
|
|
68
|
+
// A directory this project does not have is not an error: the list is
|
|
69
|
+
// the framework's conventional layout, not a requirement.
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
for (const file of options.files) {
|
|
74
|
+
const absolute = resolve(options.root, file)
|
|
75
|
+
try {
|
|
76
|
+
watchers.push(watch(absolute, () => report(absolute)))
|
|
77
|
+
} catch {
|
|
78
|
+
// Same: a `.env` that does not exist is simply not watched.
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return {
|
|
83
|
+
close: () => {
|
|
84
|
+
for (const timer of pending.values()) clearTimeout(timer)
|
|
85
|
+
pending.clear()
|
|
86
|
+
for (const watcher of watchers) watcher.close()
|
|
87
|
+
},
|
|
88
|
+
}
|
|
89
|
+
}
|