Repository navigation
Expand file tree
/
Copy pathcli.js
More file actions
3131 lines (2969 loc) · 149 KB
/
Copy pathcli.js
File metadata and controls
3131 lines (2969 loc) · 149 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
// tinyjs CLI: scaffold, run, and package tinyjs projects.
//
// tinyjs new <dir> scaffold a new app
// tinyjs dev run the app in the current directory
// tinyjs build build dist/<name> + dist/<Name>.app
// tinyjs update self-update from the latest GitHub release
// tinyjs uninstall remove ~/.tinyjs and the PATH symlink
//
// Runs on txiki.js itself (via the `tinyjs` wrapper script).
const enc = new TextEncoder();
const dec = new TextDecoder();
// txiki has no tjs.platform; OS=Windows_NT is always set by Windows itself,
// and navigator.platform reads "Linux …" from uname on Linux.
const IS_WIN = tjs.env.OS === 'Windows_NT';
const IS_LINUX = !IS_WIN && /linux/i.test(globalThis.navigator?.platform ?? '');
// URL.pathname renders C:\Users\me as /C:/Users/me (percent-encoded) — decode
// and drop the leading slash so the result is a usable Windows path.
function pathFromUrl(u) {
let p = decodeURIComponent(u.pathname);
if (/^\/[A-Za-z]:\//.test(p)) p = p.slice(1);
return p;
}
const TOOL_DIR = pathFromUrl(new URL('.', import.meta.url));
// Invoked as: tjs run cli.js <cmd> [args...]
const [cmd, ...args] = tjs.args.slice(3);
function fail(msg) {
console.log('tinyjs: ' + msg);
tjs.exit(1);
}
async function exists(p) {
try {
await tjs.stat(p);
return true;
} catch {
return false;
}
}
async function copyTree(src, dest) {
await tjs.makeDir(dest, { recursive: true }).catch(() => {});
const iter = await tjs.readDir(src);
for await (const e of iter) {
const s = src + '/' + e.name;
const d = dest + '/' + e.name;
if (e.isDirectory) await copyTree(s, d);
else await tjs.writeFile(d, await tjs.readFile(s));
}
}
// tjs.watch on a folder: cb(rel) per change, rel relative to dir with '/'
// separators, skipped when skip(rel). macOS (FSEvents) and Windows watch the
// whole tree from one call, but Linux's inotify only sees a folder's direct
// entries, so with `perDir` every subfolder gets its own watch, including
// folders made later. Self-contained: the dev entry inlines its source for
// the frontend reload watcher.
async function watchTree(dir, cb, skip = () => false, perDir = false) {
const watchers = new Map();
const add = async (rel) => {
if (watchers.has(rel)) return;
const path = rel ? dir + '/' + rel : dir;
try {
watchers.set(rel, tjs.watch(path, (file) => {
if (!file) return;
const r = (rel ? rel + '/' : '') + String(file).replace(/\\/g, '/');
if (skip(r)) return;
if (perDir) sync(r);
cb(r);
}));
} catch { return; }
if (!perDir) return;
try {
for await (const e of await tjs.readDir(path)) {
const r = (rel ? rel + '/' : '') + e.name;
if (e.isDirectory && !skip(r)) await add(r);
}
} catch {}
};
// A name that changed may be a folder made (watch it and what's inside) or
// removed (drop its watches, so one made again later is watched afresh).
const sync = async (r) => {
let isDir = false;
try { isDir = (await tjs.stat(dir + '/' + r)).isDirectory; } catch {}
if (isDir) return add(r);
for (const [k, w] of watchers) {
if (k === r || k.startsWith(r + '/')) { try { w.close(); } catch {} watchers.delete(k); }
}
};
await add('');
}
// Data the app's own code reads at runtime lives in resources/ and reaches
// it as app.paths.resources: the whole folder, or only the files and
// directories inside it that tinyjs.json "resources" lists (per OS through
// the platform blocks). Files the OS reads (icon, Credits, help book) live
// in assets/ instead. Reject symlinks at every parent and below selected
// directories, even when they point back into the project.
const RESOURCES_DIR = 'resources';
async function validateResources(value) {
if (value !== undefined && !Array.isArray(value)) fail('tinyjs.json "resources" must be an array of paths inside resources/ (got ' + JSON.stringify(value) + ')');
let dirSt = null;
try { dirSt = await tjs.lstat(RESOURCES_DIR); } catch {}
if (dirSt?.isSymbolicLink) fail('resources/: symlinks are not supported');
if (dirSt && !dirSt.isDirectory) fail('resources/ must be a directory');
if (value === undefined) {
// No list: everything in the folder, if there is one.
if (!dirSt) return [];
value = [];
for await (const e of await tjs.readDir(RESOURCES_DIR)) value.push(e.name);
value.sort();
} else if (value.length && !dirSt) {
fail('tinyjs.json "resources" lists paths inside resources/, but the project has no resources/ folder');
}
const paths = [];
for (const raw of value) {
const bad = (why) => fail('tinyjs.json resource ' + JSON.stringify(raw) + ': ' + why);
if (typeof raw !== 'string' || !raw || raw.includes('\0')) bad('expected a non-empty path inside resources/');
const p = raw.replace(/\\/g, '/');
if (p.startsWith('/') || p.includes(':')) bad('absolute, drive and UNC paths are not allowed');
const parts = p.split('/').filter((s) => s && s !== '.');
if (parts.includes('..')) bad('parent traversal is not allowed');
if (IS_WIN && parts.some((s) => /[. ]$/.test(s))) bad('Windows path components cannot end in a dot or space');
if (!parts.length) bad('that is resources/ itself — leave "resources" out to ship the whole folder');
const rel = parts.join('/');
if (!paths.includes(rel)) paths.push(rel);
}
// A selected directory already includes its children. Keep the first
// occurrence of each root, independent of the order of overlapping entries.
const roots = paths.filter((p) => !paths.some((q) => p !== q && p.startsWith(q + '/')));
const root = paths.length ? await tjs.realPath(RESOURCES_DIR) : null;
async function check(rel, selected, recurse) {
const bad = (why) => fail('tinyjs.json resource ' + JSON.stringify(selected) + ' (resources/' + rel + '): ' + why);
let st;
try { st = await tjs.lstat(root + '/' + rel); }
catch { bad('not found or unreadable'); }
if (st.isSymbolicLink) bad('symlinks are not supported');
if (!st.isDirectory && !st.isFile) bad('expected a regular file or directory');
if (recurse && st.isDirectory) {
try {
const iter = await tjs.readDir(root + '/' + rel);
for await (const e of iter) await check(rel + '/' + e.name, selected, true);
} catch (e) { bad('could not read directory: ' + String(e)); }
}
}
// Validate ALL entries before dropping overlaps: e.g. file.txt/child must
// still fail even if file.txt was also explicitly selected.
for (const p of paths) {
const parts = p.split('/');
for (let i = 1; i < parts.length; i++) await check(parts.slice(0, i).join('/'), p, false);
await check(p, p, true);
}
return roots;
}
async function stageResources(paths) {
// Recheck after any frontend build hook, before copying its output.
for (const p of await validateResources(paths)) {
const src = RESOURCES_DIR + '/' + p;
const dest = '.build/resources/' + p;
try {
if ((await tjs.lstat(src)).isDirectory) await copyTree(src, dest);
else {
await tjs.makeDir(dest.replace(/\/[^/]*$/, ''), { recursive: true });
await copyFile(src, dest);
}
} catch (e) { fail('tinyjs.json resource ' + JSON.stringify(p) + ': could not copy: ' + String(e)); }
}
}
// Sidecar programs the app spawns ship from executables/, the same way
// resources/ does: with no list, everything in it, overridden by name from
// executables/<os>/ (macos, windows, linux) and then executables/<os>-<arch>/
// (arm64 / x86_64) for that build. "executables": [...] lists paths inside
// the folder instead (per OS through the platform blocks). A .app puts them
// in Contents/Helpers/, where codesign treats them as nested code and signs
// each one; Windows/Linux put them in executables/ beside the exe. Either
// way they land flat, so app.paths.executables + '/<name>' is the program.
// Only this OS's native binaries (and the libraries they load) ship:
// anything else in a .app's code location breaks its signature. A no-list
// build skips other files at the root with a note (that's where the other
// OSes' binaries live); in an OS folder or a list they fail the build.
const EXECUTABLES_DIR = 'executables';
const EXEC_OS = IS_WIN ? 'windows' : IS_LINUX ? 'linux' : 'macos';
const EXEC_KIND = IS_WIN ? 'Windows (PE: .exe/.dll)' : IS_LINUX ? 'Linux (ELF or #! script)' : 'macOS (Mach-O)';
const EXEC_OS_DIR = /^(macos|windows|linux)(-(arm64|x86_64))?$/;
const JUNK_FILES = ['.DS_Store', 'Thumbs.db', 'desktop.ini'];
let hostArchP = null;
const hostArch = () => (hostArchP ??= IS_WIN
? Promise.resolve(/arm64/i.test(tjs.env.PROCESSOR_ARCHITECTURE ?? '') ? 'arm64' : 'x86_64')
: capture(['uname', '-m']).then((m) => ({ aarch64: 'arm64', arm64: 'arm64' })[m.trim()] ?? 'x86_64'));
function isNativeBinary(b) {
const u32 = (o) => ((b[o] << 24) | (b[o + 1] << 16) | (b[o + 2] << 8) | b[o + 3]) >>> 0;
if (IS_WIN) return b[0] === 0x4d && b[1] === 0x5a; // MZ
if (IS_LINUX) return (b[0] === 0x7f && b[1] === 0x45 && b[2] === 0x4c && b[3] === 0x46) || (b[0] === 0x23 && b[1] === 0x21);
if (b.length < 8) return false;
const m = u32(0);
// Thin Mach-O (either endianness), or a fat header — which Java class files
// share; their "arch count" is the class version (45+), so cap it.
if ([0xfeedface, 0xfeedfacf, 0xcefaedfe, 0xcffaedfe].includes(m)) return true;
return (m === 0xcafebabe || m === 0xcafebabf) && u32(4) > 0 && u32(4) < 45;
}
async function readsAsNative(path) {
const fh = await tjs.open(path, 'r');
const head = new Uint8Array(8);
let n = 0;
try { n = (await fh.read(head, 0)) ?? 0; } finally { await fh.close(); }
return isNativeBinary(head.subarray(0, n));
}
const notNative = () => `not a ${EXEC_KIND} binary` + (IS_WIN || IS_LINUX ? '' :
' — a script in a .app can\'t carry a code signature; ship it in resources/ and run it with its interpreter');
// Returns { files: [{ name, src }] } for this build (name = where it lands,
// src = its path in the project), or null when nothing ships. target: a
// macOS build's MAC_TARGET (null = this Mac).
async function validateExecutables(list, target = null) {
if (list !== undefined && !Array.isArray(list)) fail('tinyjs.json "executables" must be an array of paths inside executables/ (got ' + JSON.stringify(list) + ')');
let st = null;
try { st = await tjs.lstat(EXECUTABLES_DIR); } catch {}
if (st?.isSymbolicLink) fail('executables/: symlinks are not supported');
if (st && !st.isDirectory) fail('executables/ must be a directory');
if (!st) {
if (list?.length) fail('tinyjs.json "executables" lists paths inside executables/, but the project has no executables/ folder');
return null;
}
const picked = new Map(); // name -> src
const add = async (src, name, strict, where) => {
const fst = await tjs.lstat(src);
if (fst.isSymbolicLink) fail(`${where}: symlinks are not supported`);
if (!fst.isFile) {
if (strict) fail(`${where}: expected a file — executables ship flat; put data the program reads in resources/`);
console.log(`==> note: ${src}/ isn't shipped — executables ship flat (OS folders are named macos, windows, linux, or <os>-arm64 / <os>-x86_64)`);
return;
}
if (!(await readsAsNative(src))) {
if (strict) fail(`${where}: ${notNative()}`);
console.log(`==> note: ${src} isn't a ${EXEC_KIND} binary — not shipped in this build`);
return;
}
if (!IS_WIN && !(fst.mode & 0o111))
console.log(`==> note: ${src} isn't executable — builds mark it, but run chmod +x on it for dev`);
picked.set(name, src);
};
if (list === undefined) {
// Layers, least specific first; a later file replaces an earlier one of
// the same name. Everything in an OS folder is meant for that OS, so a
// wrong file there fails; at the root it's just another OS's.
const arch = target === 'universal' ? null : target ?? await hostArch();
const layers = [EXECUTABLES_DIR, EXECUTABLES_DIR + '/' + EXEC_OS];
if (arch) layers.push(EXECUTABLES_DIR + '/' + EXEC_OS + '-' + arch);
for (const dir of layers) {
const root = dir === EXECUTABLES_DIR;
if (!root) {
let dst = null;
try { dst = await tjs.lstat(dir); } catch {}
if (!dst) continue;
if (dst.isSymbolicLink || !dst.isDirectory) fail(`executables: ${dir}: expected a folder (symlinks are not supported)`);
}
const names = [];
for await (const e of await tjs.readDir(dir)) names.push(e.name);
for (const name of names.sort()) {
if (JUNK_FILES.includes(name) || (root && EXEC_OS_DIR.test(name))) continue;
await add(dir + '/' + name, name, !root, 'executables: ' + dir + '/' + name);
}
}
} else {
// A list: exactly these, each a binary for this OS (a folder means the
// files in it). Same path rules as "resources".
const from = new Map(); // name -> list entry, to report clashes
for (const raw of list) {
const where = 'tinyjs.json executable ' + JSON.stringify(raw);
if (typeof raw !== 'string' || !raw || raw.includes('\0')) fail(where + ': expected a non-empty path inside executables/');
const p = raw.replace(/\\/g, '/');
if (p.startsWith('/') || p.includes(':')) fail(where + ': absolute, drive and UNC paths are not allowed');
const parts = p.split('/').filter((x) => x && x !== '.');
if (parts.includes('..')) fail(where + ': parent traversal is not allowed');
if (!parts.length) fail(where + ': that is executables/ itself — leave "executables" out to ship the whole folder');
for (let i = 1; i <= parts.length; i++) {
let pst = null;
try { pst = await tjs.lstat(EXECUTABLES_DIR + '/' + parts.slice(0, i).join('/')); } catch {}
if (!pst) fail(where + ': not found');
if (pst.isSymbolicLink) fail(where + ': symlinks are not supported');
}
const src = EXECUTABLES_DIR + '/' + parts.join('/');
const srcs = [];
if ((await tjs.lstat(src)).isDirectory) {
const names = [];
for await (const e of await tjs.readDir(src)) if (!JUNK_FILES.includes(e.name)) names.push(e.name);
for (const name of names.sort()) srcs.push(src + '/' + name);
} else srcs.push(src);
for (const s of srcs) {
const name = s.replace(/^.*\//, '');
if (picked.get(name) === s) continue;
if (picked.has(name)) fail(`${where}: two files named ${name} would ship (${picked.get(name)} from ${from.get(name)}) — they land side by side, so names must differ`);
await add(s, name, true, where + (s === src ? '' : ' (' + s + ')'));
from.set(name, JSON.stringify(raw));
}
}
}
const files = [...picked].map(([name, src]) => ({ name, src })).sort((a, b) => (a.name < b.name ? -1 : 1));
return files.length ? { files } : null;
}
// Copy the staged sidecars to dest, keeping them executable.
async function copyExecutables(exe, dest) {
if (!exe) return;
await tjs.makeDir(dest, { recursive: true });
for (const { name } of exe.files) {
await copyFile('.build/executables/' + name, dest + '/' + name);
if (!IS_WIN) await tjs.chmod(dest + '/' + name, 0o755);
}
}
// "executableEntitlements": { "<file name>": ["com.apple…"] } (macOS) — the
// entitlements each sidecar is signed with, replacing any it arrived with.
function executableEntitlements(cfg) {
const v = cfg.executableEntitlements;
if (v === undefined) return {};
const files = (cfg.executablesStaged?.files ?? []).map((f) => f.name);
const bad = (why) => fail('tinyjs.json "executableEntitlements": ' + why);
if (!isPlainObject(v)) bad('expected { "<file name>": ["com.apple.security…", …] }');
for (const [name, list] of Object.entries(v)) {
if (!files.includes(name)) bad(`${JSON.stringify(name)} isn't one of the executables this build ships` +
(files.length ? ' (' + files.join(', ') + ')' : ' (none)'));
if (!Array.isArray(list) || list.some((k) => typeof k !== 'string' || !/^[A-Za-z0-9.-]+$/.test(k)))
bad(`${JSON.stringify(name)}: expected an array of entitlement keys, e.g. ["com.apple.security.cs.allow-jit"]`);
}
return v;
}
// Gather this build's sidecars flat in .build/executables. Dev links them on
// macOS/Linux, so a sidecar rebuilt while dev runs is the one that spawns;
// builds copy and mark them executable.
async function stageExecutables(exe, dev) {
if (!exe) return;
await tjs.makeDir('.build/executables', { recursive: true });
for (const { name, src } of exe.files) {
const dest = '.build/executables/' + name;
if (dev && !IS_WIN) await tjs.symlink(await tjs.realPath(src), dest);
else {
await copyFile(src, dest);
if (!IS_WIN) await tjs.chmod(dest, 0o755);
}
}
}
// assets/ holds the files the OS and the build read, each by a known name:
// the icon, the About panel's Credits, the macOS help book. Nothing else in
// it ships, so anything unrecognised is most likely a page or data file put
// in the wrong folder — say so instead of dropping it silently.
const CREDITS_FILES = ['Credits.html', 'Credits.rtf', 'Credits.rtfd'];
// The About panel's credits: assets/Credits.{html,rtf,rtfd}, or a
// Credits.html at the project root (where it went before assets/).
async function findCredits() {
for (const f of CREDITS_FILES) if (await exists('assets/' + f)) return 'assets/' + f;
return (await exists('Credits.html')) ? 'Credits.html' : null;
}
// "helpBook" (in the macos block) names a folder inside assets/.
function helpBookRel(value) {
if (value === undefined) return null;
const rel = typeof value === 'string' ? value.replace(/\\/g, '/').replace(/\/+$/, '') : '';
if (!rel || rel.startsWith('/') || rel.includes(':') || rel.split('/').includes('..'))
fail('tinyjs.json "helpBook" must name a folder inside assets/ (got ' + JSON.stringify(value) + ')');
// It lands in the .app's Resources/, which already holds the app itself
// and its icon and credits.
const folder = rel.replace(/^.*\//, '');
if (/^(app|AppIcon\.icns|Credits\.(html|rtf|rtfd))$/i.test(folder))
fail(`tinyjs.json "helpBook": a help book can't be named ${folder} — rename the folder`);
return rel;
}
async function warnUnusedAssets(cfg) {
const used = new Set(['.DS_Store', 'Thumbs.db', 'desktop.ini', ...CREDITS_FILES]);
if (cfg.icon && /^assets\/[^/]+$/.test(cfg.icon)) used.add(cfg.icon.slice(7));
if (cfg.helpBookAnyOS) used.add(cfg.helpBookAnyOS.split('/')[0]);
let iter;
try { iter = await tjs.readDir('assets'); } catch { return; }
for await (const e of iter) {
if (used.has(e.name)) continue;
console.log(`==> note: assets/${e.name} isn't used by the build — assets/ is for the ` +
'icon, Credits and help book; files for your page go in the frontend, data for your code in resources/');
}
}
// Copy the help book (#47) into the .app's Resources and (re)build its
// search index. Returns the Info.plist values, or null without one: the
// folder, and the name Help Viewer knows it by — the book's own
// CFBundleIdentifier, falling back to its folder name for a book with no
// Info.plist (older ones).
async function stageHelpBook(cfg, resDir) {
const rel = helpBookRel(cfg.helpBook);
if (!rel) return null;
const src = 'assets/' + rel;
let st = null;
try { st = await tjs.lstat(src); } catch {}
if (!st?.isDirectory) fail(`tinyjs.json "helpBook": ${src} is not a folder`);
const folder = rel.replace(/^.*\//, '');
const dest = resDir + '/' + folder;
await run(['cp', '-R', src, dest]);
const info = dest + '/Contents/Info.plist';
const key = async (k) => (await capture(['plutil', '-extract', k, 'raw', '-o', '-', info])).trim();
let name = await key('CFBundleIdentifier');
if (!name) {
name = folder.replace(/\.help$/i, '');
console.log(`==> note: ${src} has no Contents/Info.plist CFBundleIdentifier — naming the help book "${name}"`);
}
// A stale index is the usual reason Help search finds nothing, so build a
// fresh one into the copy for each language, where the book says it lives.
const indexPath = await key('HPDBookIndexPath');
if (indexPath) {
let iter = null;
try { iter = await tjs.readDir(dest + '/Contents/Resources'); } catch {}
for await (const e of iter ?? []) {
if (!e.isDirectory || !e.name.endsWith('.lproj')) continue;
const dir = dest + '/Contents/Resources/' + e.name;
if (!(await tryRun(['hiutil', '-I', 'corespotlight', '-Caf', dir + '/' + indexPath, dir])))
console.log(`==> note: hiutil could not index ${e.name} of the help book — keeping the index it shipped with`);
}
}
console.log(`==> help book ${folder} (${name})`);
return { folder, name };
}
// Portable rm -rf (replaces shelling out, which Windows has no equivalent for).
async function rmTree(p) {
try {
await tjs.remove(p, { recursive: true });
return;
} catch {}
try {
const st = await tjs.stat(p);
if (st.isDirectory) {
const iter = await tjs.readDir(p);
for await (const e of iter) await rmTree(p + '/' + e.name);
}
await tjs.remove(p);
} catch {}
}
async function copyFile(src, dest) {
await tjs.writeFile(dest, await tjs.readFile(src));
}
// Run a shell command line: sh -c on POSIX, cmd /c on Windows (also the only
// way to reach npm/npx there — they are .cmd shims CreateProcess won't exec).
const shellArgv = (cmdline) => IS_WIN ? ['cmd', '/c', cmdline] : ['sh', '-c', cmdline];
// npm/npx-style argv: pass through on POSIX, hop through cmd /c on Windows.
const nodeToolArgv = (argv) => IS_WIN ? ['cmd', '/c', ...argv] : argv;
// Give coding agents working in a scaffolded project the tinyjs reference
// skill — in .claude/skills/ (Claude Code) and .agents/skills/ (the
// tool-agnostic location other agents read).
async function writeAgentSkill(dir) {
// The whole skill dir: SKILL.md plus references/ (loaded on demand by the
// agent, so the core stays small while the deep material rides along).
for (const base of ['/.claude/skills/tinyjs', '/.agents/skills/tinyjs']) {
await copyTree(TOOL_DIR + 'skill', dir + base);
}
}
async function run(argv, opts = {}) {
const p = tjs.spawn(argv, { stdin: 'inherit', stdout: 'inherit', stderr: 'inherit', ...opts });
const st = await p.wait();
if (st.exit_status !== 0 || st.term_signal) {
fail(`command failed (${argv[0]}): ` + JSON.stringify(st));
}
}
// Like run(), but stdout passes through only until a line matches `stopAt`;
// that line and everything after it are dropped. For create-vite, whose
// closing "Done. Now run: npm install / npm run dev" contradicts the steps
// we print next (issue #43).
async function runUntil(argv, stopAt, opts = {}) {
const p = tjs.spawn(argv, { stdin: 'inherit', stdout: 'pipe', stderr: 'inherit', ...opts });
const reader = p.stdout.getReader();
let pending = '', stopped = false;
for (;;) {
const { value, done } = await reader.read();
if (done) break;
if (stopped) continue; // keep draining so the child never blocks on a full pipe
pending += dec.decode(value, { stream: true });
const lines = pending.split('\n');
pending = lines.pop();
let out = '';
for (const l of lines) {
if (stopAt.test(l)) { stopped = true; break; }
out += l + '\n';
}
if (out) await writeOut(out);
}
if (!stopped && pending && !stopAt.test(pending)) await writeOut(pending);
const st = await p.wait();
if (st.exit_status !== 0 || st.term_signal) {
fail(`command failed (${argv[0]}): ` + JSON.stringify(st));
}
}
// Run a command and capture its stdout.
async function runCapture(argv) {
const p = tjs.spawn(argv, { stdout: 'pipe', stderr: 'ignore' });
const reader = p.stdout.getReader();
let out = '';
while (true) {
const { value, done } = await reader.read();
if (done) break;
out += dec.decode(value, { stream: true });
}
const st = await p.wait();
if (st.exit_status !== 0 || st.term_signal) fail(`command failed (${argv[0]})`);
return out;
}
// Like run(), but returns false on failure instead of aborting.
async function tryRun(argv, opts = {}) {
const p = tjs.spawn(argv, { stdin: 'inherit', stdout: 'ignore', stderr: 'ignore', ...opts });
const st = await p.wait();
return st.exit_status === 0 && !st.term_signal;
}
// Capture stdout, tolerating a non-zero exit (returns whatever was printed).
async function capture(argv, opts = {}) {
const p = tjs.spawn(argv, { stdout: 'pipe', stderr: 'ignore', ...opts });
const reader = p.stdout.getReader();
let out = '';
while (true) {
const { value, done } = await reader.read();
if (done) break;
out += dec.decode(value, { stream: true });
}
await p.wait();
return out;
}
// --- self-update -------------------------------------------------------------
const REPO = 'tarwin/tinyjsapp';
const UPDATE_CHECK_FILE = TOOL_DIR + '.update-check';
const UPDATE_CHECK_INTERVAL = 24 * 60 * 60 * 1000;
async function toolVersion() {
try {
return dec.decode(await tjs.readFile(TOOL_DIR + 'VERSION')).trim();
} catch {
return 'dev';
}
}
function parseVer(v) {
const m = /^v?(\d+)\.(\d+)\.(\d+)/.exec(String(v));
return m ? [+m[1], +m[2], +m[3]] : null;
}
// True when `latest` is a release newer than `current`.
function isNewer(current, latest) {
const a = parseVer(current), b = parseVer(latest);
if (!a || !b) return false;
for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] < b[i];
return false;
}
function withTimeout(promise, ms) {
return new Promise((resolve) => {
const t = setTimeout(() => resolve(null), ms);
promise.then(
(v) => { clearTimeout(t); resolve(v); },
() => { clearTimeout(t); resolve(null); },
);
});
}
// The tag comes off github.com's /releases/latest redirect (→ /releases/tag/
// vX.Y.Z), not the REST API: unauthenticated API calls are capped at 60 an
// hour per IP, which shared CI runners hit constantly (#51).
async function fetchLatestVersion() {
try {
const res = await fetch(`https://github.com/${REPO}/releases/latest`, {
method: 'HEAD', headers: { 'user-agent': 'tinyjs-cli' },
});
if (!res.ok) return null;
const tag = res.url.replace(/\/+$/, '').split('/').pop();
return typeof tag === 'string' && parseVer(tag) ? tag : null;
} catch {
return null;
}
}
// Once a day (and never from a source checkout), see if a newer release
// exists and mention it. Network errors are silent; never blocks or fails
// the command it piggybacks on.
async function maybeNotifyUpdate() {
try {
const current = await toolVersion();
if (current === 'dev') return;
let cache = null;
try {
cache = JSON.parse(dec.decode(await tjs.readFile(UPDATE_CHECK_FILE)));
} catch {}
const notify = (latest) =>
console.log(`tinyjs: ${latest} is available (you have ${current}) — run \`tinyjs update\``);
if (cache?.latest && isNewer(current, cache.latest)) notify(cache.latest);
if (cache && Date.now() - (cache.checkedAt || 0) < UPDATE_CHECK_INTERVAL) return;
const latest = await withTimeout(fetchLatestVersion(), 4000);
if (!latest) return;
await tjs.writeFile(UPDATE_CHECK_FILE,
enc.encode(JSON.stringify({ checkedAt: Date.now(), latest })));
if (isNewer(current, latest) && latest !== cache?.latest) notify(latest);
} catch {}
}
async function cmdUpdate() {
const dryRun = args.includes('--dry-run');
const current = await toolVersion();
if (current === 'dev') {
fail('running from a source checkout — update with `git pull` (+ ' +
(IS_WIN ? 'setup.ps1' : './setup.sh') + ') instead');
}
const latest = await withTimeout(fetchLatestVersion(), 10000);
if (!latest) fail('could not reach GitHub to check the latest release');
if (!isNewer(current, latest)) {
console.log(`already up to date (${current})`);
tjs.exit(0);
}
if (args[0] === '--check') {
console.log(`${latest} is available (you have ${current}) — run \`tinyjs update\` to install`);
tjs.exit(0);
}
// Run the installer that shipped WITH this install, not a fresh copy from
// tinyjs.app: the website would otherwise be trusted to run code on every
// update, on top of GitHub serving the release (#30). It downloads the
// pinned tag from GitHub, checks it against the release's checksums.txt,
// and swaps the install dir — TINYJS_HOME keeps a custom location where it
// is. It runs from a temp copy because the swap deletes (Unix) or moves
// (Windows) the directory it would otherwise be running from. Only a
// hand-assembled install lacks the copy; that falls back to the website.
// Backslashes on Windows: install.ps1 matches TINYJS_HOME against the user
// PATH entries verbatim, and a forward-slash spelling would add a second.
let installDir = TOOL_DIR.replace(/[\\/]+$/, '');
if (IS_WIN) installDir = installDir.replace(/\//g, '\\');
const local = TOOL_DIR + (IS_WIN ? 'install.ps1' : 'install');
const haveLocal = await exists(local);
const env = { ...tjs.env, TINYJS_HOME: installDir, TINYJS_VERSION: latest };
console.log(`==> updating ${current} → ${latest} in ${installDir}`);
if (dryRun) {
console.log(haveLocal
? ` would run the installer shipped with this install: ${local}`
: ` no installer in this install — would fall back to ${IS_WIN ? 'https://tinyjs.app/install.ps1' : 'https://tinyjs.app/install'}`);
console.log(` with TINYJS_HOME=${installDir} TINYJS_VERSION=${latest}`);
console.log(` it downloads from https://github.com/${REPO}/releases/tag/${latest} and checks checksums.txt`);
tjs.exit(0);
}
if (!haveLocal) {
console.log(' (this install has no bundled installer — using the one on tinyjs.app)');
if (IS_WIN) {
await run(['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass',
'-Command', 'irm https://tinyjs.app/install.ps1 | iex'], { env });
} else {
await run(['sh', '-c', 'curl -fsSL https://tinyjs.app/install | sh'], { env });
}
tjs.exit(0);
}
const tmp = await tjs.makeTempDir(tjs.tmpDir + '/tinyjs-update-XXXXXX');
const script = tmp + (IS_WIN ? '/install.ps1' : '/install');
await copyFile(local, script);
try {
if (IS_WIN) {
await run(['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', script], { env });
} else {
await run(['sh', script], { env });
}
} finally {
await tjs.remove(tmp, { recursive: true }).catch(() => {});
}
tjs.exit(0);
}
// Read a symlink's target (absolute or relative), or null if p isn't a symlink.
async function readLink(p) {
const t = (await capture(['readlink', p])).trim();
return t || null;
}
// Ask a yes/no question on the controlling terminal. No tty → treat as "no",
// so a piped/non-interactive `tinyjs uninstall` never deletes without --yes.
async function confirmTty(prompt) {
const out = (await capture(['sh', '-c',
'printf "%s" "$1" >/dev/tty 2>/dev/null && IFS= read -r r </dev/tty && printf "%s" "$r"',
'sh', prompt])).trim();
return /^y(es)?$/i.test(out);
}
async function cmdUninstall() {
if (IS_WIN) {
fail('there is no Windows installer yet — delete the checkout and remove it from your user PATH (Settings > Environment Variables; setup.ps1 added it)');
}
const version = await toolVersion();
if (version === 'dev') {
fail('running from a source checkout — nothing to uninstall (just delete the repo)');
}
// The install dir is the directory this CLI runs from — the installer created
// it as ${TINYJS_HOME:-~/.tinyjs}. Trust the running location over the env so
// we remove exactly the install that's executing.
const installDir = TOOL_DIR.replace(/\/+$/, '');
// Safety rails: never rm -rf a root or a git checkout.
if (!installDir || installDir === '/' || await exists(installDir + '/.git')) {
fail(`refusing to remove ${installDir || '/'} — does not look like a tinyjs install`);
}
// Collect PATH symlinks that point back into this install dir (the same
// candidate dirs the installer picks from).
const home = tjs.env.HOME || '';
const wrapper = installDir + '/tinyjs';
const links = [];
for (const d of ['/usr/local/bin', '/opt/homebrew/bin', home + '/.local/bin']) {
const link = d + '/tinyjs';
const target = await readLink(link);
if (!target) continue;
// Resolve a relative target against the link's own directory.
const abs = target.startsWith('/') ? target : d + '/' + target;
if (abs === wrapper) links.push(link);
}
console.log(`this will remove tinyjs ${version}:`);
console.log(' ' + installDir + ' (runtime + CLI)');
for (const l of links) console.log(' ' + l + ' (PATH symlink)');
if (!links.length) {
console.log(' (no PATH symlink found pointing here — remove any stray one by hand)');
}
const yes = args.some(a => a === '-y' || a === '--yes' || a === '-f' || a === '--force');
if (!yes && !(await confirmTty('\nremove it? [y/N] '))) {
console.log('cancelled');
tjs.exit(0);
}
for (const l of links) await run(['rm', '-f', l]);
await run(['rm', '-rf', installDir]);
console.log(`\nuninstalled tinyjs ${version}.`);
console.log('if the installer added a PATH line to your shell profile, delete the');
console.log('block marked "# added by tinyjs installer" (harmless if left).');
tjs.exit(0);
}
// Per-OS config: root keys apply everywhere, and an optional "macos" /
// "windows" / "linux" block is merged on top for that platform only. Block
// names match tiny.system.os() so the config vocabulary matches the runtime's.
// Plain objects merge (so "macos": { chrome: { vibrancy } } keeps a root
// chrome.frame); scalars and arrays replace outright.
const OS_KEYS = ['macos', 'windows', 'linux'];
const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
function mergeConfig(base, over) {
const out = { ...base };
for (const [k, v] of Object.entries(over ?? {})) {
out[k] = isPlainObject(v) && isPlainObject(base[k]) ? mergeConfig(base[k], v) : v;
}
return out;
}
// Env vars OVERRIDE the file — but never silently: a value exported in a shell
// quietly changing how a project signs is exactly the failure worth shouting
// about, so an override that displaces a real config value announces itself.
// [cfg path, env var] pairs; the path is dotted.
const ENV_OVERRIDES = [
['signIdentity', 'TINYJS_SIGN_IDENTITY'],
['notarize.profile', 'TINYJS_NOTARY_PROFILE'],
];
function applyEnvOverrides(cfg) {
for (const [path, envName] of ENV_OVERRIDES) {
const val = tjs.env[envName];
if (!val) continue;
const parts = path.split('.');
let node = cfg;
for (const p of parts.slice(0, -1)) {
if (!isPlainObject(node[p])) node[p] = {};
node = node[p];
}
const leaf = parts[parts.length - 1];
const had = node[leaf];
node[leaf] = val;
if (had !== undefined && had !== val) {
console.log(`==> ${path} from ${envName} (overriding tinyjs.json)`);
}
}
return cfg;
}
// An app can declare the oldest tinyjs it works with. Optional — but without
// it, running an app against a tinyjs that predates an API it uses fails as an
// unexplained TypeError in the page, with nothing naming the real cause.
// A source checkout reports 'dev' and is assumed newest, so it never trips.
async function checkMinVersion(cfg) {
const want = cfg.minTinyjsVersion;
if (!want) return;
const have = await toolVersion();
if (have === 'dev') return;
if (!parseVer(want)) return; // unparseable: not worth blocking a build over
if (isNewer(have, want)) {
fail(`${cfg.name} needs tinyjs ${want} or newer — you have ${have}.\n` +
' run `tinyjs update`, or drop "minTinyjsVersion" from tinyjs.json ' +
'if you know better.');
}
}
async function loadConfig() {
if (!(await exists('tinyjs.json'))) {
fail('no tinyjs.json here — run this from a tinyjs project (or `tinyjs new <dir>` to create one)');
}
const raw = JSON.parse(dec.decode(await tjs.readFile('tinyjs.json')));
// Resolve the platform ONCE here, so every existing cfg.* read downstream
// sees the merged value and no call site has to know about OS blocks.
const osKey = IS_WIN ? 'windows' : IS_LINUX ? 'linux' : 'macos';
const cfg = applyEnvOverrides(mergeConfig(raw, raw[osKey]));
for (const k of OS_KEYS) delete cfg[k]; // the blocks themselves aren't config
if (!cfg.name) fail('tinyjs.json needs a "name"');
if (cfg.activation && !['regular', 'accessory'].includes(cfg.activation)) {
fail('tinyjs.json "activation" must be "regular" or "accessory"');
}
if (cfg.mainWindow !== undefined && typeof cfg.mainWindow !== 'boolean') fail('tinyjs.json "mainWindow" must be a boolean');
if (cfg.mainWindow === false && cfg.url) fail('tinyjs.json "url" needs a main window to load into — drop "mainWindow": false');
cfg.resources = await validateResources(cfg.resources);
// The app icon: "icon" if set, else assets/icon.png, else icon.png at the
// project root (where projects made before assets/ keep it). Every reader
// goes through `cfg.icon || 'icon.png'`, so resolving it here covers them.
if (!cfg.icon && await exists('assets/icon.png')) cfg.icon = 'assets/icon.png';
// The help book is macOS's, but its folder sits in assets/ for every OS's
// build to see — keep the name around so they don't flag it as unused.
cfg.helpBookAnyOS = helpBookRel(cfg.helpBook ?? raw.macos?.helpBook);
await checkMinVersion(cfg);
return { title: cfg.name, size: '960x640', id: 'com.example.' + cfg.name, ...cfg };
}
// Backend entry: cfg.backend, or the first of src/backend/main.js|ts (the
// vanilla layout: backend and frontend side by side under src/), src/main.js|ts
// (the vanilla layout before 0.52, frontend nested in the backend's folder),
// backend/main.js|ts (the Vite templates). .ts entries (or any entry with
// cfg.backendBundle) are bundled with esbuild — which also makes npm packages
// usable in the backend.
async function resolveBackendEntry(cfg) {
if (cfg.backend) {
if (!(await exists(cfg.backend))) fail('backend entry not found: ' + cfg.backend);
return cfg.backend;
}
for (const p of ['src/backend/main.js', 'src/backend/main.ts', 'src/main.js', 'src/main.ts',
'backend/main.js', 'backend/main.ts']) {
if (await exists(p)) return p;
}
fail('no backend entry found (src/backend/main.js|ts, src/main.js|ts, backend/main.js|ts, or "backend" in tinyjs.json)');
}
// Code both sides import (#58): a shared/ folder beside the backend's folder
// (src/shared next to src/backend; shared/ at the root next to the Vite
// templates' backend/). It ships as app/shared, beside app/src (the backend)
// and app/frontend, so `../shared/x.js` resolves the same from both sides in
// dev and in a build. A backend at the project root has no sibling folder.
function sharedDirFor(backendEntry) {
const entry = String(backendEntry).replace(/\\/g, '/').replace(/^(\.\/)+/, '');
if (!entry.includes('/')) return null;
const entryDir = entry.replace(/\/[^/]*$/, '');
return entryDir.includes('/') ? entryDir.replace(/\/[^/]*$/, '') + '/shared' : 'shared';
}
// A frontend with its own build tooling needs its packages installed first.
// Without node_modules the script's tools come from wherever else they are
// (a global tsc, say) and fail with errors that never say "install" (#41:
// "Cannot find type definition file for 'vite/client'"). Node resolves
// packages in every parent dir (workspaces hoist them), and Yarn PnP keeps
// none at all, so either of those counts as installed.
async function ensurePackagesInstalled(cmd) {
if (!(await exists('package.json'))) return;
let d = tjs.cwd.replace(/\\/g, '/').replace(/\/+$/, '');
for (;;) {
if ((await exists(d + '/node_modules')) || (await exists(d + '/.pnp.cjs'))) return;
const up = d.replace(/\/[^/]*$/, '');
if (!up || up === d) break;
d = up;
}
fail(`no node_modules for this project, so \`${cmd}\` can't find its tools — ` +
'run `npm install` (or your package manager\'s install) first');
}
// Run esbuild on project files. The project's own copy wins (that is what
// `npx esbuild` from the project used to pick); otherwise npx fetches it —
// run from a temp dir, because npm 11 refuses npx inside a project whose
// package.json pins another package manager (devEngines.packageManager:
// pnpm — Vite+ 1.0 scaffolds write one) with EBADDEVENGINES. Paths go in
// absolute so the cwd doesn't matter to esbuild.
async function runEsbuild(entry, flags, outfile) {
const cwd = tjs.cwd.replace(/\\/g, '/').replace(/\/+$/, '');
const abs = (p) => /^([A-Za-z]:)?\//.test(p) ? p : cwd + '/' + p;
const argv = [abs(entry), ...flags, '--outfile=' + abs(outfile)];
for (let d = cwd; ;) {
const bin = d + '/node_modules/.bin/esbuild' + (IS_WIN ? '.cmd' : '');
if (await exists(bin)) return run(nodeToolArgv([bin, ...argv]));
const up = d.replace(/\/[^/]*$/, '');
if (!up || up === d) break;
d = up;
}
const tmp = await tjs.makeTempDir(tjs.tmpDir + '/tinyjs-esbuild-XXXXXX');
try {
await run(nodeToolArgv(['npx', '--yes', 'esbuild', ...argv]), { cwd: tmp });
} finally {
await tjs.remove(tmp, { recursive: true }).catch(() => {});
}
}
// Generate .build/app/: bridge + copied backend sources + an entry module,
// in the layout `tjs app compile` expects (app dir with an app.json manifest
// — it bundles the whole module graph into one executable). The frontend
// ships as real files (the launcher loads file:// documents, so relative
// css/js/images just work): dev points at src/frontend directly; build
// copies it into .build/app/frontend.
async function generateBuild(cfg, dev = false) {
await rmTree('.build');
const B = '.build/app';
await tjs.makeDir(B, { recursive: true });
await tjs.writeFile(B + '/app.json',
enc.encode(JSON.stringify({ version: 0, build: {}, main: 'entry.js' })));
await tjs.writeFile(B + '/bridge.js', await tjs.readFile(TOOL_DIR + 'runtime/bridge.js'));
await tjs.writeFile(B + '/update.js', await tjs.readFile(TOOL_DIR + 'runtime/update.js'));
// Backend: TypeScript (or any entry, with npm packages) bundles via esbuild;
// plain JS copies sources as before.
const backendEntry = await resolveBackendEntry(cfg);
const entryDir = backendEntry.includes('/') ? backendEntry.replace(/\/[^/]*$/, '') : '.';
let entryName = backendEntry.split('/').pop();
if (backendEntry.endsWith('.ts')) {
console.log('==> bundling backend (esbuild)');
await runEsbuild(backendEntry, ['--bundle', '--format=esm',
'--platform=neutral', '--main-fields=module,main',
'--external:tjs:*', '--log-level=warning'], B + '/src/main.js');
entryName = 'main.js';
} else {
// Copy the backend dir: the folder the entry sits in is the backend's
// root ("backend": "server/index.js" → server/). Minus a nested
// frontend/ (src/ layouts) and anything that isn't backend source, which
// matters once the entry sits at the project root ("backend":
// "main.js"): .build is where this copy is GOING (copying it recursed
// until ENAMETOOLONG), and node_modules / dist / .git / the frontend
// folder would bloat the app. A plain-JS backend can't import from
// node_modules anyway; bundle (a .ts entry) to use npm packages.
await tjs.makeDir(B + '/src');
const fe0 = cfg.frontend ?? {};
const skip = new Set(['frontend', '.build', 'node_modules', 'dist', '.git']);
if (entryDir === '.') {
for (const d of [fe0.dir, fe0.dist]) if (d) skip.add(String(d).replace(/^\.\//, '').split('/')[0]);
// These ship on their own paths; a copy here would put unsigned code
// in Resources/app (and duplicate the data).
for (const d of [RESOURCES_DIR, EXECUTABLES_DIR, 'assets']) skip.add(d);
}
const iter = await tjs.readDir(entryDir);
for await (const e of iter) {
if (skip.has(e.name)) continue;
const s = entryDir + '/' + e.name;
const d = B + '/src/' + e.name;
if (e.isDirectory) await copyTree(s, d);
else await tjs.writeFile(d, await tjs.readFile(s));
}
}
// shared/: copied in dev too, since the dev backend runs from .build/app/src.
// The pre-0.52 layout nests the frontend in the backend's folder, so its
// page would reach ../../shared in dev but nothing in a build.
const sharedDir = sharedDirFor(backendEntry);
if (sharedDir && await exists(sharedDir)) {
await copyTree(sharedDir, B + '/shared');
} else if (entryDir === 'src' && await exists('src/shared')) {
console.log('tinyjs: src/shared/ is only shared with a backend in src/backend/ — ' +
'move src/main.js (and the files it imports) there');
}
// tinyjs.json "inject": document-start JS injected into every window before
// the page boots (site wrappers shim capabilities/behaviour there). Bundled
// like the backend (.ts via esbuild); ships as Resources/app/inject.js in a
// packaged .app, rides the spawn env (TINYJS_INJECT) in dev.
let injectSrc = null;
if (cfg.inject) {
if (!(await exists(cfg.inject))) fail('tinyjs.json "inject": ' + cfg.inject + ' not found');
if (String(cfg.inject).endsWith('.ts')) {
console.log('==> bundling inject (esbuild)');
await runEsbuild(cfg.inject, ['--bundle', '--format=iife', '--log-level=warning'],
B + '/inject.js');
injectSrc = dec.decode(await tjs.readFile(B + '/inject.js'));
} else {
injectSrc = dec.decode(await tjs.readFile(cfg.inject));
await tjs.writeFile(B + '/inject.js', enc.encode(injectSrc));
}
}
// Frontend: optional build hook (bundlers) or plain source dir; dev with a