/
build-node-binding.js.bak
375 lines (323 loc) · 11.1 KB
/
build-node-binding.js.bak
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
import { execa } from 'execa'
import watcher from '@parcel/watcher'
import path from 'node:path'
import crypto from 'crypto'
import fs from 'node:fs'
import fsp from 'fs/promises'
import debug from 'debug'
import chalk from 'chalk'
import { fileURLToPath } from 'node:url'
if (!process.env.DEBUG) {
debug.enable('rolldown')
}
const ROOT_DIR = path.normalize(
path.join(path.dirname(fileURLToPath(import.meta.url)), '..'),
)
const CACHE_DIR = path.join(ROOT_DIR, 'node_modules/.rolldown')
const NO_WASM = process.argv.includes('--no-wasm')
const IS_RELEASE = process.argv.includes('--release')
fs.mkdirSync(CACHE_DIR, { recursive: true })
/** @typedef {import('debug').Debugger['log']} LogFunction */
/** A function that returns an array of paths for files (similar to the getDirFiles function, see {@link getDirFiles}) @typedef {() => Promise<string[]>} LoadFilesCallback */
/** The file that triggered the build. @typedef {string} ChangedFile */
/** Represents whether the package was rebuilt. @typedef {boolean} WasRebuilt */
/**
* Takes a path relative to the project root and returns an array of paths for files in this directory.
* @param {string} dir - Directory path relative to the project root directory. For example, 'crates/rolldown_binding/src'.
* @returns {Promise<string[]>} Array of directory file paths relative to the rolldown root directory.
* Example: If dir is 'crates/rolldown_binding/src', it returns ['crates/rolldown_binding/src/bunder.rs', 'crates/rolldown_binding/src/lib.rs', and so on].
*
* @example
* const files = await getDirFiles('crates/rolldown_binding/src')
* console.log(files) // Example output: ['crates/rolldown_binding/src/bunder.rs', 'crates/rolldown_binding/src/lib.rs', and so on]
*/
async function getDirFiles(dir) {
const result = await execa(
'git',
[
'ls-files',
'--full-name',
'--cached',
'--modified',
'--others',
'--exclude-standard',
'--deduplicate',
dir,
],
{ cwd: ROOT_DIR },
)
return result.stdout.split('\n').filter(Boolean)
}
/**
* Takes an array of file paths and returns a common hash string.
* @param {string[]} files - Array of file paths.
* @returns {Promise<string>} A common hash string for input files.
*/
async function hashFiles(files) {
const result = await execa('git', ['hash-object', '--stdin-paths'], {
cwd: ROOT_DIR,
input: files.join('\n'),
})
return result.stdout
}
/**
* Returns the path to the cache file for the given package name.
* @param {string} pkgName - The package name.
* @returns {string} The absolute path to the cache file.
*/
function getCacheFile(pkgName) {
let key = pkgName
if (key.includes('/')) {
key = pkgName.split('/')[1]
}
return path.join(CACHE_DIR, `hash-${key}`)
}
/**
* Generates the build hash string
* @param {string[]} deps - An array of dependencies.
* @param {string[]} files - An array of file paths.
* @returns {Promise<string>} The build hash string
*/
async function generateBuildHash(deps, files) {
const hasher = crypto.createHash('sha256')
for (const dep of deps) {
const depFile = getCacheFile(dep)
if (fs.existsSync(depFile)) {
hasher.update(await fsp.readFile(depFile, 'utf8'))
}
}
hasher.update(await hashFiles(files))
return hasher.digest('hex')
}
/**
* Checks if the package needs to be rebuilt. If the cache is stale or does not exist, it returns true.
* @param {string} pkgName - The package name
* @param {string[]} deps - An array of dependencies.
* @param {string[]} files - An array of file paths.
* @returns {Promise<boolean>} Indicates whether the package needs to be rebuilt.
*/
async function isStaleOrUnbuilt(pkgName, deps, files) {
const cacheFile = getCacheFile(pkgName)
const buildHash = await generateBuildHash(deps, files)
// If the build does not exist
if (!fs.existsSync(cacheFile)) {
await fsp.writeFile(cacheFile, buildHash)
return true
}
const cachedHash = await fsp.readFile(cacheFile, 'utf8')
// If the cached and build hashes don't match, the build is stale
if (buildHash != cachedHash) {
await fsp.writeFile(cacheFile, buildHash)
return true
}
// Otherwise, the package is up-to-date
return false
}
/**
* Executes the 'yarn build' command for the specified package.
* @param {string} pkgName - The package name
* @param {LogFunction} log - Log function
* @returns {Promise<void>}
*/
async function runYarnBuild(pkgName, log) {
const command = IS_RELEASE ? 'build:release' : 'build'
const result = execa('yarn', ['workspace', pkgName, 'run', command], {
cwd: ROOT_DIR,
env: { CARGO_TERM_COLOR: 'always', FORCE_COLOR: 'true' },
stdio: 'pipe',
})
/**
* Callback function called when a chunk of data is received from the stream.
* @param {unknown} data - The chunk of data received from the stream.
*/
const onData = (data) => {
String(data)
.split('\n')
.filter(Boolean)
.forEach((line) => {
log(` ${line.trim()}`)
})
}
result.stderr?.on('data', onData)
result.stdout?.on('data', onData)
try {
await result
} catch (err) {
if (err instanceof Error) {
debug(`Yarn Build:error`)(`Failed to build ${pkgName}: ${err.message}`)
} else {
debug(`Yarn Build:error`)(`Failed to build ${pkgName}: ${err}`)
}
process.exitCode = 1
}
}
/**
* Object with keys representing package names and values as tuples consisting of the resolve function for {@link build} function and the setTimeout timer.
* Used in the 'buildWithDebounce' function to manage debounced builds for different packages.
* @type {{ [packageName: string]: [resolve: (value: boolean | PromiseLike<boolean>) => void, timeout: ReturnType<setTimeout>] }}
*/
const BUILD_TIMERS = {}
/**
* Builds the specified package.
* @param {string} pkgName - The name of the package to build.
* @param {string[]} deps - An array of dependencies required for building the package.
* @param {ChangedFile | undefined} changedFile - Optional. The file that triggered the build, if any.
* @param {LoadFilesCallback} loadFiles - A function that returns an array of paths for files (similar to the getDirFiles function, see {@link getDirFiles})
* @returns {Promise<WasRebuilt>} A Promise that resolves to true if the package was rebuilt, false otherwise.
*/
async function build(pkgName, deps, changedFile, loadFiles) {
const name = pkgName?.split('/')[1] || pkgName
const log = debug(`rolldown:${name}`)
if (!changedFile) {
log(`Checking for changes to ${pkgName}`)
}
const files = await loadFiles()
// Exit early for files we don't care about
if (changedFile && !files.some((file) => file === changedFile)) {
return false
}
if (await isStaleOrUnbuilt(name, deps, files)) {
log('Detected changes, building...')
await runYarnBuild(pkgName, log)
return true
}
log('No changes since last build')
return false
}
/**
*
* @param {string} pkgName - The package name
* @param {string[]} deps - An array of dependencies.
* @param {ChangedFile | undefined} changedFile - Optional. The file that triggered the build, if any.
* @param {LoadFilesCallback} loadFiles - A function that returns an array of paths for files (similar to the getDirFiles function, see {@link getDirFiles})
* @returns {Promise<WasRebuilt>} A Promise that resolves to true if the package was rebuilt, false otherwise.
*/
async function buildWithDebounce(pkgName, deps, changedFile, loadFiles) {
if (BUILD_TIMERS[pkgName]) {
const [resolve, timer] = BUILD_TIMERS[pkgName]
clearTimeout(timer)
resolve(true)
delete BUILD_TIMERS[pkgName]
}
return new Promise((resolve) => {
BUILD_TIMERS[pkgName] = [
resolve,
setTimeout(
() => resolve(build(pkgName, deps, changedFile, loadFiles)),
125,
),
]
})
}
/**
*
* @param {ChangedFile} [changedFile] - Optional. The file that triggered the build, if any.
* @returns {Promise<WasRebuilt>} A Promise that resolves to true if the package was rebuilt, false otherwise.
*/
async function buildRolldownPackage(changedFile) {
return buildWithDebounce(
'rolldown',
['@rolldown/node-binding'],
changedFile,
async () => {
const files = await getDirFiles('packages/node/src')
files.push(
'packages/node/build.config.ts',
'packages/node/package.json',
'packages/node/tsconfig.json',
)
return files
},
)
}
/**
* @param {ChangedFile} [changedFile] - Optional. The file that triggered the build, if any.
* @returns {Promise<WasRebuilt>} A Promise that resolves to true if the package was rebuilt, false otherwise.
*/
async function buildNodeBindingCrate(changedFile) {
return buildWithDebounce(
'@rolldown/node-binding',
[],
changedFile,
async () => {
const files = await getDirFiles('crates/rolldown_binding/src')
files.push(
'crates/rolldown_binding/build.rs',
'crates/rolldown_binding/Cargo.toml',
'crates/rolldown_binding/package.json',
)
return files
},
)
}
/**
* @param {ChangedFile} [changedFile] - Optional. The file that triggered the build, if any.
* @returns {Promise<WasRebuilt>} A Promise that resolves to true if the package was rebuilt, false otherwise.
*/
async function buildWasmBindingCrate(changedFile) {
if (NO_WASM) {
return false
}
return buildWithDebounce(
'@rolldown/wasm-binding',
[],
changedFile,
async () => {
const files = await getDirFiles('crates/rolldown_binding_wasm/src')
files.push(
'crates/rolldown_binding_wasm/Cargo.toml',
'crates/rolldown_binding_wasm/package.json',
)
return files
},
)
}
/**
* Subscribe to changes in subfolders and rebuild some package if change is detected.
* @returns {Promise<void>}
*/
async function watchForChanges() {
const log = debug('rolldown:watcher')
log('Watching for changes...')
/** @type import('@parcel/watcher').SubscribeCallback */
const onChange = (error, events) => {
if (error) {
console.error(error)
process.exit(1)
}
events.forEach((event) => {
const changedFile = event.path.replace(ROOT_DIR, '').slice(1)
log(chalk.gray(`${event.type}: ${changedFile}`))
if (changedFile.includes('crates/rolldown_binding/')) {
buildNodeBindingCrate(changedFile).then(() =>
buildRolldownPackage(changedFile),
)
} else if (changedFile.includes('crates/rolldown_binding_wasm/')) {
buildWasmBindingCrate(changedFile)
} else if (changedFile.includes('packages/node/')) {
buildRolldownPackage(changedFile)
}
})
return
}
const promises = [
watcher.subscribe(path.join(ROOT_DIR, 'packages/node'), onChange),
watcher.subscribe(path.join(ROOT_DIR, 'crates/rolldown_binding'), onChange),
]
if (!NO_WASM) {
promises.push(
watcher.subscribe(
path.join(ROOT_DIR, 'crates/rolldown_binding_wasm'),
onChange,
),
)
}
await Promise.all(promises)
}
await Promise.all([
buildNodeBindingCrate().then(() => buildRolldownPackage()),
buildWasmBindingCrate(),
])
if (process.argv.includes('--watch')) {
await watchForChanges()
}