-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathesm-to-plain-js.ts
More file actions
118 lines (109 loc) · 4.47 KB
/
Copy pathesm-to-plain-js.ts
File metadata and controls
118 lines (109 loc) · 4.47 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
// esm-to-plain-js ~~ MIT License
//
// Usage in package.json:
// "scripts": {
// "make-plain-js": "esm-to-plain-js --cd=build web-app.esm.js web-app.js"
// },
//
// Usage from command line:
// $ npm install --save-dev esm-to-plain-js
// $ npx esm-to-plain-js web-app.esm.js web-app.js
//
// Contributors to this project:
// $ cd esm-to-plain-js
// $ npm install
// $ npm test
// $ node bin/cli.js --cd=spec fixtures/web-app.esm.js target/web-app.js
// Imports
import { cliArgvUtil } from 'cli-argv-util';
import chalk from 'chalk';
import fs from 'node:fs';
import log from 'fancy-log';
import os from 'node:os';
import path from 'node:path';
import slash from 'slash';
// Types
export type Settings = {
cd: string | null, //change working directory before starting copy
};
export type Result = {
origin: string, //path of source file
dest: string, //path of targe file
length: number, //size of the target file in bytes
duration: number, //execution time in milliseconds
};
const esmToPlainJs = {
assertOk(ok: unknown, message: string | null) {
if (!ok)
throw new Error(`[esm-to-plain-js] ${message}`);
},
cli() {
const validFlags = ['cd', 'note', 'quiet'];
const cli = cliArgvUtil.parse(validFlags);
const source = cli.params[0];
const target = cli.params[1];
const error =
cli.invalidFlag ? cli.invalidFlagMsg :
cli.paramCount > 2 ? 'Extraneous parameter: ' + cli.params[2]! :
!source ? 'Missing source file.' :
!target ? 'Missing target file.' :
null;
esmToPlainJs.assertOk(!error, error);
const options = {
cd: cli.flagMap.cd ?? null,
};
const result = esmToPlainJs.transform(source!, target!, options);
if (!cli.flagOn.quiet)
esmToPlainJs.reporter(result);
},
transform(sourceFile: string, targetFile: string, options?: Partial<Settings>): Result {
const defaults: Settings = {
cd: null,
};
const settings = { ...defaults, ...options };
const startTime = Date.now();
const clean = (folder: string) => slash(path.normalize(folder)).replace(/\/$/, '');
const cleanPath = (folder: string | null) => !folder ? '' : clean(folder);
const startFolder = settings.cd ? cleanPath(settings.cd) + '/' : '';
const source = sourceFile ? cleanPath(startFolder + sourceFile) : '';
const sourceExists = source && fs.existsSync(source);
const sourceIsFile = sourceExists && fs.statSync(source).isFile();
const target = targetFile ? cleanPath(startFolder + targetFile) : null;
const targetFolder = target ? path.dirname(target) : null;
if (targetFolder)
fs.mkdirSync(targetFolder, { recursive: true });
const badTargetFolder = !targetFolder || !fs.existsSync(targetFolder);
const error =
!sourceFile ? 'Must specify a source file.' :
!sourceExists ? 'Source file does not exist: ' + source :
!sourceIsFile ? 'Source is not a file: ' + source :
!target ? 'Must specify a target file.' :
badTargetFolder ? 'Target folder cannot be written to: ' + String(targetFolder) :
null;
esmToPlainJs.assertOk(!error, error);
const esm = fs.readFileSync(source, 'utf-8');
const importPattern = /^import .*/mg; //example: "import * as R from 'ramda';"
const exportPattern = /^export \{ (.*) \};$/m; //example: "export { webApp };"
const replaceImport = (stmt: string) => '// Ensure library is loaded => ' + stmt;
const toGlobal = (module: string) => `globalThis.${module} = ${module};`;
const replaceExport = (stmt: string, modules: string) =>
modules.split(', ').map(toGlobal).join(os.EOL);
const plainJs = esm
.replace(importPattern, replaceImport)
.replace(exportPattern, replaceExport);
fs.writeFileSync(target!, plainJs);
return {
origin: source,
dest: target!,
length: plainJs.length,
duration: Date.now() - startTime,
};
},
reporter(result: Result) {
const name = chalk.gray('esm-to-plain-js');
const ancestor = cliArgvUtil.calcAncestor(result.origin, result.dest);
const info = chalk.white(`(${result.duration}ms)`);
log(name, ancestor.message, info);
},
};
export { esmToPlainJs };