forked from microsoft/devicescript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.ts
More file actions
580 lines (531 loc) · 16.8 KB
/
build.ts
File metadata and controls
580 lines (531 loc) · 16.8 KB
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
import { basename, dirname, join, relative, resolve } from "node:path"
import { readFileSync, writeFileSync, existsSync, readdirSync } from "node:fs"
import { ensureDirSync, mkdirp, removeSync } from "fs-extra"
import {
compileWithHost,
jacdacDefaultSpecifications,
DevsDiagnostic,
formatDiagnostics,
DEVS_DBG_FILE,
prettySize,
DebugInfo,
SrcMapResolver,
preludeFiles,
Host,
LocalBuildConfig,
ResolvedBuildConfig,
resolveBuildConfig,
DeviceConfig,
RepoInfo,
pinsInfo,
CompilationResult,
PkgJson,
} from "@devicescript/compiler"
import {
BINDIR,
consoleColors,
debug,
error,
FLASHDIR,
FLASHFILE,
GENDIR,
LIBDIR,
log,
verboseLog,
} from "./command"
import glob from "fast-glob"
import type { DevsModule } from "@devicescript/vm"
import { readFile, writeFile } from "node:fs/promises"
import { printDmesg } from "./vmworker"
import { EXIT_CODE_COMPILATION_ERROR } from "./exitcodes"
import {
converters,
parseServiceSpecificationMarkdownToJSON,
sha256,
toHex,
versionTryParse,
} from "jacdac-ts"
import { execSync } from "node:child_process"
import { BuildOptions } from "./sideprotocol"
import { readJSON5Sync } from "./jsonc"
// TODO should we move this to jacdac-ts and call automatically for transports?
export function setupWebsocket() {
if (typeof WebSocket !== "undefined") return
try {
require("websocket-polyfill")
// @ts-ignore
global.Blob = require("buffer").Blob
global.WebSocket.prototype.send = function (this: any, data: any) {
if (typeof data.valueOf() === "string")
this.connection_.sendUTF(data)
else {
this.connection_.sendBytes(Buffer.from(data))
}
}
global.WebSocket.prototype.close = function (this: any, code, reason) {
this.state_ = WebSocket.CLOSING
if (this.connection_) {
if (code === undefined) this.connection_.sendCloseFrame()
else this.connection_.sendCloseFrame(code, reason)
}
}
} catch {
log("can't load websocket-polyfill")
}
}
export function readDebugInfo() {
let dbg: DebugInfo
try {
dbg = readJSON5Sync(join(BINDIR, DEVS_DBG_FILE))
} catch {}
return dbg
}
let devsInst: DevsModule
export function setDevsDmesg() {
if (devsInst) {
const dbg = readDebugInfo()
devsInst.dmesg = (s: string) => {
printDmesg(dbg, "WASM", s)
}
}
}
export function devsFactory() {
// emscripten doesn't like multiple instances
if (devsInst) return Promise.resolve(devsInst)
const d = require("@devicescript/vm")
setupWebsocket()
return (d() as Promise<DevsModule>).then(m => {
devsInst = m
setDevsDmesg()
// m.devsInit() - don't init here, we may still want to do more setup
return m
})
}
export async function devsStartWithNetwork(options: {
tcp?: boolean
test?: boolean
deviceId?: string
gcStress?: boolean
stateless?: boolean
clearFlash?: boolean
}) {
const inst = await devsFactory()
inst.devsGcStress(!!options.gcStress)
if (options.tcp)
await inst.setupNodeTcpSocketTransport(require, "127.0.0.1", 8082)
else await inst.setupWebsocketTransport("ws://127.0.0.1:8081")
if (options.stateless) {
inst.flashLoad = null
inst.flashSave = null
} else {
ensureDirSync(FLASHDIR)
const fn = join(FLASHDIR, FLASHFILE)
// clear flash if needed
if (options.clearFlash && existsSync(fn)) {
verboseLog(`clearing flash ${fn}`)
removeSync(fn)
}
verboseLog(`set up flash in ${fn}`)
inst.flashLoad = () => {
try {
return new Uint8Array(readFileSync(fn))
} catch {
return new Uint8Array(0)
}
}
inst.flashSave = buf => {
writeFileSync(fn, buf)
}
}
if (options.deviceId) inst.devsSetDeviceId(options.deviceId)
inst.devsStart()
return inst
}
export async function getHost(
buildConfig: ResolvedBuildConfig,
options: BuildOptions,
folder: string
) {
const inst = options.verify === false ? undefined : await devsFactory()
const outdir = resolve(options.cwd ?? ".", options.outDir || BINDIR)
ensureDirSync(outdir)
const devsHost: Host = {
write: (fn: string, cont: string) => {
const p = join(outdir, fn)
verboseLog(`write ${p}`)
writeFileSync(p, cont)
if (
fn.endsWith(".jasm") &&
typeof cont == "string" &&
cont.indexOf("???oops") >= 0
)
throw new Error("bad disassembly")
},
read: (fn: string) => {
// verboseLog(`read ${fn} ${resolve(folder, fn)}`)
return readFileSync(resolve(folder, fn), "utf-8")
},
resolvePath: fn => resolve(fn),
relativePath: fn => relative(resolve("."), fn),
log: verboseLog,
isBasicOutput: () => !consoleColors,
error: (err: DevsDiagnostic) => {
if (!options.quiet)
console.error(formatDiagnostics([err], !consoleColors))
},
getFlags: () => options.flag ?? {},
getConfig: () => buildConfig,
verifyBytecode: (buf: Uint8Array) => {
if (!inst) return
const res = inst.devsVerify(buf)
if (res != 0) throw new Error("verification error: " + res)
},
}
return devsHost
}
function toDevsDiag(d: jdspec.Diagnostic): DevsDiagnostic {
return {
category: 1,
code: 9998,
file: undefined,
filename: d.file,
start: 0,
length: 1,
messageText: d.message,
line: d.line,
column: 1,
endLine: d.line,
endColumn: 100,
formatted: "",
}
}
function execCmd(cmd: string) {
try {
return execSync(cmd, { encoding: "utf-8" }).trim()
} catch {
return ""
}
}
function isGit() {
let pref = ""
for (let i = 0; i < 10; ++i) {
if (existsSync(pref + ".git")) return true
pref = pref + "../"
}
return false
}
function compilePackageJson(
tsdir: string,
entryPoint: string,
lcfg: LocalBuildConfig,
errors: DevsDiagnostic[]
) {
const pkgJsonPath = join(tsdir, "package.json")
if (existsSync(pkgJsonPath)) {
const pkgJSON = readJSON5Sync(pkgJsonPath) as PkgJson
lcfg.pkgJson = pkgJSON
lcfg.hwInfo["@name"] = pkgJSON.name ?? "(no name)"
let version = pkgJSON.version ?? "(no version)"
if (isGit()) {
const head = execCmd(
"git describe --tags --match 'v[0-9]*' --always"
)
let dirty = execCmd(
"git status --porcelain --untracked-file=no --ignore-submodules=untracked"
)
if (!head) dirty = "yes"
const exact = !dirty && head[0] == "v" && !head.includes("-")
if (exact) {
version = head
} else {
let v = versionTryParse(version)
if (head[0] == "v") v = versionTryParse(head) || v
let verStr = ""
if (v) verStr = `v${v.major}.${v.minor}.${v.patch + 1}-`
verStr += head.replace(/.*-/, "")
if (dirty) {
const now = new Date()
.toISOString()
.replace(/T/, ".")
.replace(/:/, ".")
.replace(/:.*/, "")
.replace(/-/g, ".")
if (verStr) verStr += "-"
verStr += now
}
version = verStr
}
lcfg.hwInfo["@version"] = version
}
}
if (entryPoint) {
entryPoint = entryPoint.replace(/^src[\/\\]/, "")
entryPoint = entryPoint.replace(/^main/, "")
entryPoint = entryPoint.replace(/.ts$/, "")
if (entryPoint) {
if (lcfg.hwInfo["@name"]) lcfg.hwInfo["@name"] += " " + entryPoint
else lcfg.hwInfo["@name"] = entryPoint
}
}
verboseLog(
`compile: ${lcfg.hwInfo["@name"]} ${lcfg.hwInfo["@version"] ?? ""}`
)
}
function compileServiceSpecs(
tsdir: string,
lcfg: LocalBuildConfig,
errors: DevsDiagnostic[]
) {
const dir = join(tsdir, "services")
lcfg.addServices = []
if (existsSync(dir)) {
const includes: Record<string, jdspec.ServiceSpec> = {}
jacdacDefaultSpecifications.forEach(
spec => (includes[spec.shortId] = spec)
)
const markdowns = readdirSync(dir, { encoding: "utf-8" }).filter(
fn => /\.md$/i.test(fn) && !/README\.md$/i.test(fn)
)
for (const mdf of markdowns) {
const fn = join(dir, mdf)
const content = readFileSync(fn, { encoding: "utf-8" })
const json = parseServiceSpecificationMarkdownToJSON(
content,
includes,
fn
)
json.catalog = false
if (json?.errors?.length)
errors.push(...json.errors.map(toDevsDiag))
else {
includes[json.shortId] = json
verboseLog(`custom service: ${json.shortName}`)
lcfg.addServices.push(json)
}
}
}
}
export function validateBoard(board: DeviceConfig, baseCfg: RepoInfo) {
const bid = board.id
if (!/^\w+$/.test(bid)) throw new Error(`invalid identifier: ${bid}`)
board.id = bid
const arch = baseCfg.archs[board.archId]
if (!arch) throw new Error(`board.archId ${board.archId} is invalid`)
if (baseCfg.boards[bid]) throw new Error(`board ${bid} already defined`)
if ((+board.productId & 0xf000_0000) != 0x3000_0000)
throw new Error(`invalid productId ${board.productId}`)
const { desc, errors } = pinsInfo(arch, board)
verboseLog(desc)
if (errors.length) throw new Error(errors.join("\n"))
}
function compileBoards(
tsdir: string,
lcfg: LocalBuildConfig,
errors: DevsDiagnostic[]
) {
const dir = join(tsdir, "boards")
lcfg.addBoards = []
const baseCfg = resolveBuildConfig()
if (existsSync(dir)) {
const boards = readdirSync(dir, { encoding: "utf-8" }).filter(fn =>
fn.endsWith(".board.json")
)
for (const boardFn of boards) {
const fullName = join(dir, boardFn)
try {
const board: DeviceConfig = JSON.parse(
readFileSync(fullName, "utf-8")
)
const bid = basename(boardFn, ".board.json")
if (board.id && board.id != bid)
throw new Error("ignoring id: field in favor of filename")
board.id = bid
validateBoard(board, baseCfg)
verboseLog(`custom board: ${board.id}`)
lcfg.addBoards.push(board)
} catch (e) {
errors.push(
toDevsDiag({
file: fullName,
line: 1,
message: e.message,
})
)
}
}
}
}
export class CompilationError extends Error {
static NAME = "CompilationError"
constructor(message: string) {
super(message)
this.name = CompilationError.NAME
}
}
export function buildConfigFromDir(
dir: string,
entryPoint: string = "",
options: BuildOptions = {}
) {
const lcfg: LocalBuildConfig = {
hwInfo: {},
}
const errors: DevsDiagnostic[] = []
if (dir) {
verboseLog(`build config from: ${dir}`)
compilePackageJson(dir, entryPoint, lcfg, errors)
compileServiceSpecs(dir, lcfg, errors)
compileBoards(dir, lcfg, errors)
if (!options.quiet)
for (const e of errors)
console.error(`${e.filename}(${e.line}): ${e.messageText}`)
}
return {
buildConfig: resolveBuildConfig(lcfg),
errors,
}
}
export async function compileFile(
fn: string,
options: BuildOptions = {}
): Promise<CompilationResult> {
const exists = existsSync(fn)
if (!exists) throw new Error(`source file "${fn}" not found`)
if (
!options.ignoreMissingConfig &&
!existsSync("./devsconfig.json") &&
!existsSync("./devs/run-tests/basic.ts") // hack for in-tree testing
)
throw new Error("./devsconfig.json file not found")
const outDir = options.outDir || BINDIR
ensureDirSync(outDir)
const folder = resolve(".")
const entryPoint = relative(folder, fn)
const { errors, buildConfig } = buildConfigFromDir(
folder,
entryPoint,
options
)
await saveLibFiles(buildConfig, options)
const host = await getHost(buildConfig, options, folder)
const t0 = Date.now()
const res = compileWithHost(fn, host)
const time = Date.now() - t0
verboseLog(`compile: ${time}ms`)
if (res.binary) {
res.dbg.binarySHA256 = toHex(await sha256([res.binary]))
verboseLog(`sha: ${res.dbg.binarySHA256}`)
writeFileSync(
join(folder, outDir, DEVS_DBG_FILE),
JSON.stringify(res.dbg)
)
}
setDevsDmesg() // set again after we have re-created -dbg.json file
if (errors.length) {
res.diagnostics.unshift(...errors)
res.success = false
}
return res
}
export async function saveLibFiles(
buildConfig: ResolvedBuildConfig,
options: BuildOptions
) {
// pass the user-provided services so they are included in devicescript-specs.d.ts
const prelude = preludeFiles(buildConfig)
const pref = resolve(options.cwd ?? ".")
const libpath = join(pref, LIBDIR)
if (
existsSync(join(libpath, "core/CORE_SOURCES.md")) ||
buildConfig.pkgJson?.devicescript?.bundle
) {
verboseLog(`not saving files in ${libpath} (source build)`)
} else {
await mkdirp(libpath)
verboseLog(`saving lib files in ${libpath}`)
for (const fn of Object.keys(prelude)) {
const fnpath = join(pref, fn)
await mkdirp(dirname(fnpath))
const ex = await readFile(fnpath, "utf-8").then(
r => r,
_ => null
)
if (prelude[fn] != ex) await writeFile(fnpath, prelude[fn])
}
}
// generate constants for non-catalog services
const customServices =
buildConfig.services.filter(srv => srv.catalog !== undefined) || []
// generate source files
await Promise.all(["ts", "c"].map(async(lang) => {
const converter = converters()[lang]
let constants = ""
for (const srv of customServices) {
constants += converter(srv) + "\n"
}
const dir = join(pref, GENDIR, lang)
await mkdirp(dir)
return writeFile(join(dir, `constants.${lang}`), constants, {
encoding: "utf-8",
})
}))
// json specs
{
const dir = join(pref, GENDIR)
await mkdirp(dir)
await writeFile(
join(dir, `services.json`),
JSON.stringify(customServices, null, 2),
{
encoding: "utf-8",
}
)
}
}
export async function buildAll(options: BuildOptions) {
await Promise.all((await glob("src/main*.ts")).map((file) => {
log(`build ${file}`)
return build(file, {
...options,
outDir: BINDIR + "/" + file.slice(8, -3),
})
}))
}
export async function build(file: string, options: BuildOptions) {
file = file || "src/main.ts"
options.outDir = options.outDir || BINDIR
try {
await buildOnce(file, options)
} catch (e) {
if (e.name !== CompilationError.NAME) {
error("exception: " + e.message)
verboseLog(e.stack)
}
process.exit(EXIT_CODE_COMPILATION_ERROR)
}
}
async function buildOnce(file: string, options: BuildOptions) {
const { stats } = options
const { success, binary, dbg } = await compileFile(file, options)
if (!success) throw new CompilationError("compilation failed")
if (stats) {
log(`bytecode: ${prettySize(binary.length)}`)
const { sizes, functions } = dbg
log(
" " +
Object.keys(sizes)
.map(name => `${name}: ${prettySize(sizes[name])}`)
.join(", ")
)
log(` functions:`)
const resolver = SrcMapResolver.from(dbg)
functions
.sort((l, r) => l.size - r.size)
.forEach(fn => {
log(` ${fn.name} (${prettySize(fn.size)})`)
fn.users.forEach(user =>
debug(` <-- ${resolver.posToString(user[0])}`)
)
})
}
}