-
Notifications
You must be signed in to change notification settings - Fork 0
/
xelm.ts
executable file
·739 lines (613 loc) · 19.9 KB
/
xelm.ts
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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
#!/usr/bin/env -S deno run -A
import { cyan as colorize } from "https://deno.land/[email protected]/fmt/colors.ts";
import { parse } from "https://deno.land/[email protected]/flags/mod.ts";
import * as fs from "https://deno.land/[email protected]/fs/mod.ts";
import * as path from "https://deno.land/[email protected]/path/mod.ts";
import { marked } from "https://esm.sh/[email protected]/";
import { minify, MinifyOptions } from "https://esm.sh/[email protected]/";
import "npm:[email protected]";
import { transform as optimize } from "npm:[email protected]";
/** Compiler options. */
export interface Options {
/** Path to the root directory of the project. */
projectRoot?: string;
/** The path to the Elm binary. */
elmPath?: string;
/** Custom directory for ELM_HOME, which is `~/.elm` by default. */
elmHome?: string;
/** Generate a TypeScript bindings, implies `module`. */
typescript?: "node" | "deno";
/** Turn on the time-travelling debugger. */
debug?: boolean;
/** List of find-and-replace transformations to apply. */
transformations?: Transform[];
/** Tune the optimization level. */
optimize?: boolean | 0 | 1 | 2 | 3;
/** Minify the output with terser. */
minify?: boolean | MinifyOptions;
/** Change how error messages are reported. This is only useful when running
from the command-line interface as the provided functions do not capture the
outputs.
*/
report?: string;
/** Generate a JSON file with the documentation. */
docs?: string;
/** Enable test mode. Can be used with `elm-test-rs` with the `--compiler` flag. */
test?: boolean;
/** Controls how `stdout` and `stderr` of the compiler should be handled.
* Defaults to "inherit". Set to "piped" to access the output programmatically.
*/
output?: "inherit" | "piped" | "null";
}
/** Simple find-and-replace rules applied to the compiled code. */
export interface Transform {
/** Code to find. */
find: string;
/** Code to replace. */
replace: string;
}
/** Compile and perform post-processing
* @param inputs The input files to read.
* @param output The name of the resulting JavaScript file.
* @param options The compiler options.
* @returns The status returned from the compiler.
*/
export async function elm(inputs: string[], output: string, options?: Options) {
const config = {
elmHome: options?.elmHome ?? DEFAULT_ELM_HOME,
elmPath: options?.elmPath ?? "elm",
projectRoot: options?.projectRoot ?? Deno.cwd(),
module: path.extname(output) === ".mjs",
typescript: options?.typescript,
debug: options?.debug ?? false,
transformations: options?.transformations ?? [],
optimize: +(options?.optimize ?? 0) as 0 | 1 | 2 | 3,
minify: options?.minify ?? false,
report: options?.report,
docs: options?.docs,
test: options?.test ?? false,
output: options?.output,
};
if (!config.module && config.typescript) {
throw new ElmError(
"Generating TypeScript bindings require building an ECMAScript module.",
);
}
const needsTempFile = config.module ||
config.transformations.length > 0 ||
config.optimize > 1 ||
config.minify;
const out = needsTempFile ? `${await Deno.makeTempFile()}.js` : output;
if (config.elmHome !== DEFAULT_ELM_HOME) {
console.log(`export ELM_HOME=${config.elmHome}`);
}
if (config.projectRoot !== Deno.cwd()) console.log("cd", config.projectRoot);
const args = [
"make",
...inputs,
...(config.debug ? ["--debug"] : []),
...(config.optimize > 0 ? ["--optimize"] : []),
`--output=${out}`,
...(config.report ? [`--report=${config.report}`] : []),
...(config?.docs ? [`--docs=${config.docs}`] : []),
];
console.log(config.elmPath, ...args);
const status = await run(args, config);
if (!status.success || !needsTempFile) return status;
await postprocess(out, output, config);
return status;
}
/** Extra options for controlling the transformation cache. */
export interface ExtraOptions extends Options {
/** Force refreshing the transformation cache. */
refresh?: boolean;
}
/** Compile and perform post-processing.
* Automatically loads transformations from the project and dependency
* `README.md` files.
* @param inputs The input files to read.
* @param output The name of the resulting JavaScript file.
* @param options The compiler options.
* @returns The status returned from the compiler.
*/
export async function xelm(
inputs: string[],
output: string,
options?: ExtraOptions,
) {
const projectRoot = options?.projectRoot ?? Deno.cwd();
const elmHome = options?.elmHome ?? DEFAULT_ELM_HOME;
const transformations = await extractWithCache(
projectRoot,
elmHome,
options?.test ?? false,
options?.refresh ?? false,
);
if (options?.transformations !== undefined) {
for (const transform of options?.transformations) {
transformations.push(transform);
}
}
return elm(inputs, output, {
...options,
projectRoot,
elmHome,
transformations,
});
}
/**
* Executes the command-line interface (CLI).
* @param args - An array of command-line arguments.
* @returns The status returned from the compiler.
*/
export async function cli(args = Deno.args) {
if (args[0] !== "make") return await run(args);
const { inputs, output, options, transform } = await parseCliArgs(args);
try {
return transform
? xelm(inputs, output, options)
: elm(inputs, output, options);
} catch (e) {
if (e instanceof ElmError) {
console.error(e.message);
Deno.exit(1);
}
throw e;
}
}
// INTERNALS
const TERSER_CONFIG_JSON = "terser.config.json";
const ELM_JSON = "elm.json";
const README_MD = "README.md";
const ELM_STUFF = "elm-stuff";
const ELM_HOME = Deno.env.get("ELM_HOME");
const DEFAULT_ELM_HOME = ELM_HOME ?? `${Deno.env.get("HOME")}/.elm`;
export class ElmError extends Error {
constructor(message: string) {
super(message);
}
}
// CLI
async function parseCliArgs(args: string[]) {
const parsed = parse(args.slice(1, args.length), {
string: [
"output",
"elm-home",
"compiler",
"project",
"report",
"docs",
],
boolean: [
"help",
"debug",
"minify",
"transform",
"test",
"refresh",
],
});
const flags: Flags = {
projectRoot: parsed.project,
elmPath: parsed.compiler,
elmHome: parsed["elm-home"],
};
if (parsed.help) {
await help(flags);
Deno.exit(0);
}
assertOutput(parsed.output);
assertOptimize(parsed.optimize);
assertTypescript(parsed.typescript);
const inputs = parsed._.map((input) => input.toString());
const options: ExtraOptions = {
...flags,
typescript: typeof parsed.typescript === "boolean"
? (parsed.typescript ? "deno" : undefined)
: (parsed.typescript ?? undefined),
debug: parsed.debug,
optimize: parsed.optimize,
minify: parsed.minify
? (await getMinifyOptions(parsed.project) ?? parsed.minify)
: parsed.minify,
report: parsed.report,
docs: parsed.docs,
test: parsed.test,
refresh: parsed.refresh,
};
return {
inputs,
output: parsed.output,
options,
transform: parsed.transform,
};
}
if (import.meta.main) await cli();
// ELM
interface Flags {
projectRoot?: string | undefined;
elmHome?: string | undefined;
elmPath?: string | undefined;
output?: "inherit" | "piped" | "null";
}
async function run(args: string[], flags?: Flags) {
return await new Deno.Command(flags?.elmPath ?? "elm", {
args: [...args],
cwd: flags?.projectRoot,
env: flags?.elmHome ? { ELM_HOME: flags?.elmHome } : undefined,
stdin: "null",
stdout: flags?.output ?? "inherit",
stderr: flags?.output ?? "inherit",
}).spawn().status;
}
interface PostConfig {
module: boolean;
typescript?: "deno" | "node";
debug: boolean;
test: boolean;
transformations: Transform[];
optimize: 0 | 1 | 2 | 3;
minify: boolean | MinifyOptions;
}
async function postprocess(src: string, dest: string, config: PostConfig) {
let content = await Deno.readTextFile(src);
if (config.transformations.length > 0) {
content = transform(content, config);
}
if (config.module) {
content = modularize(content);
if (config.typescript) typescript(dest, config.typescript);
}
if (config.optimize > 1) {
content = await optimize(content, config.optimize === 3);
}
if (config.minify !== false) {
const minifyOptions = config.minify !== true ? config.minify : undefined;
const result = await minify(content, minifyOptions);
content = result.code ?? content;
}
await Deno.writeTextFile(dest, content);
}
function transform(content: string, config: PostConfig) {
const map: { [find: string]: string } = {};
const patterns: string[] = [];
for (const { find, replace } of config.transformations) {
const fmt = spacesToTabs(find);
map[fmt] = preprocess(spacesToTabs(replace), config);
const txt = escapeRegExp(fmt);
patterns.push(txt);
}
const regexp = new RegExp(`(${patterns.join("|")})`, "gm");
return content.replaceAll(regexp, (substring) => map[substring] ?? substring);
}
function escapeRegExp(text: string) {
return text.replace(/[.*+?^${}()|[\]\\\/]/g, "\\$&");
}
function spacesToTabs(content: string, spaces = " ") {
return content.replace(/^\s+/gm, (match) => match.replaceAll(spaces, "\t"));
}
function preprocess(content: string, config: PostConfig) {
const lines: string[] = [];
const vars = ["debug", "test"] as const;
type Flags = typeof vars[number];
const stack: { flag: Flags; cond: boolean }[] = [];
lines:
for (const line of content.split("\n")) {
const [comment, cond, flag] = line.trim().split(/\s+/);
if (comment === "//") {
if (cond === "@IF" && vars.includes(flag as Flags)) {
stack.push({ flag: flag as Flags, cond: true });
continue lines;
} else if (cond === "@UNLESS" && vars.includes(flag as Flags)) {
stack.push({ flag: flag as Flags, cond: false });
continue lines;
} else if (cond === "@END") {
stack.pop();
continue lines;
}
}
for (const { flag, cond } of stack) {
if (cond !== (config[flag] ?? false)) continue lines;
}
lines.push(
stack.length === 0 ? line : line.replace("\t".repeat(stack.length), ""),
);
}
return lines.join("\n");
}
function modularize(content: string) {
const pre = "(function(scope){\n'use strict';".length;
const pos = "(this));".length;
return `const scope = {};\n(function(scope){` +
content.slice(pre, content.length - pos) +
`(scope));\nexport default scope.Elm;`;
}
async function typescript(dest: string, runtime: "deno" | "node") {
const { dir, name } = path.parse(dest);
await Deno.writeTextFile(
path.join(dir, `${name}.ts`),
`/// <reference lib="dom" />
import elm from "./${name}${runtime === "deno" ? ".mjs" : ""}";
interface Elm {
[module: Capitalize<string>]: Elm | undefined;
init?: (options?: { node?: Node; flags?: unknown }) => {
ports?: {
[port: string]:
| { send(value: unknown): void }
| {
subscribe(listener: (value: unknown) => void): void;
unsubscribe(listener: (value: unknown) => void): void;
}
| undefined;
};
};
}
export const Elm: { [module: Capitalize<string>]: Elm | undefined } = elm;
`,
);
}
// EXTRACT
async function extractWithCache(
projectRoot: string,
elmHome: string,
test: boolean,
refresh: boolean,
): Promise<Transform[]> {
const transformationsFile = path.join(
projectRoot,
ELM_STUFF,
"transformations.json",
);
const changed = refresh
? refresh
: (await needsCacheRefresh(projectRoot, transformationsFile));
if (!changed) {
return JSON.parse(await Deno.readTextFile(transformationsFile));
}
const transformations = await extract(projectRoot, elmHome, test);
await Deno.writeTextFile(
transformationsFile,
JSON.stringify(transformations),
);
return transformations;
}
async function extract(projectRoot: string, elmHome: string, test: boolean) {
const elmJsonFile = path.join(projectRoot, ELM_JSON);
const { version, dependencies } = await parseElmJson(elmJsonFile);
const readmeFile = test
? path.join(projectRoot, "..", "..", README_MD)
: path.join(projectRoot, README_MD);
const name = test
? (await parseElmJson(path.join(projectRoot, "..", "..", ELM_JSON))).name
: undefined;
const transformations = await extractReadme(readmeFile, name);
const directory = path.join(elmHome, version, "packages");
for (const [dep, ver] of dependencies) {
for (const transform of await extractDependency(dep, ver, directory)) {
transformations.push(transform);
}
}
return transformations;
}
async function parseElmJson(filePath: string) {
if (!await fs.exists(filePath)) {
throw new ElmError(`Could not find '${ELM_JSON}' at ${filePath}`);
}
type StringRecord = Record<string, string>;
type Dependencies = { direct: StringRecord; indirect: StringRecord };
type ElmJson = {
["name"]: string;
dependencies: Dependencies;
["elm-version"]: string;
};
const elmJson: ElmJson = JSON.parse(await Deno.readTextFile(filePath));
const version = elmJson["elm-version"];
if (version === undefined) {
throw new ElmError(`Undefined "elm-version" field in '${ELM_JSON}'`);
}
const { direct, indirect } = elmJson["dependencies"] ?? {};
const dependencies = Object.entries(direct ?? {}).concat(
Object.entries(indirect ?? {}),
);
return { name: elmJson.name, version, dependencies };
}
async function extractDependency(
dependency: string,
version: string,
directory: string,
) {
const [author, name] = dependency.split("/");
if (author === undefined) {
console.error("Undefined package author");
}
if (name === undefined) {
console.error("Undefined package name");
}
const markdownFile = path.join(
directory,
author,
name,
version,
README_MD,
);
return await extractReadme(markdownFile);
}
async function extractReadme(filePath: string, namespace?: string) {
if (!await fs.exists(filePath)) return [];
const regExp = namespace ? getNamespace(namespace) : undefined;
const content = await Deno.readTextFile(filePath);
const transforms: Transform[] = [];
let collect = false;
let find: string | undefined = undefined;
for (const token of marked.lexer(content)) {
if (collect && token.type === "heading" && token.depth < 4) break;
if (!collect && token.type === "paragraph") {
for (const item of token.tokens) {
if (
item.type === "link" &&
item.href === "#98f5c378-5809-4e35-904e-d1c5c3a8154e"
) {
collect = true;
break;
}
}
}
if (collect && token.type === "code") {
if (token.lang !== "js") {
throw new ElmError(`Unexpected '${token.lang}' code block`);
}
const text = regExp
? token.text.replaceAll(regExp, "$author$project$")
: token.text;
if (find !== undefined) {
transforms.push({ find, replace: spacesToTabs(text, " ") });
find = undefined;
} else {
find = spacesToTabs(text, " ");
}
}
}
if (find !== undefined) {
throw new ElmError(
`Unmatched find-and-replace transformation pattern:\n\n${find}`,
);
}
return transforms;
}
function getNamespace(name: string) {
const [author, project] = escapeVar(name).split("/");
if (author === undefined) {
throw new ElmError(`Could not extract author name from ${ELM_JSON}`);
}
if (project === undefined) {
throw new ElmError(`Could not extract project name from ${ELM_JSON}`);
}
const authorPart = escapeRegExp(escapeVar(author));
const projectPart = escapeRegExp(escapeVar(project));
return new RegExp(
`\\\$${authorPart}\\\$${projectPart}\\\$`,
"gm",
);
}
function escapeVar(name: string) {
// TODO: proper escape
return name.replace(/\-/gm, "_");
}
// CACHE
async function needsCacheRefresh(
projectRoot: string,
transformationsFile: string,
) {
if (!await fs.exists(transformationsFile)) return true;
const dependenciesChanged = await isModifiedAfter(
path.join(projectRoot, ELM_JSON),
transformationsFile,
);
const readmeChanged = await isModifiedAfter(
path.join(projectRoot, README_MD),
transformationsFile,
);
return dependenciesChanged || readmeChanged;
}
async function isModifiedAfter(src: string, dest: string) {
const srcTime = await getModificationTime(src, Number.POSITIVE_INFINITY);
const destTime = await getModificationTime(dest, 0);
return srcTime > destTime;
}
async function getModificationTime(filePath: string, fallback: number) {
try {
return (await Deno.stat(filePath)).mtime?.getTime() ?? fallback;
} catch (e) {
if (e instanceof Deno.errors.NotFound) return fallback;
throw e;
}
}
// CLI
async function help(flags: Flags) {
await run(["make", "--help"], flags);
const l = console.log.bind(console);
const h = (s: string) => console.log(colorize(s));
l("Expanded flags:");
l("");
h(" --output=<output-file>");
l(" Expanded to build ECMAScript modules. For example");
l(" --output=assets/elm.mjs to generate the module at assets/elm.mjs");
l("");
h(" --optimize=0");
l(" Disable all optimizations.");
l("");
h(" --optimize=1");
l(" Same as running `elm make --optimize`.");
l("");
h(" --optimize=2");
l(" Same as running `elm-optimize-level-2`.");
l("");
h(" --optimize=3");
l(" Same as running `elm-optimize-level-2 --optimize-speed`.");
l("");
h(" --compiler=<elm-binary>");
l(" The path to the Elm binary, which is `elm` by default.");
l("");
h(" --project=<project-root>");
l(" Path to the root directory of the project.");
l(" Defaults to the current working directory.");
l("");
h(" --elm-home=<elm-home>");
l(" Use a custom directory for ELM_HOME, which is `~/.elm` by default.");
if ((ELM_HOME ?? "") !== "") {
l(` [env: ELM_HOME=${Deno.env.get("ELM_HOME")}]`);
}
l("");
h(" --typescript=<runtime>");
l(" Generate TypeScript bindings for the given runtime. For example,");
l(" --typescript=node generates bindings for Node.js. Defaults to deno and");
l(" requires a `.mjs` output.");
l("");
h(" --minify");
l(` Minify the output with terser, loading configuration from`);
l(` \`${TERSER_CONFIG_JSON}\` if available.`);
l("");
h(" --transform");
l(" Enable loading find-and-replace transformations from `README.md` files.");
l("");
h(" --test");
l(" Load find-and-replace transformations from test dependencies.");
l("");
h(" --refresh");
l(" Refresh find-and-replace transformation cache.");
}
function assertOutput(
output: unknown,
): asserts output is string {
if (typeof output !== "string") throw new ElmError("No output file");
if (![".js", ".mjs"].includes(path.extname(output))) {
throw new ElmError("Output must be JavaScript or ECMAScript module");
}
}
function assertOptimize(
optimize: unknown,
): asserts optimize is Options["optimize"] {
if (optimize === undefined || typeof optimize === "boolean") return;
if (typeof optimize === "number" && (optimize < 0 || optimize > 3)) {
throw new ElmError(`Invalid optimization level ${optimize}`);
}
}
function assertTypescript(
typescript: unknown,
): asserts typescript is Options["typescript"] {
if (typescript === undefined || typeof typescript === "boolean") return;
if (typescript !== "deno" && typescript !== "node") {
throw new ElmError(`Invalid TypeScript format ${typescript}`);
}
}
async function getMinifyOptions(projectRoot?: string) {
const terserFile = path.join(projectRoot ?? Deno.cwd(), TERSER_CONFIG_JSON);
if (!await fs.exists(terserFile)) return undefined;
try {
return JSON.parse(await Deno.readTextFile(terserFile));
} catch (e) {
throw new ElmError(
`Could not parse \`${TERSER_CONFIG_JSON}\`: ${e.message}`,
);
}
}