-
-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathbuild.ts
More file actions
1121 lines (908 loc) · 34.3 KB
/
Copy pathbuild.ts
File metadata and controls
1121 lines (908 loc) · 34.3 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
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
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { debounce } from '@std/async/debounce';
import { encodeBase64Url } from '@std/encoding/base64url';
import { parseArgs } from '@std/cli/parse-args';
import { mapValues } from '@std/collections/map-values';
import * as path from '@std/path';
import esbuild from 'esbuild';
type Awaitable<T> = T | PromiseLike<T>;
type Timer = ReturnType<typeof setTimeout>;
/** Asserts (like a cast) that an array contains no `null` elements. */
// XXX: Arrays are covariant on their element types in TypeScript, so this will accept a T[] where null is not a member of T.
const asNoNulls = <T>(arr: (T | null)[]): T[] => arr as T[];
interface TaskResult {
/** Inputs that can change the output of this task (not always comprehensive, but good enough for watch mode). */
readonly inputs: readonly Source[];
/** Key/value pairs to be written to manifest.json, mapping asset ids to hash-suffixed output file paths. */
readonly entries: readonly (readonly [string, string])[];
/** Any further build work that wasn’t required in order to compute {@link entries}. */
readonly work: Promise<unknown>;
readonly cache?: TaskCache | null;
}
interface TaskResultWithCache<Cache extends TaskCache> extends TaskResult {
readonly cache: Cache | null;
}
interface TaskResultWithInputMap extends TaskResult {
readonly inputsByEntry: Map<string, readonly Source[]>;
}
interface TaskCache {
dispose(): void;
}
class PackageSource {
readonly package: string;
constructor(
package_: string,
readonly path: string,
) {
this.package = package_;
}
}
class AbsoluteSource {
constructor(readonly path: string) {}
}
type RelativeSource = string;
type Source =
| RelativeSource
| PackageSource
| AbsoluteSource;
class Context {
readonly absoluteAssetsRoot: string;
#cssWorker: Worker;
#cssWorkerNextMessageId = 1;
#cssWorkerRequests = new Map<number, (data: object) => void>();
constructor(
readonly verbose: boolean,
readonly assetsRoot: string,
readonly outputRoot: string,
) {
this.absoluteAssetsRoot = path.resolve(assetsRoot);
const cssWorker = new Worker(new URL('./build-css.ts', import.meta.url), {
name: 'CSS worker',
type: 'module',
deno: {
permissions: {
env: [
'CI',
'SASS_PATH',
'BROWSERSLIST_DISABLE_CACHE',
'BROWSERSLIST_IGNORE_OLD_DATA',
'AUTOPREFIXER_GRID',
],
read: [assetsRoot],
},
},
});
cssWorker.onerror = cssWorker.onmessageerror = onCssWorkerFatal;
cssWorker.onmessage = (e: MessageEvent<{messageId?: unknown} | null | undefined>) => {
const resolve = mapPop(this.#cssWorkerRequests, e.data?.messageId);
if (resolve !== undefined) {
resolve(e.data as object);
return;
}
console.error('bad message from CSS worker: %o', e.data);
throw new TypeError('bad message from CSS worker');
};
// XXX: There appears to be no way (as of Deno 2.8) to handle a worker `close`ing itself. Messages will just be silently dropped.
this.#cssWorker = cssWorker;
}
resolveSource(source: Source) {
if (typeof source === 'string') {
return path.join(this.assetsRoot, source);
}
if (source instanceof AbsoluteSource) {
return source.path;
}
if (import.meta.dirname === undefined) {
throw new Error();
}
return path.join(import.meta.dirname, 'node_modules', source.package, source.path);
}
resolveOutput(output: string) {
return path.join(this.outputRoot, output);
}
sendCssWork(request: CssRequestData): Promise<object> {
const messageId = this.#cssWorkerNextMessageId++;
const {promise, resolve} = Promise.withResolvers<object>();
this.#cssWorkerRequests.set(messageId, resolve);
this.#cssWorker.postMessage({...request, messageId} satisfies CssRequest);
return promise;
}
[Symbol.dispose]() {
this.#cssWorker.terminate();
}
}
const onCssWorkerFatal = () => {
// Uncaught errors are already logged by the runtime, and `messageerror` should never happen, so we don't bother with more detailed logging.
throw new Error('fatal event from CSS worker');
};
// deno-lint-ignore ban-types
type NotUndefined = {} | null;
const mapPop = <K, V extends NotUndefined>(map: Map<K, V>, key: K): V | undefined => {
const value = map.get(key);
if (value === undefined) {
return undefined;
}
map.delete(key);
return value;
};
interface CssRequestData {
resolvedSource: string;
}
export interface CssRequest extends CssRequestData {
messageId: number;
}
export interface CssResponse {
messageId: number;
css: string;
loadedUrls: string[];
warnings: string[];
}
/** Indicates that error information was already written to stderr. */
const $hasStderr = Symbol('hasStderr');
interface CanHaveStderr {
readonly [$hasStderr]: boolean;
}
const hasStderr = (error: unknown): boolean =>
error != null
&& Boolean((error as {[$hasStderr]?: boolean})[$hasStderr]);
/**
* Gets a 10-character digest from a SHA-512 digest buffer using characters from the URL-safe base64 set.
*/
const getShortDigest = (digest: Uint8Array): string => {
if (digest.length < 8) {
throw new RangeError('Digest too short');
}
return encodeBase64Url(digest)
.substring(0, 10);
};
const addFilenameSuffix = (relativePath: string, suffix: string): string => {
const pathInfo = path.parse(relativePath);
return path.format({
dir: pathInfo.dir,
name: pathInfo.name + '-' + suffix,
ext: pathInfo.ext,
});
};
const tryRemovePrefix = (s: string, prefix: string): string | null =>
s.startsWith(prefix)
? s.substring(prefix.length)
: null;
const removePrefix = (s: string, prefix: string): string => {
const r = tryRemovePrefix(s, prefix);
if (r === null) {
throw new Error('String didn’t start with expected prefix');
}
return r;
};
declare global {
interface PromiseConstructor {
// XXX: simplified while waiting for this to work out of the box
try<T>(action: () => T | PromiseLike<T>): Promise<Awaited<T>>;
}
}
/** Prevents an idempotent async action from running multiple times concurrently, queuing one run as necessary. */
class LimitOne {
#action: () => Promise<void>;
#running = false;
#waiting: PromiseWithResolvers<void> = Promise.withResolvers();
constructor(action: () => Promise<void>) {
this.#action = action;
}
get running(): boolean {
return this.#running;
}
run = (): Promise<void> => {
if (this.#running) {
return this.#waiting.promise;
}
const oldWaiting = this.#waiting;
this.#waiting = Promise.withResolvers();
this.#running = true;
oldWaiting.resolve(Promise.try(this.#action).finally(() => {
this.#running = false;
}));
return oldWaiting.promise;
};
}
interface SourceOutputPair<T = Source> {
readonly from: T;
readonly to: string;
}
type SourceOutputSame = string;
type SourceOutputSpec<T = Source> = SourceOutputSame | SourceOutputPair<T>;
const expandSpec = <T>(spec: SourceOutputSpec<T>): SourceOutputPair<T | string> =>
typeof spec === 'string'
? {
from: spec,
to: spec,
}
: spec;
type AnyDependencies = Readonly<Record<string, TaskResult>>;
type AnyTask<Result extends TaskResult = TaskResult> = Task<AnyDependencies, Result, TaskCache | undefined>;
interface Task<
Dependencies extends AnyDependencies,
Result extends TaskResult = TaskResult,
Cache extends TaskCache | undefined = undefined,
> {
readonly dependencies: {readonly [k in keyof Dependencies]: AnyTask<Dependencies[k]>};
run(
ctx: Context,
deps: {readonly [k in keyof Dependencies]: Promise<Dependencies[k]>},
cache: Cache | null,
): Awaitable<
undefined extends Cache
? Result
: TaskResultWithCache<Exclude<Cache, undefined>> & Result
>;
}
type Dependencies<T> = T extends Task<infer U> ? U : never;
type Providers<D extends AnyDependencies> = {readonly [k in keyof D]: AnyTask<D[k]>};
type Provided<D extends AnyDependencies> = {readonly [k in keyof D]: Promise<D[k]>};
type Touch = {touch: TaskResult};
class CopyUnversionedStaticFile implements Task<Touch> {
readonly #spec: SourceOutputPair;
constructor(
spec: SourceOutputSpec,
readonly dependencies: Providers<Touch>,
) {
this.#spec = expandSpec(spec);
}
run(ctx: Context, deps: Provided<Touch>): TaskResult {
const outputFullPath = ctx.resolveOutput(this.#spec.to);
return {
inputs: [this.#spec.from],
entries: [],
work: deps.touch.then(() =>
Deno.copyFile(ctx.resolveSource(this.#spec.from), outputFullPath)),
};
}
}
const shortHash = async (data: Uint8Array<ArrayBuffer>) =>
getShortDigest(new Uint8Array(await crypto.subtle.digest('SHA-512', data)));
class CopyStaticFile implements Task<Touch> {
readonly #file: SourceOutputPair;
constructor(
file: SourceOutputSpec,
readonly dependencies: Providers<Touch>,
) {
this.#file = expandSpec(file);
}
async run(ctx: Context, deps: Provided<Touch>): Promise<TaskResult> {
const tempPath = await Deno.makeTempFile({dir: ctx.outputRoot});
const cleanup = async () => {
try {
await Deno.remove(tempPath);
} catch (removeError) {
if (!(removeError instanceof Deno.errors.NotFound)) {
console.error('Failed to remove temporary file: %o', removeError);
}
}
};
try {
await Deno.copyFile(ctx.resolveSource(this.#file.from), tempPath);
const shortDigest = await Deno.readFile(tempPath).then(shortHash);
const suffixedOutputPath = addFilenameSuffix(this.#file.to, shortDigest);
const outputFullPath = ctx.resolveOutput(suffixedOutputPath);
return {
inputs: [this.#file.from],
entries: [[this.#file.to, suffixedOutputPath]],
work: deps.touch
.then(() => Deno.rename(tempPath, outputFullPath))
.catch(cleanup),
};
} catch (error) {
await cleanup();
throw error;
}
}
}
const joinSource = (source: Source, subpath: string): Source =>
typeof source === 'string' ? path.join(source, subpath)
: source instanceof AbsoluteSource ? new AbsoluteSource(path.join(source.path, subpath))
: new PackageSource(source.package, path.join(source.path, subpath));
class CopyStaticFiles implements Task<Touch> {
readonly #spec: SourceOutputPair;
constructor(
spec: SourceOutputSpec,
readonly dependencies: Providers<Touch>,
) {
this.#spec = expandSpec(spec);
}
async run(ctx: Context, deps: Provided<Touch>): Promise<TaskResultWithInputMap> {
const subtasks = [];
const resolvedSource = ctx.resolveSource(this.#spec.from);
for await (const entry of Deno.readDir(resolvedSource)) {
if (!entry.isDirectory) {
const subtask = new CopyStaticFile({
from: joinSource(this.#spec.from, entry.name),
to: path.join(this.#spec.to, entry.name),
}, this.dependencies);
subtasks.push(subtask.run(ctx, deps));
}
}
const subtasks_ = await Promise.all(subtasks);
return {
inputs: subtasks_.flatMap(task => task.inputs),
entries: subtasks_.flatMap(task => task.entries),
work: Promise.all(subtasks_.map(task => task.work)),
inputsByEntry: new Map(subtasks_.flatMap(task =>
task.entries.map(([k]) => [k, task.inputs]))),
};
}
}
class CopyRuffleComponents implements Task<Dependencies<CopyUnversionedStaticFile>> {
constructor(
readonly dependencies: Providers<Dependencies<CopyUnversionedStaticFile>>,
) {}
async run(
ctx: Context,
deps: Provided<Dependencies<CopyUnversionedStaticFile>>,
): Promise<TaskResult> {
const ruffleRoot = ctx.resolveSource(new PackageSource('@ruffle-rs/ruffle', '.'));
const subtasks = [];
for await (const {name} of Deno.readDir(ruffleRoot)) {
if (
name.endsWith('.wasm')
|| (name.startsWith('core.ruffle.') && name.endsWith('.js'))
) {
subtasks.push(
// These components already include hashes in their names.
new CopyUnversionedStaticFile({
from: new PackageSource('@ruffle-rs/ruffle', name),
to: 'js/ruffle/' + name,
}, this.dependencies).run(ctx, deps)
);
}
}
return {
inputs: [], // This task type doesn’t watch.
entries: subtasks.flatMap(task => task.entries),
work: Promise.all(subtasks.map(task => task.work)),
};
}
}
const updateSet = <T>(set: Set<T>, values: Iterable<T>) => {
for (const x of values) {
set.add(x);
}
};
const canGet = (x: unknown): x is Readonly<Record<string, unknown>> => x != null;
class Sass implements Task<Touch & {images: TaskResultWithInputMap}> {
readonly #spec: SourceOutputPair<RelativeSource>;
constructor(
spec: SourceOutputPair<RelativeSource>,
readonly dependencies: Providers<Touch & {images: TaskResultWithInputMap}>,
) {
this.#spec = spec;
}
async run(ctx: Context, deps: Provided<Touch & {images: TaskResultWithInputMap}>): Promise<TaskResult> {
const resolvedSource = ctx.resolveSource(this.#spec.from);
const response = await ctx.sendCssWork({resolvedSource});
if (
!canGet(response)
|| typeof response.css !== 'string'
|| !Array.isArray(response.loadedUrls)
|| !response.loadedUrls.every(x => typeof x === 'string')
|| !Array.isArray(response.warnings)
|| !response.warnings.every(x => typeof x === 'string')
) {
throw new TypeError('bad response from CSS worker');
}
//response satisfies CssResponse;
// ... is the intent here, but that doesn't typecheck in current TypeScript, even though the compiler essentially knows it.
for (const warning of response.warnings) {
// NOTE: workers can already write to stdout/stderr (and read from stdin!)
console.error(warning);
}
// ew
const images = await deps.images;
const subresources = new Map<string, {inputs: readonly Source[], resolved: string}>(
[
...images.entries.map(([k, v]) => [k, {
inputs: images.inputsByEntry.get(k)!,
resolved: v,
}] as const),
// font license does not allow distribution with source code
...[
'fonts/Museo500.woff2',
'fonts/Museo500.woff',
].map(p => [p, {inputs: [], resolved: p}] as const),
]
.map(([k, v]) => [new URL('http://localhost/' + k).href, v])
);
const subresourceInputs = new Set<Source>();
const urlTranslatedCss = response.css.replace(/(url\()([^)]*)\)/gi, (_match: string, left: string, link: string) => {
if (/^["']./.test(link) && link.slice(-1) === link.charAt(0)) {
link = link.slice(1, -1);
}
const expandedLink = new URL(link, 'http://localhost/' + this.#spec.from).href;
const subresource = subresources.get(expandedLink);
if (!subresource) {
throw new Error(`Unresolvable url() in ${this.#spec.from}: ${link}`);
}
updateSet(subresourceInputs, subresource.inputs);
return left + '/' + subresource.resolved + ')';
});
const urlTranslatedCssBytes = new TextEncoder().encode(urlTranslatedCss);
const shortDigest = await shortHash(urlTranslatedCssBytes);
const outputPath = addFilenameSuffix(this.#spec.to, shortDigest);
const outputFullPath = ctx.resolveOutput(outputPath);
return {
inputs: [
...subresourceInputs,
// untrusted, but declaring invalid inputs should be harmless
...response.loadedUrls.map(url =>
removePrefix(path.fromFileUrl(url), ctx.absoluteAssetsRoot + '/')),
],
entries: [[this.#spec.to, outputPath]],
work: deps.touch.then(() => Deno.writeFile(outputFullPath, urlTranslatedCssBytes)),
};
}
}
class EsbuildFilesWithDeps<Deps extends AnyDependencies> implements Task<Touch & Deps, TaskResult, esbuild.BuildContext> {
#relativePaths: readonly SourceOutputSame[];
#options: (d: Provided<Deps>) => Awaitable<esbuild.BuildOptions>;
constructor(
relativePaths: readonly SourceOutputSame[],
options: (d: Provided<Deps>) => Awaitable<esbuild.BuildOptions>,
readonly dependencies: Providers<Touch & Deps>,
) {
this.#relativePaths = relativePaths;
this.#options = options;
}
private async createBuildContext(ctx: Context, deps: Provided<Deps>, entryPoints: string[]) {
return esbuild.context({
entryPoints,
outdir: '.', // `outdir` is required even when `write: false`
outbase: ctx.assetsRoot,
bundle: true,
minify: true,
target: 'es6',
banner: {
js: '"use strict";',
},
mangleProps: /^m_/,
...await this.#options(deps),
write: false,
metafile: true,
});
}
async run(
ctx: Context,
deps: Provided<Touch & Deps>,
buildContext: Awaited<ReturnType<typeof this.createBuildContext>> | null,
): Promise<TaskResultWithCache<NonNullable<typeof buildContext>>> {
const entryPoints = this.#relativePaths.map(p => ctx.resolveSource(p));
const cwd = Deno.cwd();
buildContext ??= await this.createBuildContext(ctx, deps, entryPoints);
const result = await buildContext.rebuild();
if (result.warnings.length !== 0) {
for (const warning of result.warnings) {
console.warn(warning);
}
throw new Error('Unexpected warnings');
}
if (ctx.verbose) {
console.log(await esbuild.analyzeMetafile(result.metafile, {verbose: true}));
}
const entries: [string, string][] = [];
const writes: [string, Uint8Array][] = [];
// output metadata keyed by esbuild’s output files’ `path` property, which seems to be an absolute path based on the resolved value of `outdir`
// XXX: not yet tested on Windows
const outputsByAbsPath = new Map(
Object.entries(result.metafile.outputs)
.map(([assetId, output]) => [path.join(cwd, assetId), {
assetId,
output, // XXX: unused for now
}])
);
for (const outputFile of result.outputFiles) {
const {assetId} = outputsByAbsPath.get(outputFile.path)!;
const bundleContents = outputFile.contents;
const shortDigest = await shortHash(bundleContents satisfies Uint8Array as Uint8Array<ArrayBuffer>);
const outputPath = addFilenameSuffix(assetId, shortDigest);
entries.push([assetId, outputPath]);
writes.push([outputPath, bundleContents]);
}
const inputs =
Object.keys(result.metafile.inputs)
.map(inputPath => tryRemovePrefix(path.join(cwd, inputPath), ctx.absoluteAssetsRoot + '/'))
// npm dependencies aren’t watched
.filter(x => x !== null);
return {
inputs,
entries,
work: deps.touch.then(() =>
Promise.all(
writes.map(([outputPath, bundleContents]) =>
Deno.writeFile(ctx.resolveOutput(outputPath), bundleContents)
)
)
),
cache: buildContext,
};
}
}
class EsbuildFiles extends EsbuildFilesWithDeps<Touch> {
constructor(
relativePaths: readonly SourceOutputSame[],
options: esbuild.BuildOptions,
dependencies: Providers<Touch>,
) {
super(relativePaths, () => options, dependencies);
}
}
const showUsage = () => {
console.error('Usage: deno run build.ts --assets=<asset-dir> --output=<output-dir>');
};
class UsageError extends Error implements CanHaveStderr {
get [$hasStderr]() {
return true;
}
}
class CreateFolders implements Task<Record<string, never>> {
constructor(
readonly folders: readonly string[],
) {}
get dependencies() {
return {};
}
async run(ctx: Context): Promise<TaskResult> {
await Promise.all(
this.folders.map(p =>
Deno.mkdir(
path.join(ctx.outputRoot, p),
{recursive: true}
)
)
);
return {
inputs: [],
entries: [],
work: Promise.resolve(),
};
}
}
const getSingleEntry = (result: TaskResult, expectedKey: string): string => {
const {entries} = result;
if (entries.length !== 1 || entries[0][0] !== expectedKey) {
console.error('Expected task to produce single entry with key %o, but got %o.', expectedKey, entries);
throw new Error();
}
return entries[0][1];
};
const touch = new CreateFolders([
'css',
'fonts',
'img/help',
'js/mod',
'js/ruffle',
]);
const images = new CopyStaticFiles('img', {touch});
const marked = new CopyStaticFile('js/marked.js', {touch});
const ruffle = new CopyStaticFile({
from: new PackageSource('@ruffle-rs/ruffle', 'ruffle.js'),
to: 'js/ruffle/ruffle.js',
}, {touch});
const PRIVATE_FIELDS: esbuild.BuildOptions = {
target: [
'chrome84',
'firefox90',
'ios15',
'safari15',
],
};
const PRIVATE_FIELDS_ESM: esbuild.BuildOptions = {
...PRIVATE_FIELDS,
format: 'esm',
banner: {},
};
const tasks: readonly AnyTask[] = [
touch,
images,
marked,
new Sass({from: 'scss/site.scss', to: 'css/site.css'}, {touch, images}),
new Sass({from: 'scss/help.scss', to: 'css/help.css'}, {touch, images}),
new Sass({from: 'scss/imageselect.scss', to: 'css/imageselect.css'}, {touch, images}),
new Sass({from: 'scss/mod.scss', to: 'css/mod.css'}, {touch, images}),
new Sass({from: 'scss/signup.scss', to: 'css/signup.css'}, {touch, images}),
new EsbuildFilesWithDeps<{marked: TaskResult}>([
'js/scripts.js',
], async (deps) => {
const markedSrc = getSingleEntry(await deps.marked, 'js/marked.js');
return ({
define: {
MARKED_SRC: JSON.stringify('/' + markedSrc),
},
});
}, {touch, marked}),
new EsbuildFiles([
'js/search.js',
'js/zxcvbn-check.js',
], {}, {touch}),
// main.js has a `Link: …;rel=preload`, and Cloudflare’s Early Hints implementation doesn’t support `modulepreload` yet
new EsbuildFiles(['js/main.js'], PRIVATE_FIELDS, {touch}),
new EsbuildFiles([
'js/forms.js',
'js/login-box.js',
'js/message-list.js',
'js/notification-list.js',
'js/rating-override.js',
'js/tags-edit.js',
'js/submit.js',
'js/view-count.js',
'js/mod/suspenduser.js',
], PRIVATE_FIELDS_ESM, {touch}),
new EsbuildFilesWithDeps<{ruffle: TaskResult}>([
'js/flash.js',
], async (deps) => {
const ruffleSrc = getSingleEntry(await deps.ruffle, 'js/ruffle/ruffle.js');
return ({
...PRIVATE_FIELDS_ESM,
define: {
RUFFLE_SRC: JSON.stringify('/' + ruffleSrc),
},
});
}, {touch, ruffle}),
new CopyStaticFiles('img/help', {touch}),
new CopyUnversionedStaticFile('opensearch.xml', {touch}),
// libraries
new CopyStaticFile('js/jquery-2.2.4.min.js', {touch}),
new CopyStaticFile('js/imageselect.js', {touch}),
new CopyStaticFile('js/zxcvbn.js', {touch}),
new CopyRuffleComponents({touch}),
ruffle,
];
const ORDER_UNSET = -1;
const ORDER_IN_PROGRESS = -2;
const getTopologicalOrder = (
tasks: readonly AnyTask[],
indexOf: (t: AnyTask) => number | undefined,
): number[] => {
const order: number[] = Array(tasks.length).fill(ORDER_UNSET);
let nextOrder = 0;
const traverse = (i: number) => {
if (order[i] >= 0) {
// dependency already satisfied
return;
}
if (order[i] === ORDER_IN_PROGRESS) {
throw new Error('dependency cycle');
}
order[i] = ORDER_IN_PROGRESS;
// satisfy all dependencies of this task
for (const dep in tasks[i].dependencies) {
const depIndex = indexOf(tasks[i].dependencies[dep]);
if (depIndex === undefined) {
throw new Error(`dependency not in tasks: ${dep}`);
}
traverse(depIndex);
}
// all dependencies of this task are now satisfied
order[i] = nextOrder++;
};
for (let i = 0; i < tasks.length; i++) {
traverse(i);
}
return order;
};
const enum Condition {
set,
unset,
handled,
}
const main = async () => {
const args = parseArgs(Deno.args, {
string: ['assets', 'output'],
boolean: ['watch'],
default: {
watch: false,
},
unknown: () => {
showUsage();
throw new UsageError();
},
});
if (args.assets === undefined || args.output === undefined) {
showUsage();
throw new UsageError();
}
const assetsRoot: string = args.assets;
const outputRoot: string = args.output;
const manifestPath = path.join(outputRoot, 'rev-manifest.json');
const verbose = !args.watch;
using ctx: Context = new Context(verbose, assetsRoot, outputRoot);
// Node:
// apparently no race on Linux (uncomfortable and not documented; I would expect watcher readiness to be async): https://github.com/nodejs/node/issues/52601
// can’t just use `fs[.promises].watch` with `recursive`: https://github.com/nodejs/node/blob/v23.11.0/lib/internal/fs/promises.js#L1248-L1250
//
// Deno:
// unknown. TODO
//
// Preferably shouldn’t miss any events during (or after!) the first build.
//
// We don’t really want this to produce absolute paths in events at all, but not only does it, it can actually produce weird paths like `/weasyl-build/./assets/…` with a relative path argument, so pass an absolute path.
const watcher = args.watch ? Deno.watchFs(ctx.absoluteAssetsRoot, {recursive: true}) : null;
const watcherPrefix = ctx.absoluteAssetsRoot + '/';
const watchMap = new Map<string, number[]>();
let buildFailed = Condition.unset;
const indexes = new Map(tasks.entries().map(([i, task]) => [task, i]));
const order = getTopologicalOrder(tasks, t => indexes.get(t));
const latestRuns: (Awaitable<TaskResult> | null)[] = Array(tasks.length).fill(null);
const latestCache: (TaskCache | null)[] = Array(tasks.length).fill(null);
const rebuild = async () => {
watchMap.clear();
buildFailed = Condition.unset;
let startedRuns = null;
try {
for (const i of order) {
if (latestRuns[i] === null) {
const task = tasks[i];
const deps = mapValues(task.dependencies, dep =>
Promise.resolve(latestRuns[indexes.get(dep)!]!));
latestRuns[i] = task.run(ctx, deps, latestCache[i]);
}
}
startedRuns = asNoNulls(latestRuns);
const taskResults = await Promise.all(startedRuns);
for (const [i, r] of taskResults.entries()) {
if (args.watch) {
latestCache[i] = r.cache ?? null;
} else {
r.cache?.dispose();
}
for (const input of r.inputs) {
if (typeof input !== 'string') {
// only `RelativeSource`s can be watched
continue;
}
let inputTasks = watchMap.get(input);
if (inputTasks === undefined) {
watchMap.set(input, inputTasks = []);
}
inputTasks.push(i);
}
}
await Deno.writeTextFile(
manifestPath,
JSON.stringify(
Object.fromEntries(
taskResults.flatMap(r => r.entries))),
);
await Promise.all(taskResults.map(r => r.work));
return true;
} catch (error) {
if (startedRuns !== null) {
let timer: Timer | null = setTimeout(() => {
timer = null;
console.debug('waiting for other tasks to finish after build failure…');
}, 100);
await Promise.allSettled(startedRuns);
if (timer === null) {
console.debug('other tasks done');
} else {
clearTimeout(timer);
}
}
watchMap.clear();
buildFailed = Condition.set;
if (!args.watch) {
throw error;
}
if (!hasStderr(error)) {
console.error('%s', error);
}
return false;
}
};
await rebuild();
if (watcher === null) {
return;
}
/** Changes since the last build started or was enqueued. */
const changes = new Set<string>();
let changesUnknown = Condition.unset;
const rebuilder = new LimitOne(async () => {
changes.clear();
changesUnknown = Condition.unset;
performance.mark('rebuild-start');
const success = await rebuild();
performance.mark('rebuild-end');