@cxl/build 0.2.1 → 1.0.0-beta.1

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/test-report.html DELETED
@@ -1,1200 +0,0 @@
1
- <!DOCTYPE html>
2
- <head><title>Test Report</title></head>
3
- <style>
4
- body { font-size: 16px; }
5
- em.covered { background-color: #a5d6a7 }
6
- em { background-color: #ef9a9a; }
7
- </style><table><tr>
8
- <td><a href="#test.js">test.js</a></td>
9
- <td>100.00% (1487/1487)</td>
10
- </tr><tr>
11
- <td><a href="#index.js">index.js</a></td>
12
- <td>78.67% (3920/4983)</td>
13
- </tr><tr>
14
- <td><a href="#cxl.js">cxl.js</a></td>
15
- <td>52.11% (6632/12728)</td>
16
- </tr><tr>
17
- <td><a href="#builder.js">builder.js</a></td>
18
- <td>59.07% (5394/9132)</td>
19
- </tr><tr>
20
- <td><a href="#tsc.js">tsc.js</a></td>
21
- <td>54.03% (6504/12038)</td>
22
- </tr><tr>
23
- <td><a href="#package.js">package.js</a></td>
24
- <td>55.01% (11661/21198)</td>
25
- </tr><tr>
26
- <td><a href="#file.js">file.js</a></td>
27
- <td>55.27% (4785/8657)</td>
28
- </tr><tr>
29
- <td><a href="#npm.js">npm.js</a></td>
30
- <td>54.26% (3126/5761)</td>
31
- </tr><tr>
32
- <td><a href="#git.js">git.js</a></td>
33
- <td>58.75% (839/1428)</td>
34
- </tr><tr>
35
- <td><a href="#lint.js">lint.js</a></td>
36
- <td>54.11% (1416/2617)</td>
37
- </tr></table><h2><a name="test.js">test.js</a></h2><pre><em class="covered">"use strict";
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- const spec_1 = require("@cxl/spec");
40
- const index_js_1 = require("./index.js");
41
- exports.default = (0, spec_1.spec)('build', <em class="covered">s =&gt; {
42
- s.test('exec', <em class="covered">it =&gt; {
43
- it.should('throw error if exec fails', <em class="covered">a =&gt; {
44
- const done = a.async();
45
- (0, index_js_1.exec)('exit 1')
46
- .catchError(<em class="covered">e =&gt; {
47
- a.ok(e !== undefined);
48
- done();
49
- }</em>)
50
- .subscribe();
51
- }</em>);
52
- }</em>);
53
- }</em>);
54
- </em></pre><h2><a name="index.js">index.js</a></h2><pre><em class="covered">#!/usr/bin/env node
55
- "use strict";
56
- Object.defineProperty(exports, "__esModule", { value: true });
57
- exports.shell = exports.exec = exports.build = exports.buildCxl = exports.docgenTask = exports.docgen = exports.template = exports.bundleAmd = exports.bundle = exports.readme = exports.pkg = exports.REQUIRE_REPLACE = exports.AMD = exports.readJson = exports.sh = exports.mkdirp = exports.concat = exports.zip = exports.minify = exports.copyDir = exports.concatFile = exports.files = exports.file = exports.basename = exports.tsBundle = exports.tsconfig = void 0;
58
- const cxl_js_1 = require("./cxl.js");
59
- var tsc_js_1 = require("./tsc.js");
60
- Object.defineProperty(exports, "tsconfig", { enumerable: true, get: <em class="">function () { return tsc_js_1.tsconfig; }</em> });
61
- Object.defineProperty(exports, "tsBundle", { enumerable: true, get: <em class="">function () { return tsc_js_1.bundle; }</em> });
62
- var file_js_1 = require("./file.js");
63
- Object.defineProperty(exports, "basename", { enumerable: true, get: <em class="">function () { return file_js_1.basename; }</em> });
64
- Object.defineProperty(exports, "file", { enumerable: true, get: <em class="">function () { return file_js_1.file; }</em> });
65
- Object.defineProperty(exports, "files", { enumerable: true, get: <em class="">function () { return file_js_1.files; }</em> });
66
- Object.defineProperty(exports, "concatFile", { enumerable: true, get: <em class="">function () { return file_js_1.concatFile; }</em> });
67
- Object.defineProperty(exports, "copyDir", { enumerable: true, get: <em class="">function () { return file_js_1.copyDir; }</em> });
68
- Object.defineProperty(exports, "minify", { enumerable: true, get: <em class="">function () { return file_js_1.minify; }</em> });
69
- Object.defineProperty(exports, "zip", { enumerable: true, get: <em class="">function () { return file_js_1.zip; }</em> });
70
- var rx_1 = require("@cxl/rx");
71
- Object.defineProperty(exports, "concat", { enumerable: true, get: <em class="">function () { return rx_1.concat; }</em> });
72
- var program_1 = require("@cxl/program");
73
- Object.defineProperty(exports, "mkdirp", { enumerable: true, get: <em class="">function () { return program_1.mkdirp; }</em> });
74
- Object.defineProperty(exports, "sh", { enumerable: true, get: <em class="">function () { return program_1.sh; }</em> });
75
- Object.defineProperty(exports, "readJson", { enumerable: true, get: <em class="">function () { return program_1.readJson; }</em> });
76
- var package_js_1 = require("./package.js");
77
- Object.defineProperty(exports, "AMD", { enumerable: true, get: <em class="">function () { return package_js_1.AMD; }</em> });
78
- Object.defineProperty(exports, "REQUIRE_REPLACE", { enumerable: true, get: <em class="">function () { return package_js_1.REQUIRE_REPLACE; }</em> });
79
- Object.defineProperty(exports, "pkg", { enumerable: true, get: <em class="">function () { return package_js_1.pkg; }</em> });
80
- Object.defineProperty(exports, "readme", { enumerable: true, get: <em class="">function () { return package_js_1.readme; }</em> });
81
- Object.defineProperty(exports, "bundle", { enumerable: true, get: <em class="">function () { return package_js_1.bundle; }</em> });
82
- Object.defineProperty(exports, "bundleAmd", { enumerable: true, get: <em class="">function () { return package_js_1.bundleAmd; }</em> });
83
- Object.defineProperty(exports, "template", { enumerable: true, get: <em class="">function () { return package_js_1.template; }</em> });
84
- Object.defineProperty(exports, "docgen", { enumerable: true, get: <em class="">function () { return package_js_1.docgen; }</em> });
85
- Object.defineProperty(exports, "docgenTask", { enumerable: true, get: <em class="">function () { return package_js_1.docgenTask; }</em> });
86
- var cxl_js_2 = require("./cxl.js");
87
- Object.defineProperty(exports, "buildCxl", { enumerable: true, get: <em class="">function () { return cxl_js_2.buildCxl; }</em> });
88
- var builder_js_1 = require("./builder.js");
89
- Object.defineProperty(exports, "build", { enumerable: true, get: <em class="">function () { return builder_js_1.build; }</em> });
90
- Object.defineProperty(exports, "exec", { enumerable: true, get: <em class="covered">function () { return builder_js_1.exec; }</em> });
91
- Object.defineProperty(exports, "shell", { enumerable: true, get: <em class="">function () { return builder_js_1.shell; }</em> });
92
- if (require.main?.filename === __filename)
93
- <em class="">(0, cxl_js_1.buildCxl)();</em>
94
- </em></pre><h2><a name="cxl.js">cxl.js</a></h2><pre><em class="covered">"use strict";
95
- Object.defineProperty(exports, "__esModule", { value: true });
96
- exports.minifyIf = minifyIf;
97
- exports.generateTestFile = generateTestFile;
98
- exports.buildCxl = buildCxl;
99
- const path_1 = require("path");
100
- const child_process_1 = require("child_process");
101
- const fs_1 = require("fs");
102
- const rx_1 = require("@cxl/rx");
103
- const builder_js_1 = require("./builder.js");
104
- const package_js_1 = require("./package.js");
105
- const file_js_1 = require("./file.js");
106
- const lint_js_1 = require("./lint.js");
107
- const tsc_js_1 = require("./tsc.js");
108
- <em class="">function minifyIf(filename) {
109
- return (0, rx_1.mergeMap)((out) =&gt; out.path === filename
110
- ? (0, rx_1.concat)((0, rx_1.of)(out), (0, file_js_1.file)(out.path).pipe((0, file_js_1.minify)()))
111
- : (0, rx_1.of)(out));
112
- }</em>
113
- <em class="">function generateTestFile(dirName, pkgName, testFile) {
114
- return `&lt;!DOCTYPE html&gt;
115
- &lt;title&gt;${pkgName} Test Suite&lt;/title&gt;
116
- &lt;script type="module" src="/cxl/dist/tester/require-browser.js"&gt;&lt;/script&gt;
117
- &lt;script type="module"&gt;
118
- require.replace = function (path) {
119
- return path.replace(
120
- /^@j5g3\\/(.+)/,
121
- (str, p1) =&gt;
122
- \`/j5g3/dist/\${str.endsWith('.js') ? p1 : p1 + '/index.js'}\`
123
- )
124
- .replace(
125
- /^@cxl\\/workspace\\.(.+)/,
126
- (str, p1) =&gt;
127
- \`/cxl.app/dist/$\{
128
- str.endsWith('.js') ? p1 : p1 + '/index.js'
129
- }\`
130
- )
131
- .replace(
132
- /^@cxl\\/gbc\.(.*)/,
133
- (str, p1) =&gt;
134
- \`/gbc/dist/$\{
135
- str.endsWith('.js') ? p1 : p1 + '/index.js'
136
- }\`
137
- )
138
- .replace(
139
- /^@cxl\\/(ui.*)/,
140
- (str, p1) =&gt;
141
- \`/ui/dist/$\{
142
- str.endsWith('.js') ? p1 : p1 + '/index.js'
143
- }\`
144
- )
145
- .replace(
146
- /^@cxl\\/(.+)/,
147
- (str, p1) =&gt;
148
- \`/cxl/dist/$\{
149
- str.endsWith('.js') ? p1 : p1 + '/index.js'
150
- }\`
151
- );
152
- };
153
- const browserRunner = require('/cxl/dist/tester/browser-runner.js').default;
154
-
155
- const suite = require('${testFile}').default;
156
- browserRunner.run([suite], '../../${dirName}/spec');
157
- &lt;/script&gt;`;
158
- }</em>
159
- <em class="">function buildCxl(...extra) {
160
- const packageJson = (0, package_js_1.readPackage)();
161
- const cwd = process.cwd();
162
- const tsconfigFile = require(cwd + '/tsconfig.json');
163
- const outputDir = tsconfigFile?.compilerOptions?.outDir;
164
- if (!outputDir)
165
- throw new Error('No outDir field set in tsconfig.json');
166
- const dirName = (0, path_1.basename)(outputDir);
167
- const tester = (0, path_1.join)(__dirname, '../tester');
168
- const isBrowser = !!packageJson.browser;
169
- return (0, builder_js_1.build)({
170
- target: 'clean',
171
- outputDir,
172
- tasks: [
173
- (0, rx_1.observable)(() =&gt; {
174
- (0, child_process_1.execSync)(`rm -rf ${outputDir}`);
175
- }),
176
- ],
177
- }, {
178
- outputDir,
179
- tasks: [
180
- (0, file_js_1.file)('index.html', 'index.html').catchError(() =&gt; rx_1.EMPTY),
181
- (0, file_js_1.file)('debug.html', 'debug.html').catchError(() =&gt; rx_1.EMPTY),
182
- (0, file_js_1.file)('stage.html', 'stage.html').catchError(() =&gt; rx_1.EMPTY),
183
- (0, file_js_1.file)('icons.svg', 'icons.svg').catchError(() =&gt; rx_1.EMPTY),
184
- (0, file_js_1.file)('favicon.ico', 'favicon.ico').catchError(() =&gt; rx_1.EMPTY),
185
- (0, file_js_1.file)('test.html', 'test.html').catchError(() =&gt; (0, rx_1.of)({
186
- path: 'test.html',
187
- source: Buffer.from(generateTestFile(dirName, packageJson.name, './test.js')),
188
- })),
189
- (0, tsc_js_1.tsconfig)('tsconfig.test.json'),
190
- ],
191
- }, {
192
- target: 'test',
193
- outputDir,
194
- tasks: [
195
- (0, builder_js_1.exec)(`cd ${outputDir} &amp;&amp; node ${tester} --baselinePath=../../${dirName}/spec${isBrowser ? '' : ' --node'}`),
196
- ],
197
- }, {
198
- target: 'package',
199
- outputDir: '.',
200
- tasks: [(0, package_js_1.readme)()],
201
- }, {
202
- target: 'package',
203
- outputDir,
204
- tasks: [
205
- (0, lint_js_1.eslint)(),
206
- packageJson.browser
207
- ? (0, file_js_1.file)(`${outputDir}/index.js`).pipe((0, file_js_1.minify)())
208
- : rx_1.EMPTY,
209
- (0, package_js_1.pkg)(),
210
- ],
211
- }, ...((0, fs_1.existsSync)('tsconfig.amd.json')
212
- ? [
213
- {
214
- target: 'package',
215
- outputDir: outputDir + '/amd',
216
- tasks: [
217
- (0, rx_1.concat)((0, tsc_js_1.tsconfig)('tsconfig.amd.json'), (0, file_js_1.minifyDir)(outputDir + '/amd', {
218
- sourceMap: false,
219
- changePath: false,
220
- })),
221
- ],
222
- },
223
- ]
224
- : []), ...((0, fs_1.existsSync)('tsconfig.mjs.json')
225
- ? [
226
- {
227
- target: 'package',
228
- outputDir: outputDir + '/mjs',
229
- tasks: [
230
- (0, rx_1.concat)((0, tsc_js_1.tsconfig)('tsconfig.mjs.json'), (0, file_js_1.minifyDir)(outputDir + '/mjs', {
231
- sourceMap: false,
232
- changePath: false,
233
- })),
234
- ],
235
- },
236
- ]
237
- : []), ...((0, fs_1.existsSync)('tsconfig.api.json')
238
- ? [
239
- {
240
- outputDir: outputDir,
241
- tasks: [
242
- (0, tsc_js_1.tsconfig)('tsconfig.api.json', {
243
- sourceMap: false,
244
- })
245
- .filter(({ path }) =&gt; path.endsWith('.js'))
246
- .pipe((0, file_js_1.concatFile)('server.js')),
247
- ],
248
- },
249
- ]
250
- : []), ...((0, fs_1.existsSync)('tsconfig.server.json')
251
- ? [
252
- {
253
- outputDir: outputDir,
254
- tasks: [(0, tsc_js_1.tsconfig)('tsconfig.server.json')],
255
- },
256
- ]
257
- : []), ...((0, fs_1.existsSync)('tsconfig.worker.json')
258
- ? [
259
- {
260
- outputDir: outputDir,
261
- tasks: [
262
- (0, tsc_js_1.tsconfig)('tsconfig.worker.json', undefined, outputDir),
263
- ],
264
- },
265
- ]
266
- : []), ...((0, fs_1.existsSync)('tsconfig.bundle.json')
267
- ? [
268
- {
269
- target: 'package',
270
- outputDir: outputDir,
271
- tasks: [
272
- (0, rx_1.concat)((0, tsc_js_1.tsconfig)('tsconfig.bundle.json'), (0, file_js_1.file)(`${outputDir}/index.bundle.js`).pipe((0, file_js_1.minify)({ changePath: false }))),
273
- ],
274
- },
275
- ]
276
- : []), {
277
- target: 'docs-dev',
278
- outputDir: '.',
279
- tasks: [(0, package_js_1.docs)(dirName, true)],
280
- }, ...extra, {
281
- target: 'docs',
282
- outputDir: '.',
283
- tasks: [(0, package_js_1.docs)(dirName)],
284
- });
285
- }</em>
286
- </em></pre><h2><a name="builder.js">builder.js</a></h2><pre><em class="covered">"use strict";
287
- Object.defineProperty(exports, "__esModule", { value: true });
288
- exports.appLog = void 0;
289
- exports.build = build;
290
- exports.exec = exec;
291
- exports.shell = shell;
292
- exports.run = run;
293
- const path_1 = require("path");
294
- const fs_1 = require("fs");
295
- const child_process_1 = require("child_process");
296
- const program_1 = require("@cxl/program");
297
- const rx_1 = require("@cxl/rx");
298
- const tsc_js_1 = require("./tsc.js");
299
- const package_js_1 = require("./package.js");
300
- const AppName = program_1.colors.green('build');
301
- exports.appLog = program_1.log.bind(null, AppName);
302
- <em class="">function kb(bytes) {
303
- return (bytes / 1000).toFixed(2) + 'kb';
304
- }</em>
305
- class Build {
306
- <em class="">constructor(log, config) {
307
- this.log = log;
308
- this.config = config;
309
- this.outputDir = config.outputDir || '.';
310
- }</em>
311
- <em class="">async runTask(task) {
312
- await task.tap(result =&gt; {
313
- const outFile = (0, path_1.resolve)(this.outputDir, result.path);
314
- const source = result.source;
315
- const outputDir = (0, path_1.dirname)(outFile);
316
- if (!(0, fs_1.existsSync)(outputDir))
317
- (0, child_process_1.execSync)(`mkdir -p ${outputDir}`);
318
- (0, fs_1.writeFileSync)(outFile, source);
319
- if (result.mtime)
320
- (0, fs_1.utimesSync)(outFile, result.mtime, result.mtime);
321
- const printPath = (0, path_1.relative)(process.cwd(), outFile);
322
- this.log(`${printPath} ${kb((result.source || '').length)}`);
323
- });
324
- }</em>
325
- <em class="">async build() {
326
- try {
327
- const target = this.config.target || '';
328
- if (target)
329
- this.log(`target ${target}`);
330
- (0, child_process_1.execSync)(`mkdir -p ${this.outputDir}`);
331
- await Promise.all(this.config.tasks.map(task =&gt; this.runTask(task)));
332
- }
333
- catch (e) {
334
- console.log('BUILD: ', e);
335
- throw 'Build finished with errors';
336
- }
337
- }</em>
338
- }
339
- <em class="">async function build(...targets) {
340
- if (!targets)
341
- throw new Error('Invalid configuration');
342
- if (package_js_1.BASEDIR !== process.cwd()) {
343
- process.chdir(package_js_1.BASEDIR);
344
- (0, exports.appLog)(`chdir "${package_js_1.BASEDIR}"`);
345
- }
346
- const pkg = (0, package_js_1.readPackage)();
347
- (0, exports.appLog)(`${pkg.name} ${pkg.version}`);
348
- (0, exports.appLog)(`typescript ${tsc_js_1.tscVersion}`);
349
- const runTargets = [undefined, ...process.argv];
350
- try {
351
- for (const targetId of runTargets) {
352
- for (const target of targets)
353
- if (target.target === targetId)
354
- await new Build(exports.appLog, target).build();
355
- }
356
- }
357
- catch (e) {
358
- console.error(e);
359
- process.exit(1);
360
- }
361
- }</em>
362
- <em class="">function formatTime(time) {
363
- const s = Number(time) / 1e9, str = s.toFixed(4) + 's';
364
- // Color code based on time,
365
- return s &gt; 0.1 ? (s &gt; 0.5 ? program_1.colors.red(str) : program_1.colors.yellow(str)) : str;
366
- }</em>
367
- <em class="covered">function exec(cmd) {
368
- return new rx_1.Observable(<em class="covered">subs =&gt; {
369
- (0, exports.appLog)(`sh ${cmd}`);
370
- (0, program_1.operation)((0, program_1.sh)(cmd, {})).then(<em class="">result =&gt; {
371
- (0, exports.appLog)(`sh ${cmd}`, formatTime(result.time));
372
- if (result.result)
373
- console.log(result.result);
374
- subs.complete();
375
- }</em>, <em class="covered">e =&gt; {
376
- subs.error(e);
377
- }</em>);
378
- }</em>);
379
- }</em>
380
- <em class="">function shell(cmd, options = {}) {
381
- return new rx_1.Observable(subs =&gt; {
382
- const proc = (0, child_process_1.spawn)(cmd, [], { shell: true, ...options });
383
- let output;
384
- let error;
385
- proc.stdout?.on('data', data =&gt; (output = output
386
- ? Buffer.concat([output, Buffer.from(data)])
387
- : Buffer.from(data)));
388
- proc.stderr?.on('data', data =&gt; (error = error
389
- ? Buffer.concat([error, Buffer.from(data)])
390
- : Buffer.from(data)));
391
- proc.on('close', code =&gt; {
392
- if (code)
393
- subs.error(error || output);
394
- else {
395
- subs.next(output);
396
- subs.complete();
397
- }
398
- });
399
- });
400
- }</em>
401
- <em class="">function run(cmd, params, options) {
402
- const args = [cmd];
403
- for (const p in params) {
404
- const val = params[p];
405
- if (val === false || val === undefined)
406
- continue;
407
- if (Array.isArray(val)) {
408
- val.forEach(v =&gt; args.push(`--${p} "${v}"`));
409
- }
410
- else
411
- args.push(typeof val === 'boolean' ? `--${p}` : `--${p} "${val}"`);
412
- }
413
- console.log(args.join(' '));
414
- return (0, program_1.sh)(args.join(' '), options);
415
- }</em>
416
- </em></pre><h2><a name="tsc.js">tsc.js</a></h2><pre><em class="covered">"use strict";
417
- Object.defineProperty(exports, "__esModule", { value: true });
418
- exports.tscVersion = void 0;
419
- exports.buildDiagnostics = buildDiagnostics;
420
- exports.printDiagnostics = printDiagnostics;
421
- exports.tsbuild = tsbuild;
422
- exports.tsconfig = tsconfig;
423
- exports.flagsToString = flagsToString;
424
- exports.bundle = bundle;
425
- const path_1 = require("path");
426
- const rx_1 = require("@cxl/rx");
427
- const tsPath = require.resolve('typescript', {
428
- paths: [process.cwd(), __dirname],
429
- });
430
- const ts = require(tsPath);
431
- const sys = ts.sys;
432
- const AMD = require('fs').readFileSync(__dirname + '/amd.js');
433
- const parseConfigHost = {
434
- useCaseSensitiveFileNames: true,
435
- readDirectory: sys.readDirectory,
436
- getCurrentDirectory: sys.getCurrentDirectory,
437
- fileExists: sys.fileExists,
438
- readFile: sys.readFile,
439
- <em class="">onUnRecoverableConfigFileDiagnostic(e) {
440
- throw e;
441
- }</em>,
442
- };
443
- const diagnosticsHost = {
444
- getCurrentDirectory: sys.getCurrentDirectory,
445
- getNewLine: <em class="">() =&gt; '\n'</em>,
446
- getCanonicalFileName: <em class="">n =&gt; n</em>,
447
- };
448
- exports.tscVersion = ts.version;
449
- <em class="">function buildDiagnostics(program) {
450
- return [
451
- ...program.getConfigFileParsingDiagnostics(),
452
- ...program.getOptionsDiagnostics(),
453
- ...program.getGlobalDiagnostics(),
454
- ...program.getDeclarationDiagnostics(),
455
- ];
456
- }</em>
457
- <em class="">function printDiagnostics(diagnostics, host = diagnosticsHost) {
458
- console.error(ts.formatDiagnosticsWithColorAndContext(diagnostics, host));
459
- throw new Error('Typescript compilation failed');
460
- }</em>
461
- <em class="">function getBuilder(tsconfig = 'tsconfig.json', defaultOptions = { module: ts.ModuleKind.CommonJS }) {
462
- const host = ts.createSolutionBuilderHost(sys);
463
- const options = parseTsConfig(tsconfig);
464
- if (options.errors?.length) {
465
- printDiagnostics(options.errors);
466
- }
467
- const outputDir = options.options.outDir;
468
- if (!outputDir)
469
- throw new Error(`No outDir field set in ${tsconfig}`);
470
- if (options.options.module === ts.ModuleKind.ESNext) {
471
- const oldRead = host.readFile;
472
- host.readFile = (...args) =&gt; {
473
- const src = oldRead.apply(host, args);
474
- return src?.replace(/^\/\/\/.+/, '');
475
- };
476
- }
477
- const builder = ts.createSolutionBuilder(host, [tsconfig], defaultOptions);
478
- return { outputDir, builder, options };
479
- }</em>
480
- <em class="">function tsbuild(tsconfig = 'tsconfig.json', subs, defaultOptions = { module: ts.ModuleKind.CommonJS }, outDir) {
481
- const { options, outputDir, builder } = getBuilder(tsconfig, defaultOptions);
482
- let program;
483
- function writeFile(name, source) {
484
- name = (0, path_1.relative)(outDir || outputDir, name);
485
- const refs = options.projectReferences?.[0];
486
- if (refs?.path.endsWith('/cxl/amd/tsconfig.json') &amp;&amp; refs.prepend) {
487
- source = AMD + source;
488
- }
489
- subs.next({ path: name, source: Buffer.from(source) });
490
- }
491
- while ((program = builder.getNextInvalidatedProject())) {
492
- const status = program.done(undefined, writeFile);
493
- if (status !== ts.ExitStatus.Success)
494
- throw `${program.project}: Typescript compilation failed`;
495
- }
496
- }</em>
497
- <em class="">function tsconfig(tsconfig = 'tsconfig.json', options, outputDir) {
498
- return new rx_1.Observable(subs =&gt; {
499
- tsbuild(tsconfig, subs, options, outputDir);
500
- subs.complete();
501
- });
502
- }</em>
503
- <em class="">function parseTsConfig(tsconfig) {
504
- let parsed;
505
- try {
506
- parsed = ts.getParsedCommandLineOfConfigFile(tsconfig, {}, parseConfigHost);
507
- }
508
- catch (e) {
509
- if (e instanceof Error)
510
- throw e;
511
- const msg = e?.message || e?.messageText || 'Unknown Error';
512
- throw new Error(msg);
513
- }
514
- if (!parsed)
515
- throw new Error(`Could not parse config file "${tsconfig}"`);
516
- return parsed;
517
- }</em>
518
- <em class="">function flagsToString(flags, Flags) {
519
- const result = [];
520
- for (const i in Flags) {
521
- if (Flags[i] &amp; flags)
522
- result.push(i);
523
- }
524
- return result;
525
- }</em>
526
- <em class="">function findImports(src, program, result = new Set()) {
527
- const typeChecker = program.getTypeChecker();
528
- src.forEachChild(node =&gt; {
529
- if ((ts.isImportDeclaration(node) &amp;&amp;
530
- (!node.importClause || !node.importClause.isTypeOnly)) ||
531
- (ts.isExportDeclaration(node) &amp;&amp; !node.isTypeOnly)) {
532
- if (!node.moduleSpecifier)
533
- return;
534
- const symbol = typeChecker.getSymbolAtLocation(node.moduleSpecifier);
535
- const childSourceFile = symbol?.valueDeclaration;
536
- if (childSourceFile &amp;&amp;
537
- ts.isSourceFile(childSourceFile) &amp;&amp;
538
- !childSourceFile.isDeclarationFile &amp;&amp;
539
- !result.has(childSourceFile.fileName)) {
540
- result.add(childSourceFile.fileName);
541
- findImports(childSourceFile, program, result);
542
- }
543
- }
544
- });
545
- return result;
546
- }</em>
547
- <em class="">function bundleFiles(config, amd) {
548
- const host = ts.createCompilerHost(config.options);
549
- const program = ts.createProgram(config.fileNames, config.options, host);
550
- const result = new Set([]);
551
- if (amd)
552
- result.add(__dirname + '/amd.js');
553
- program.getRootFileNames().forEach(file =&gt; {
554
- const src = program.getSourceFile(file);
555
- result.add(file);
556
- if (src)
557
- findImports(src, program, result);
558
- });
559
- return { host, program, result };
560
- }</em>
561
- <em class="">function bundle(tsconfig = 'tsconfig.json', outFile = 'index.bundle.js', amd = false) {
562
- return new rx_1.Observable(subs =&gt; {
563
- var _a, _b;
564
- const config = parseTsConfig(tsconfig);
565
- const { host, result } = bundleFiles(config, amd);
566
- config.options.module = ts.ModuleKind.AMD;
567
- config.options.outFile = outFile;
568
- (_a = config.options).rootDir || (_a.rootDir = (0, path_1.resolve)('../..'));
569
- (_b = config.options).baseDir || (_b.baseDir = process.cwd());
570
- if (amd)
571
- config.options.allowJs = true;
572
- const rootNames = Array.from(result);
573
- const program = ts.createProgram(rootNames, config.options, host);
574
- function writeFile(name, source) {
575
- subs.next({ path: name, source: Buffer.from(source) });
576
- }
577
- const diagnostics = buildDiagnostics(program);
578
- if (diagnostics.length) {
579
- printDiagnostics(diagnostics, host);
580
- return subs.error('Failed to compile');
581
- }
582
- program
583
- .getSourceFiles()
584
- .forEach(src =&gt; (src.isDeclarationFile = !rootNames.includes(src.fileName)));
585
- program.emit(undefined, writeFile);
586
- subs.complete();
587
- });
588
- }</em>
589
- </em></pre><h2><a name="package.js">package.js</a></h2><pre><em class="covered">"use strict";
590
- Object.defineProperty(exports, "__esModule", { value: true });
591
- exports.REQUIRE_REPLACE = exports.BASEDIR = void 0;
592
- exports.readPackage = readPackage;
593
- exports.docs = docs;
594
- exports.docgen = docgen;
595
- exports.docgenTask = docgenTask;
596
- exports.readme = readme;
597
- exports.pkg = pkg;
598
- exports.AMD = AMD;
599
- exports.bundle = bundle;
600
- exports.bundleAmd = bundleAmd;
601
- exports.template = template;
602
- exports.deployS3 = deployS3;
603
- const rx_1 = require("@cxl/rx");
604
- const fs_1 = require("fs");
605
- const path_1 = require("path");
606
- const file_js_1 = require("./file.js");
607
- const child_process_1 = require("child_process");
608
- const program_1 = require("@cxl/program");
609
- const builder_js_1 = require("./builder.js");
610
- const npm_js_1 = require("./npm.js");
611
- const ts = require("typescript");
612
- const SCRIPTDIR = process.cwd();
613
- exports.BASEDIR = (0, child_process_1.execSync)(`npm prefix`, { cwd: SCRIPTDIR })
614
- .toString()
615
- .trim();
616
- const LICENSE_MAP = {
617
- 'GPL-3.0': 'license-GPL-3.0.txt',
618
- 'GPL-3.0-only': 'license-GPL-3.0.txt',
619
- 'Apache-2.0': 'license-Apache-2.0.txt',
620
- 'SEE LICENSE IN LICENSE.txt': '',
621
- UNLICENSED: '',
622
- };
623
- <em class="">function verifyFields(fields, pkg) {
624
- for (const f of fields)
625
- if (!pkg[f])
626
- throw new Error(`Field "${f}" missing in package.json`);
627
- }</em>
628
- <em class="">function readPackage(base = exports.BASEDIR) {
629
- const pkg = base + '/package.json';
630
- if (!(0, fs_1.existsSync)(pkg))
631
- throw new Error('package.json not found');
632
- const PACKAGE = JSON.parse((0, fs_1.readFileSync)(pkg, 'utf8'));
633
- verifyFields(['name', 'version', 'description'], PACKAGE);
634
- if (!PACKAGE.private)
635
- verifyFields(['license'], PACKAGE);
636
- return PACKAGE;
637
- }</em>
638
- <em class="">function docs(dirName, devMode = false) {
639
- const docgen = (0, path_1.join)(__dirname, '../docgen');
640
- return new rx_1.Observable(subs =&gt; {
641
- const cmd = `node ${docgen} --clean ${devMode ? '--debug' : ''} -o ../docs/${dirName} --summary --markdown --cxlExtensions`;
642
- console.log(cmd);
643
- (0, program_1.sh)(cmd).then(out =&gt; (console.log(out), subs.complete()), e =&gt; subs.error(e));
644
- });
645
- }</em>
646
- <em class="">async function docgen(options) {
647
- const { name, tag, repo, file, setup, npm, tmpDir, typeRoots, scripts, sitemapBase, packageJson, docsJson, forceInstall, baseHref, rootDir, customJsDocTags, exports, summary, followReferences, cxlExtensions, headHtml, } = options;
648
- const repodir = options.repodir ||
649
- `${name.replace('/', '--')}-${tag.replace('/', '--')}`;
650
- const dir = (0, path_1.join)(tmpDir || '', repodir, npm ? `/node_modules/${npm}` : ``);
651
- const cwd = (0, path_1.join)(dir, options.cwd || '');
652
- const outDir = (0, path_1.resolve)(options.outDir || 'docs');
653
- const files = Array.isArray(file)
654
- ? file.map(f =&gt; `--file ${f}`).join(' ')
655
- : `--tsconfig ${file}`;
656
- const pkg = (0, path_1.join)(cwd, packageJson || 'package.json');
657
- const install = repo
658
- ? `git clone ${repo} --branch=${tag} --depth=1 ${repodir};
659
- cd ${repodir} ${setup ? `&amp;&amp; ${setup}` : ''}`
660
- : `mkdir -p ${repodir} &amp;&amp; npm install --prefix ./${repodir} ${npm}@${tag}`;
661
- const DOCGEN = (0, path_1.join)(__dirname, '../docgen');
662
- if (forceInstall)
663
- await (0, program_1.sh)(`mkdir -p ${tmpDir} &amp;&amp; cd ${tmpDir} &amp;&amp; rm -rf ${repodir} &amp;&amp; ${install}`);
664
- else
665
- await (0, program_1.sh)(`if [ ! -d "${dir}" ]; then
666
- mkdir -p ${tmpDir} &amp;&amp; cd ${tmpDir}
667
- ${install}
668
- fi`);
669
- const { description, version } = await (0, npm_js_1.readPackage)(pkg);
670
- const sitemap = `${sitemapBase}/${name}/${version}/sitemap.xml`;
671
- const outputDir = (0, path_1.join)(outDir, name);
672
- console.log(cwd);
673
- await (0, builder_js_1.run)(`node ${DOCGEN} ${files}`, {
674
- packageJson,
675
- docsJson,
676
- scripts,
677
- outputDir,
678
- sitemap: sitemapBase ? `${sitemapBase}/${name}` : '',
679
- summary: summary ?? true,
680
- typeRoots,
681
- packageName: name,
682
- repository: repo?.startsWith('https')
683
- ? `${repo.replace(/.git$/, '')}/blob/${tag}${options.cwd ? `/${options.cwd}` : ''}`
684
- : undefined,
685
- markdown: true,
686
- baseHref,
687
- customJsDocTags,
688
- rootDir,
689
- exports,
690
- followReferences,
691
- cxlExtensions,
692
- headHtml,
693
- }, { cwd });
694
- return { name, version, description, sitemap };
695
- }</em>
696
- <em class="">function docgenTask(packages, commonOptions) {
697
- return (0, rx_1.fromAsync)(async () =&gt; {
698
- const output = [];
699
- for (const p of packages)
700
- output.push(await docgen({
701
- ...commonOptions,
702
- ...p,
703
- }));
704
- return {
705
- path: 'docgen.json',
706
- source: Buffer.from(JSON.stringify(output)),
707
- };
708
- });
709
- }</em>
710
- <em class="">function packageJson(p) {
711
- return (0, rx_1.of)({
712
- path: 'package.json',
713
- source: Buffer.from(JSON.stringify({
714
- name: p.name,
715
- version: p.version,
716
- description: p.description,
717
- private: p.private,
718
- license: p.license,
719
- files: p.files || [
720
- '*.js',
721
- '*.d.ts',
722
- '*.css',
723
- 'amd/*.js',
724
- 'amd/*.d.ts',
725
- 'mjs/*.js',
726
- 'mjs/*.d.ts',
727
- 'LICENSE',
728
- '*.md',
729
- ],
730
- main: p.main || 'index.js',
731
- exports: p.exports,
732
- browser: p.browser,
733
- homepage: p.homepage,
734
- bugs: p.bugs,
735
- bin: p.bin,
736
- repository: p.repository,
737
- dependencies: p.dependencies,
738
- peerDependencies: p.peerDependencies,
739
- bundledDependencies: p.bundledDependencies,
740
- type: p.type,
741
- }, null, 2)),
742
- });
743
- }</em>
744
- <em class="">function license(id) {
745
- if (id === 'UNLICENSED' || id === 'SEE LICENSE IN LICENSE.txt')
746
- return rx_1.EMPTY;
747
- const licenseFile = LICENSE_MAP[id];
748
- if (!licenseFile)
749
- throw new Error(`Invalid license: "${id}"`);
750
- return (0, file_js_1.file)((0, path_1.join)(__dirname, licenseFile), 'LICENSE');
751
- }</em>
752
- <em class="">function npmLink(pkgName, version) {
753
- return `https://npmjs.com/package/${pkgName}/v/${version}`;
754
- }</em>
755
- <em class="">function readIfExists(file) {
756
- try {
757
- return (0, fs_1.readFileSync)(file, 'utf8');
758
- }
759
- catch (E) {
760
- return '';
761
- }
762
- }</em>
763
- /**
764
- * Generate README file
765
- */
766
- <em class="">function readme() {
767
- return (0, rx_1.defer)(() =&gt; {
768
- const pkg = readPackage(exports.BASEDIR);
769
- const extra = readIfExists('USAGE.md');
770
- const encodedName = encodeURIComponent(pkg.name);
771
- return (0, rx_1.of)({
772
- path: 'README.md',
773
- source: Buffer.from(`# ${pkg.name}
774
-
775
- [![npm version](https://badge.fury.io/js/${encodedName}.svg)](https://badge.fury.io/js/${encodedName})
776
-
777
- ${pkg.description}
778
-
779
- ## Project Details
780
-
781
- - Branch Version: [${pkg.version}](${npmLink(pkg.name, pkg.version)})
782
- - License: ${pkg.license}
783
- - Documentation: [Link](${pkg.homepage})
784
- - Report Issues: [Github](${pkg.bugs})
785
-
786
- ## Installation
787
-
788
- npm install ${pkg.name}
789
-
790
- ${extra}`),
791
- });
792
- });
793
- }</em>
794
- <em class="">function pkg() {
795
- return (0, rx_1.defer)(() =&gt; {
796
- const p = readPackage();
797
- const licenseId = p.license;
798
- const output = [packageJson(p)];
799
- output.push((0, file_js_1.file)('README.md', 'README.md'));
800
- if (licenseId)
801
- output.push(license(licenseId));
802
- return (0, rx_1.merge)(...output);
803
- });
804
- }</em>
805
- <em class="">function createBundle(files, resolvedFiles, content, outFile, config) {
806
- const options = {
807
- lib: ['lib.es2017.d.ts'],
808
- target: ts.ScriptTarget.ES2019,
809
- module: ts.ModuleKind.AMD,
810
- allowJs: true,
811
- declaration: false,
812
- baseUrl: process.cwd(),
813
- outDir: process.cwd(),
814
- outFile: outFile,
815
- removeComments: true,
816
- isolatedModules: true,
817
- moduleResolution: ts.ModuleResolutionKind.NodeJs,
818
- sourceMap: false,
819
- ...config,
820
- };
821
- const host = ts.createCompilerHost(options);
822
- const oldGetSourceFile = host.getSourceFile;
823
- const sourceFiles = [];
824
- host.getSourceFile = function (fn, target) {
825
- const i = resolvedFiles.indexOf(fn);
826
- if (i !== -1) {
827
- const sf = ts.createSourceFile(resolvedFiles[i], content[i], target);
828
- sf.moduleName = files[i];
829
- sourceFiles.push(sf);
830
- return sf;
831
- }
832
- return oldGetSourceFile.apply(this, arguments);
833
- };
834
- const program = ts.createProgram(resolvedFiles, options, host);
835
- let source = '';
836
- program.emit(undefined, (_a, b) =&gt; (source += b));
837
- return {
838
- path: outFile,
839
- source: Buffer.from(source),
840
- };
841
- }</em>
842
- <em class="">function AMD() {
843
- return (0, rx_1.defer)(() =&gt; (0, rx_1.of)({
844
- path: 'amd.js',
845
- source: (0, fs_1.readFileSync)(__dirname + '/amd.js'),
846
- }));
847
- }</em>
848
- <em class="">function bundle(files, outFile, config) {
849
- return new rx_1.Observable(subs =&gt; {
850
- const moduleNames = Object.keys(files);
851
- const resolvedFiles = Object.values(files);
852
- Promise.all(resolvedFiles.map(f =&gt; fs_1.promises.readFile(f, 'utf8')))
853
- .then(content =&gt; {
854
- subs.next(createBundle(moduleNames, resolvedFiles, content, outFile, config));
855
- subs.complete();
856
- })
857
- .catch(e =&gt; subs.error(e));
858
- });
859
- }</em>
860
- <em class="">function bundleAmd(files, outFile) {
861
- return new rx_1.Observable(subs =&gt; {
862
- const result = [];
863
- const moduleNames = Object.keys(files);
864
- const resolvedFiles = Object.values(files);
865
- Promise.all(resolvedFiles.map(f =&gt; fs_1.promises.readFile(f, 'utf8'))).then(content =&gt; {
866
- moduleNames.forEach((mod, i) =&gt; {
867
- result.push(`define("${mod}", ["require", "exports"], function (require, exports) {\n${content[i]}\n})`);
868
- });
869
- subs.next({
870
- path: outFile,
871
- source: Buffer.from(result.join('\n')),
872
- });
873
- });
874
- });
875
- }</em>
876
- exports.REQUIRE_REPLACE = `
877
- require.replace = function (path) {
878
- return path.replace(
879
- /^@cxl\\/workspace\\.(.+)/,
880
- (str, p1) =&gt;
881
- \`/cxl.app/dist/\${str.endsWith('.js') ? p1 : p1 + '/index.js'}\`
882
- ).replace(
883
- /^@cxl\\/(ui.*)/,
884
- (str, p1) =&gt;
885
- \`/ui/dist/\${str.endsWith('.js') ? p1 : p1 + '/index.js'}\`
886
- ).replace(
887
- /^@cxl\\/(.+)/,
888
- (str, p1) =&gt;
889
- \`/cxl/dist/\${str.endsWith('.js') ? p1 : p1 + '/index.js'}\`
890
- );
891
- };
892
- `;
893
- const INDEX_HEAD = `&lt;!DOCTYPE html&gt;&lt;meta charset="utf-8"&gt;&lt;script src="index.bundle.min.js"&gt;&lt;/script&gt;`;
894
- const DEBUG_HEAD = `&lt;!DOCTYPE html&gt;&lt;meta charset="utf-8"&gt;
895
- &lt;script src="/cxl/dist/tester/require-browser.js"&gt;&lt;/script&gt;
896
- &lt;script&gt;
897
- window.CXL_DEBUG = true;
898
- ${exports.REQUIRE_REPLACE}
899
- require('@cxl/ui');
900
- require('@cxl/ui-router');
901
- require('@cxl/router/debug.js');
902
- &lt;/script&gt;
903
- `;
904
- const DefaultTemplateConfig = {
905
- header: INDEX_HEAD,
906
- debugHeader: DEBUG_HEAD,
907
- };
908
- const HTML_COMMENT_REGEX = /&lt;!--[^]+?--&gt;/gm;
909
- <em class="">function template(filename, config = {}) {
910
- return (0, file_js_1.file)(filename).switchMap(({ source }) =&gt; {
911
- const prodSource = source
912
- .toString('utf8')
913
- .replace(HTML_COMMENT_REGEX, '');
914
- const cfg = { ...DefaultTemplateConfig, ...config };
915
- return (0, rx_1.from)([
916
- { path: 'index.html', source: `${cfg.header}\n${prodSource}` },
917
- { path: 'debug.html', source: `${cfg.debugHeader}\n${source}` },
918
- ]);
919
- });
920
- }</em>
921
- <em class="">function deployS3({ environment, s3Path }) {
922
- if (environment !== 'dev' &amp;&amp; environment !== 'prod')
923
- throw new Error(`Invalid environment ${environment}`);
924
- return (0, builder_js_1.exec)(`aws s3 sync --dryrun --cache-control max-age=60 --content-encoding=utf8 --delete ../dist/debuggerjs.com s3://${s3Path}`);
925
- }</em>
926
- </em></pre><h2><a name="file.js">file.js</a></h2><pre><em class="covered">"use strict";
927
- Object.defineProperty(exports, "__esModule", { value: true });
928
- exports.MinifyDefault = void 0;
929
- exports.ls = ls;
930
- exports.read = read;
931
- exports.filterPath = filterPath;
932
- exports.file = file;
933
- exports.basename = basename;
934
- exports.concatFile = concatFile;
935
- exports.files = files;
936
- exports.matchStat = matchStat;
937
- exports.copyDir = copyDir;
938
- exports.getSourceMap = getSourceMap;
939
- exports.minify = minify;
940
- exports.minifyDir = minifyDir;
941
- exports.zip = zip;
942
- const Terser = require("terser");
943
- const rx_1 = require("@cxl/rx");
944
- const fs_1 = require("fs");
945
- const path_1 = require("path");
946
- const builder_js_1 = require("./builder.js");
947
- <em class="">function ls(dir) {
948
- return new rx_1.Observable(async (subs) =&gt; {
949
- const files = await fs_1.promises.readdir(dir);
950
- for (const path of files)
951
- subs.next((0, path_1.resolve)(dir, path));
952
- subs.complete();
953
- });
954
- }</em>
955
- <em class="">async function read(source) {
956
- const content = await fs_1.promises.readFile(source);
957
- return {
958
- path: source,
959
- source: content,
960
- };
961
- }</em>
962
- <em class="">function filterPath(matchPath) {
963
- matchPath = (0, path_1.resolve)(matchPath);
964
- return (0, rx_1.filter)((out) =&gt; (0, path_1.resolve)(out.path).startsWith(matchPath));
965
- }</em>
966
- <em class="">function file(source, out) {
967
- return (0, rx_1.defer)(() =&gt; (0, rx_1.from)(read(source).then(res =&gt; ({
968
- path: out || (0, path_1.resolve)(source),
969
- source: res.source,
970
- }))));
971
- }</em>
972
- <em class="">function basename(replace) {
973
- return (0, rx_1.tap)(out =&gt; (out.path = (replace || '') + (0, path_1.basename)(out.path)));
974
- }</em>
975
- /*export function prepend(src: string) {
976
- return tap(out =&gt; out.source = Buffer.from(src + out.source.toString('utf8')));
977
- }*/
978
- <em class="">function concatFile(outName, separator = '\n') {
979
- return (0, rx_1.pipe)((0, rx_1.reduce)((out, src) =&gt; `${out}${separator}${src.source}`, ''), (0, rx_1.map)(source =&gt; ({ path: outName, source: Buffer.from(source) })));
980
- }</em>
981
- /**
982
- * Reads multiple files asynchronously and emits them in order
983
- */
984
- <em class="">function files(sources) {
985
- return new rx_1.Observable(subs =&gt; {
986
- Promise.all(sources.map(read)).then(out =&gt; {
987
- out.forEach(o =&gt; subs.next(o));
988
- subs.complete();
989
- }, e =&gt; subs.error(e));
990
- });
991
- }</em>
992
- <em class="">function matchStat(fromPath, toPath) {
993
- return Promise.all([fs_1.promises.stat(fromPath), fs_1.promises.stat(toPath)]).then(([fromStat, toStat]) =&gt; fromStat.mtime.getTime() === toStat.mtime.getTime(), () =&gt; true);
994
- }</em>
995
- /**
996
- * Copy Directory
997
- */
998
- <em class="">function copyDir(fromPath, toPath, glob = '*') {
999
- return (0, builder_js_1.exec)(`mkdir -p ${toPath} &amp;&amp; rsync -au -i --delete ${fromPath}/${glob} ${toPath}`);
1000
- }</em>
1001
- <em class="">function getSourceMap(out) {
1002
- const source = out.source.toString();
1003
- const match = /\/\/# sourceMappingURL=(.+)/.exec(source);
1004
- const path = match ? (0, path_1.resolve)((0, path_1.dirname)(out.path), match?.[1]) : null;
1005
- if (path)
1006
- return { path: (0, path_1.basename)(path), source: (0, fs_1.readFileSync)(path) };
1007
- }</em>
1008
- exports.MinifyDefault = {
1009
- ecma: 2020,
1010
- };
1011
- <em class="">function minify(op) {
1012
- return (0, rx_1.mergeMap)(out =&gt; {
1013
- const config = { ...exports.MinifyDefault, ...op };
1014
- // Bypass if not a JS file
1015
- if (!out.path.endsWith('.js'))
1016
- return (0, rx_1.of)(out);
1017
- const destPath = op?.changePath === false
1018
- ? out.path
1019
- : out.path.replace(/\.js$/, '.min.js');
1020
- if (config.sourceMap === undefined) {
1021
- const sourceMap = getSourceMap(out);
1022
- if (sourceMap)
1023
- config.sourceMap = {
1024
- content: sourceMap.source.toString(),
1025
- url: destPath + '.map',
1026
- };
1027
- }
1028
- const source = out.source.toString();
1029
- delete config.changePath;
1030
- return new rx_1.Observable(async (subscriber) =&gt; {
1031
- try {
1032
- const { code, map } = await Terser.minify({ [out.path]: source }, config);
1033
- if (!code)
1034
- throw new Error('No code generated');
1035
- subscriber.next({
1036
- path: destPath,
1037
- source: Buffer.from(code),
1038
- });
1039
- if (map &amp;&amp; config.sourceMap)
1040
- subscriber.next({
1041
- path: config.sourceMap.url,
1042
- source: Buffer.from(map.toString()),
1043
- });
1044
- }
1045
- catch (e) {
1046
- console.error(`Error minifying ${out.path}`);
1047
- throw e;
1048
- }
1049
- subscriber.complete();
1050
- });
1051
- });
1052
- }</em>
1053
- <em class="">function minifyDir(dir, op) {
1054
- return ls(dir)
1055
- .filter(path =&gt; path.endsWith('.js'))
1056
- .mergeMap(file)
1057
- .pipe(minify(op));
1058
- }</em>
1059
- <em class="">function zip(src, path) {
1060
- return (0, builder_js_1.shell)(`zip - ${src.join(' ')}`).map(source =&gt; ({ path, source }));
1061
- }</em>
1062
- </em></pre><h2><a name="npm.js">npm.js</a></h2><pre><em class="covered">"use strict";
1063
- Object.defineProperty(exports, "__esModule", { value: true });
1064
- exports.readPackage = readPackage;
1065
- exports.getLatestVersion = getLatestVersion;
1066
- exports.isPackageVersionPublished = isPackageVersionPublished;
1067
- exports.testPackage = testPackage;
1068
- exports.publishNpm = publishNpm;
1069
- exports.getPackageInfo = getPackageInfo;
1070
- const program_1 = require("@cxl/program");
1071
- const promises_1 = require("fs/promises");
1072
- const git_js_1 = require("./git.js");
1073
- const path_1 = require("path");
1074
- <em class="">async function readPackage(path) {
1075
- return JSON.parse(await (0, promises_1.readFile)(path, 'utf8'));
1076
- }</em>
1077
- <em class="">async function getLatestVersion(packageName, tag = 'latest') {
1078
- const info = await getPackageInfo(packageName);
1079
- return info?.['dist-tags'][tag] || undefined;
1080
- }</em>
1081
- <em class="">async function isPackageVersionPublished(packageName, version) {
1082
- const info = await getPackageInfo(packageName);
1083
- return info.versions.includes(version);
1084
- }</em>
1085
- <em class="">async function testPackage(dir) {
1086
- const cwd = (0, path_1.resolve)(`dist/${dir}`);
1087
- if (!cwd.startsWith(process.cwd()))
1088
- throw `"${cwd}" should be under current working directory`;
1089
- await (0, program_1.sh)(`npm install --production`, { cwd });
1090
- try {
1091
- await (0, program_1.sh)(`npm test`, { cwd: dir });
1092
- }
1093
- finally {
1094
- await (0, program_1.sh)(`rm -rf ${cwd}/node_modules package-lock.json`);
1095
- }
1096
- }</em>
1097
- <em class="">async function publishNpm(dir) {
1098
- const branch = await (0, git_js_1.getBranch)(process.cwd());
1099
- if (branch !== 'master')
1100
- throw `Active branch "${branch}" is not master`;
1101
- const pkg = await readPackage(`${dir}/package.json`);
1102
- await (0, git_js_1.checkBranchClean)('master');
1103
- const info = await getPackageInfo(pkg.name);
1104
- if (info.versions.includes(pkg.version)) {
1105
- console.log(`Package "${pkg.name}" version "${pkg.version}" already published. Skipping.`);
1106
- }
1107
- else {
1108
- console.log(`Building ${pkg.name} ${pkg.version}`);
1109
- await (0, program_1.sh)(`npm run build package --prefix ${dir}`);
1110
- await testPackage(dir);
1111
- const distDir = `dist/${dir}`;
1112
- const tag = pkg.version.includes('beta') ? 'beta' : 'latest';
1113
- const removeVersion = tag === 'beta' ? info['dist-tags'].beta : undefined;
1114
- console.log(await (0, program_1.sh)(`npm publish --access=public --tag ${tag}`, {
1115
- cwd: distDir,
1116
- }));
1117
- if (tag === 'beta') {
1118
- const baseTag = `${pkg.version.split('.')[0]}-beta`;
1119
- console.log(await (0, program_1.sh)(`npm dist-tag add ${pkg.name}@${pkg.version} ${baseTag}`));
1120
- }
1121
- if (removeVersion)
1122
- console.log(await (0, program_1.sh)(`npm unpublish ${pkg.name}@${removeVersion}`));
1123
- }
1124
- // Create Release Tag if it doesn't exist already
1125
- const gitTag = `${dir}/${pkg.version}`;
1126
- if (!(await (0, program_1.sh)(`git tag -l ${gitTag}`)).trim()) {
1127
- console.log(`Creating tag "${gitTag}"`);
1128
- await (0, program_1.sh)(`git tag ${gitTag} &amp;&amp; git push origin ${gitTag}`);
1129
- }
1130
- }</em>
1131
- <em class="">async function getPackageInfo(name) {
1132
- return JSON.parse((await (0, program_1.sh)(`npm show ${name} --json`)).trim());
1133
- }</em>
1134
- </em></pre><h2><a name="git.js">git.js</a></h2><pre><em class="covered">"use strict";
1135
- Object.defineProperty(exports, "__esModule", { value: true });
1136
- exports.getBranch = getBranch;
1137
- exports.checkBranchClean = checkBranchClean;
1138
- exports.checkBranchUpToDate = checkBranchUpToDate;
1139
- const program_1 = require("@cxl/program");
1140
- <em class="">async function getBranch(cwd) {
1141
- return (await (0, program_1.sh)('git rev-parse --abbrev-ref HEAD', { cwd })).trim();
1142
- }</em>
1143
- <em class="">async function checkBranchClean(branch) {
1144
- try {
1145
- await (0, program_1.sh)(`git status &gt; /dev/null; git diff-index --quiet ${branch}`);
1146
- }
1147
- catch (e) {
1148
- throw new Error('Not a clean repository');
1149
- }
1150
- }</em>
1151
- <em class="">async function checkBranchUpToDate(branch = 'master') {
1152
- try {
1153
- await (0, program_1.sh)(`git diff origin/${branch} ${branch} --quiet`);
1154
- }
1155
- catch (e) {
1156
- throw new Error('Branch has not been merged with origin');
1157
- }
1158
- }</em>
1159
- </em></pre><h2><a name="lint.js">lint.js</a></h2><pre><em class="covered">"use strict";
1160
- Object.defineProperty(exports, "__esModule", { value: true });
1161
- exports.eslint = eslint;
1162
- const path_1 = require("path");
1163
- const rx_1 = require("@cxl/rx");
1164
- const builder_js_1 = require("./builder.js");
1165
- <em class="">function handleEslintResult(results) {
1166
- const result = [];
1167
- let hasErrors = false;
1168
- results.forEach(result =&gt; {
1169
- const errorCount = result.errorCount;
1170
- const file = (0, path_1.relative)(process.cwd(), result.filePath);
1171
- (0, builder_js_1.appLog)(`eslint ${file}`);
1172
- if (errorCount) {
1173
- hasErrors = true;
1174
- result.messages.forEach(r =&gt; console.error(`${file}#${r.line}:${r.column}: ${r.message} (${r.ruleId})`));
1175
- }
1176
- });
1177
- if (hasErrors)
1178
- throw new Error('eslint errors found.');
1179
- return result;
1180
- }</em>
1181
- <em class="">function eslint(options) {
1182
- return new rx_1.Observable(subs =&gt; {
1183
- const eslintPath = require.resolve('eslint', {
1184
- paths: [process.cwd(), __dirname],
1185
- });
1186
- const { ESLint } = require(eslintPath);
1187
- (0, builder_js_1.appLog)(`eslint ${ESLint.version} (${eslintPath})`);
1188
- const linter = new ESLint({
1189
- cache: true,
1190
- cwd: process.cwd(),
1191
- // fix: true,
1192
- ...options,
1193
- });
1194
- linter
1195
- .lintFiles(['**/*.ts?(x)'])
1196
- .then(handleEslintResult)
1197
- .then(() =&gt; subs.complete(), e =&gt; subs.error(e));
1198
- });
1199
- }</em>
1200
- </em></pre>