-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart.mjs
More file actions
1309 lines (1224 loc) · 51.3 KB
/
Copy pathstart.mjs
File metadata and controls
1309 lines (1224 loc) · 51.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
#!/usr/bin/env node
/**
* Dapp starter — full interactive setup using @clack/prompts.
* Run: node start.mjs [--template=URL] [--template-version=REF] [args for sv create]
* Update mode: node start.mjs --update [--template=URL] [--template-version=REF] (overwrites from template except vite.config.ts)
* Template version: URL can include @version (e.g. ...mota-dapp.git@1.2.3). Else use --template-version/--tv. If both omitted, uses repo default branch (git ls-remote).
*
* npm warn gitignore-fallback: We do not create .npmignore. If you see that warning, npm is using .gitignore
* for pack/publish exclusion; it is harmless. Add a .npmignore in the project to control published files and silence it.
*/
import { spawn, spawnSync } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { fileURLToPath } from 'node:url';
import {
intro,
outro,
confirm,
select,
text,
spinner,
log,
isCancel,
cancel
} from '@clack/prompts';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const STARTER_DIR = __dirname;
const TEMPLATE_URL = 'https://github.com/bchainhub/mota-dapp.git';
const MOTA_TRANSLATIONS_REPO = 'https://github.com/bchainhub/mota-translations.git';
const STARTER_REPO_RAW = 'https://cdn.jsdelivr.net/gh/bchainhub/dapp-starter';
const CORE_LICENSE_URL = 'https://cdn.jsdelivr.net/gh/bchainhub/core-license@main/LICENSE';
/** Installed on every project; kept in sync with the initial `pmAdd` / `pmAddDev` calls below. */
const STARTER_RUNTIME_PACKAGES = [
'@blockchainhub/blo', '@blockchainhub/ican', '@tailwindcss/vite',
'blockchain-wallet-validator', 'device-sherlock', 'exchange-rounding',
'@lucide/svelte', 'payto-rl', 'tailwindcss', 'txms.js', 'vite-plugin-pwa', 'zod'
];
const STARTER_DEV_TOOL_PACKAGES = ['hygen', 'tiged', 'json5', 'ejs', 'prompts'];
/** Names to skip when listing locale subfolders inside mota-translations repo i18n/ folder. */
const MOTA_TRANSLATIONS_SKIP_NAMES = new Set(['.git', 'README.md', 'LICENSE', '.gitignore', 'node_modules']);
// Ctrl+C exits immediately (including during sv create)
process.on('SIGINT', () => process.exit(130));
process.on('SIGTERM', () => process.exit(143));
// Parse argv: --update/-u, --template/-t=URL, --template-version/--tv=REF, rest passed to sv create
let templateUrl = TEMPLATE_URL;
let templateVersion = null; // alternative to URL@version; used when URL has no @ref (e.g. mota-dapp or -t without @). null = repo default branch
let updateMode = false;
const passArgs = [];
for (let i = 2; i < process.argv.length; i++) {
const arg = process.argv[i];
if (arg === '--update' || arg === '-u') {
updateMode = true;
} else if (arg === '--template' && process.argv[i + 1]) {
templateUrl = process.argv[++i];
} else if (arg === '-t' && process.argv[i + 1]) {
templateUrl = process.argv[++i];
} else if (arg.startsWith('--template=')) {
templateUrl = arg.slice('--template='.length);
} else if (arg.startsWith('-t=')) {
templateUrl = arg.slice(3);
} else if (arg === '--template-version' && process.argv[i + 1]) {
templateVersion = process.argv[++i];
} else if (arg === '--tv' && process.argv[i + 1]) {
templateVersion = process.argv[++i];
} else if (arg.startsWith('--template-version=')) {
templateVersion = arg.slice('--template-version='.length);
} else if (arg.startsWith('--tv=')) {
templateVersion = arg.slice(5);
} else {
passArgs.push(arg);
}
}
function run(cmd, args = [], opts = {}) {
// Avoid DEP0190: never use shell: true when passing args (they are concatenated, not escaped).
const spawnOpts = {
stdio: opts.inherit ? 'inherit' : 'pipe',
cwd: opts.cwd || process.cwd(),
encoding: opts.encoding,
...opts,
shell: args.length === 0 && opts.shell === true
};
const result = spawnSync(cmd, args, spawnOpts);
return result;
}
/** Run a command asynchronously so the event loop (and spinner) can run. Returns Promise<{ status }>. */
function runAsync(cmd, args = [], opts = {}) {
// Avoid DEP0190: never use shell: true when passing args.
return new Promise((resolve) => {
const spawnOpts = {
stdio: opts.stdio ?? 'pipe',
cwd: opts.cwd || process.cwd(),
...opts,
shell: args.length === 0 && opts.shell === true
};
const child = spawn(cmd, args, spawnOpts);
child.on('close', (code) => resolve({ status: code ?? 0 }));
});
}
const SPINNER_EMOJIS = ['⏳', '📦', '🚀', '✨', '🔧', '📥', '💾', '🌐', '📂', '💻', '🔍', '💼', '💿'];
/** Random emoji frames for spinner (replaces rotating bar |/-\). */
function randomEmojiFrames(n = 60) {
return Array.from({ length: n }, () => SPINNER_EMOJIS[Math.floor(Math.random() * SPINNER_EMOJIS.length)]);
}
/**
* Parse template URL; supports jsDelivr-style version at the end: URL@version (e.g. ...mota-dapp.git@1.2.3).
* Returns { baseUrl, refFromUrl }; refFromUrl is null if no @version in URL.
*/
function parseTemplateUrl(url) {
const i = url.lastIndexOf('@');
if (i <= 0) return { baseUrl: url, refFromUrl: null };
const baseUrl = url.slice(0, i);
const refFromUrl = url.slice(i + 1).trim() || null;
return { baseUrl: baseUrl || url, refFromUrl };
}
/** Get the default branch of a remote repo (e.g. main, master) via git ls-remote. */
function getDefaultBranch(repoUrl) {
const tpl = repoUrl.replace(/\.git$/, '') + '.git';
const result = run('git', ['ls-remote', '--symref', tpl, 'HEAD'], { encoding: 'utf8', stdio: 'pipe' });
const match = result.stdout?.match(/ref: refs\/heads\/(\S+)\s+HEAD/);
return match ? match[1].trim() : 'main';
}
function runNpx(args, opts = {}) {
return run('npx', ['--yes', ...args], opts);
}
function runNpxAsync(args, opts = {}) {
return runAsync('npx', ['--yes', ...args], { ...opts, stdio: opts.stdio ?? 'pipe' });
}
function appendIfMissing(filePath, pattern) {
if (!fs.existsSync(filePath)) return;
const content = fs.readFileSync(filePath, 'utf8');
if (content.includes(pattern)) return;
fs.appendFileSync(filePath, pattern + '\n');
}
function ensureLineInFile(filePath, line) {
if (!fs.existsSync(filePath)) {
fs.writeFileSync(filePath, line + '\n');
return;
}
const content = fs.readFileSync(filePath, 'utf8');
if (content.includes(line)) return;
const hasNewline = content.endsWith('\n');
fs.appendFileSync(filePath, (hasNewline ? '' : '\n') + line + '\n');
}
/** npm 7+ peer resolution; needed e.g. vite-plugin-pwa vs Vite 8 until upstream peers catch up. */
function ensureNpmLegacyPeerDeps(cwd) {
ensureLineInFile(path.join(cwd, '.npmrc'), 'legacy-peer-deps=true');
}
function addScriptsToPackageJson(pkgPath, scripts) {
if (!fs.existsSync(pkgPath)) return;
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
pkg.scripts = pkg.scripts || {};
Object.assign(pkg.scripts, scripts);
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n');
}
/**
* Template `package.json` is the source of truth. Add only starter packages that are not already listed
* in `dependencies` or `devDependencies` (semver `*` until `npm install` resolves).
*/
function addMissingStarterDependencyEntries(pkg) {
pkg.dependencies = pkg.dependencies && typeof pkg.dependencies === 'object' ? { ...pkg.dependencies } : {};
pkg.devDependencies = pkg.devDependencies && typeof pkg.devDependencies === 'object' ? { ...pkg.devDependencies } : {};
const have = new Set([
...Object.keys(pkg.dependencies),
...Object.keys(pkg.devDependencies)
]);
for (const name of STARTER_RUNTIME_PACKAGES) {
if (!have.has(name)) {
pkg.dependencies[name] = '*';
have.add(name);
}
}
for (const name of STARTER_DEV_TOOL_PACKAGES) {
if (!have.has(name)) {
pkg.devDependencies[name] = '*';
have.add(name);
}
}
return pkg;
}
/** Ensure `bin` maps exist for scripts copied to `bin/` (e.g. addon) when the template omitted them. */
function applyStarterBinToPackageJson(pkg, scriptFileNames) {
if (!scriptFileNames || scriptFileNames.length === 0) return pkg;
pkg.bin = pkg.bin && typeof pkg.bin === 'object' ? { ...pkg.bin } : {};
for (const name of scriptFileNames) {
const stem = name.replace(/\.[^.]+$/, '') || name;
if (!pkg.bin[stem]) pkg.bin[stem] = `./bin/${name}`;
}
return pkg;
}
function syncStarterIntoPackageJsonFile(pkgPath, scriptFileNames) {
if (!fs.existsSync(pkgPath)) return;
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
addMissingStarterDependencyEntries(pkg);
applyStarterBinToPackageJson(pkg, scriptFileNames);
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n');
}
/**
* Copy translation locales from mota-translations repo (repo i18n/ folder) into project src/i18n.
* Creates src/i18n if it does not exist.
* @param {string} projectCwd - Project root
* @param {string[] | 'all'} localeCodes - Array of locale codes (e.g. ['es', 'pt-br']) or 'all'
* @returns {{ success: boolean, copied: string[] }}
*/
function copyAdditionalTranslations(projectCwd, localeCodes) {
const destI18n = path.join(projectCwd, 'src', 'i18n');
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mota-translations-'));
const cloneDir = path.join(tmpDir, 'repo');
const cloneResult = run('git', ['clone', '--depth=1', MOTA_TRANSLATIONS_REPO, cloneDir], { stdio: 'ignore' });
if (cloneResult.status !== 0) {
fs.rmSync(tmpDir, { recursive: true, force: true });
return { success: false, copied: [] };
}
const repoI18n = path.join(cloneDir, 'i18n');
if (!fs.existsSync(repoI18n) || !fs.statSync(repoI18n).isDirectory()) {
fs.rmSync(tmpDir, { recursive: true, force: true });
return { success: false, copied: [] };
}
const entries = fs.readdirSync(repoI18n, { withFileTypes: true });
const availableLocales = entries
.filter((e) => e.isDirectory() && !MOTA_TRANSLATIONS_SKIP_NAMES.has(e.name))
.map((e) => e.name);
const toCopy = localeCodes === 'all'
? availableLocales
: localeCodes.filter((code) => availableLocales.includes(code));
const copied = [];
if (!fs.existsSync(destI18n)) fs.mkdirSync(destI18n, { recursive: true });
for (const locale of toCopy) {
const srcLocale = path.join(repoI18n, locale);
const destLocale = path.join(destI18n, locale);
if (!fs.existsSync(srcLocale) || !fs.statSync(srcLocale).isDirectory()) continue;
fs.mkdirSync(destLocale, { recursive: true });
const files = fs.readdirSync(srcLocale, { withFileTypes: true });
for (const f of files) {
const srcPath = path.join(srcLocale, f.name);
const destPath = path.join(destLocale, f.name);
if (f.isDirectory()) {
fs.cpSync(srcPath, destPath, { recursive: true });
} else {
fs.copyFileSync(srcPath, destPath);
}
}
copied.push(locale);
}
fs.rmSync(tmpDir, { recursive: true, force: true });
return { success: true, copied };
}
function composeReadme(opts) {
const runDev =
opts.pm === 'deno' ? 'deno task dev' :
opts.pm === 'pnpm' ? 'pnpm dev' :
opts.pm === 'yarn' ? 'yarn dev' :
opts.pm === 'bun' ? 'bun run dev' :
'npm run dev';
const installCmd =
opts.pm === 'deno' ? 'deno run npm:install' :
opts.pm === 'pnpm' ? 'pnpm install' :
opts.pm === 'yarn' ? 'yarn' :
opts.pm === 'bun' ? 'bun install' :
'npm install';
const lines = [
`# ${opts.projectName}`,
'',
'MOTA ĐApp Framework ₡ore (SvelteKit, Core Blockchain, multi-chain).',
'',
'## Overview',
'',
'- SvelteKit + MOTA stack',
'- Addon CLI: `npx addon <repo> <generator> <action>`',
'- Hidden addon control files supported: `prompt.js`, `_scripts.ejs.sh` / `_scripts.sh`, `_config.ejs.json5` / `_config.json5`'
];
if (opts.installTranslations) lines.push('- **i18n** – typesafe-i18n (see [Translations](#translations))');
if (opts.skillsSelected && opts.skillsSelected.length > 0) {
const skillLabels = [];
if (opts.skillsSelected.includes('mota')) skillLabels.push('MOTA Skills');
if (opts.skillsSelected.includes('custom') || opts.skillsSelected.includes('find')) skillLabels.push('custom/find');
lines.push('- **Agent skills** – [skills.sh](https://skills.sh/)' + (skillLabels.length ? ` (${skillLabels.join(', ')})` : ''));
}
if (opts.templateMerged && opts.templateUrl) {
lines.push(`- **Template** – \`${opts.templateUrl.replace(/\.git$/, '')}\``);
}
if (opts.copyEditorconfig) lines.push('- `.editorconfig`');
if (opts.copyCodeOfConductContributing) lines.push('- `CODE_OF_CONDUCT.md`, `CONTRIBUTING.md`');
if (opts.copyProvider === '.github') lines.push('- `.github/ISSUE_TEMPLATE`');
else if (opts.copyProvider === '.gitlab') lines.push('- `.gitlab/issue_templates`');
else if (opts.copyProvider === 'custom') lines.push('- Issue templates (custom URL)');
lines.push(
'',
'## Run dev server',
'',
'```bash',
installCmd,
runDev,
'```',
'',
'## Addons',
'',
'Install an addon:',
'',
'```bash',
'npx addon <repo> <generator> <action>',
'```',
'',
'Examples:',
'',
'```bash',
'npx addon bchainhub@mota-addon-support support install',
'npx addon owner/repo name-of-addon uninstall',
'npx addon owner/repo name-of-addon install --cache',
'npx addon owner/repo name-of-addon install --dry-run',
'```',
'',
'Addon action folders can contain:',
'',
'```text',
'<generator>/<action>/',
' prompt.js',
' *.ejs.t',
' _scripts.ejs.sh',
' _scripts.sh',
' _config.ejs.json5',
' _config.json5',
'```',
'',
'- `prompt.js` collects answers once and those values are reused in templates, scripts, and config.',
'- `*.ejs.t` are normal Hygen templates and are copied/generated into the project.',
'- `_scripts*` files are rendered/executed automatically and are never copied.',
'- `_config*` files are rendered/applied automatically and are never copied.',
'- `_config*` currently targets the `modules` block in `vite.config.ts`.',
'',
'## Resources',
'',
'- [📦 MOTA addons search](https://github.com/topics/mota-addon)',
'- [📖 MOTA skills search](https://skills.sh)',
''
);
if (opts.installTranslations) {
lines.push(
'## Translations',
'',
'i18n is provided by **typesafe-i18n**.',
'',
'- `npm run i18n:extract` – extract strings from the project',
'- `npm run i18n:watch` – watch and update translations',
''
);
}
if (opts.licenseLabel && opts.licenseLabel !== 'None') {
const licenseLine = (opts.licenseLabel === 'Other License' || opts.licenseLabel === 'Commercial Source License (CSL)')
? 'CSL or Other License. See [LICENSE](LICENSE) in the repo root.'
: `${opts.licenseLabel}. See [LICENSE](LICENSE) in the repo root.`;
lines.push('## License', '', licenseLine);
}
return lines.join('\n');
}
function detectPm(cwd) {
if (fs.existsSync(path.join(cwd, 'deno.lock'))) return 'deno';
if (fs.existsSync(path.join(cwd, 'deno.json')) || fs.existsSync(path.join(cwd, 'deno.jsonc'))) return 'deno';
if (fs.existsSync(path.join(cwd, 'pnpm-lock.yaml'))) return 'pnpm';
if (fs.existsSync(path.join(cwd, 'bun.lockb'))) return 'bun';
if (fs.existsSync(path.join(cwd, 'yarn.lock'))) return 'yarn';
return 'npm';
}
function pmAdd(cwd, pm, ...pkgs) {
if (pkgs.length === 0) return { status: 0 };
if (pm === 'deno') return run('deno', ['add', ...pkgs.map((p) => 'npm:' + p)], { cwd });
if (pm === 'pnpm') return run('pnpm', ['add', ...pkgs], { cwd });
if (pm === 'yarn') return run('yarn', ['add', ...pkgs], { cwd });
if (pm === 'bun') return run('bun', ['add', ...pkgs], { cwd });
return run('npm', ['i', ...pkgs], { cwd });
}
function pmAddDev(cwd, pm, ...pkgs) {
if (pkgs.length === 0) return { status: 0 };
if (pm === 'deno') return run('deno', ['add', ...pkgs.map((p) => 'npm:' + p)], { cwd });
if (pm === 'pnpm') return run('pnpm', ['add', '-D', ...pkgs], { cwd });
if (pm === 'yarn') return run('yarn', ['add', ...pkgs], { cwd });
if (pm === 'bun') return run('bun', ['add', '-d', ...pkgs], { cwd });
return run('npm', ['i', '-D', ...pkgs], { cwd });
}
function pmRemove(cwd, pm, pkg) {
if (pm === 'deno') return run('deno', ['remove', pkg], { cwd });
if (pm === 'pnpm') return run('pnpm', ['remove', pkg], { cwd });
if (pm === 'yarn') return run('yarn', ['remove', pkg], { cwd });
if (pm === 'bun') return run('bun', ['remove', pkg], { cwd });
return run('npm', ['uninstall', pkg], { cwd });
}
function pmInstall(cwd, pm) {
if (pm === 'deno') return run('deno', ['run', 'npm:install'], { cwd });
if (pm === 'pnpm') return run('pnpm', ['install'], { cwd });
if (pm === 'yarn') return run('yarn', ['install'], { cwd });
if (pm === 'bun') return run('bun', ['install'], { cwd });
return run('npm', ['install'], { cwd });
}
/**
* @param {string} cwd
* @param {string} pm
* @param {string | string[]} pkgs - package name(s)
* @param {{ stdio?: 'pipe' | 'inherit' }} [opts] - use `inherit` for long installs so output isn’t buffered and npm errors are visible
*/
async function pmAddAsync(cwd, pm, pkgs, opts = {}) {
const list = Array.isArray(pkgs) ? pkgs : [pkgs];
if (list.length === 0) return { status: 0 };
const stdio = opts.stdio ?? 'pipe';
if (pm === 'deno') return runAsync('deno', ['add', ...list.map((p) => 'npm:' + p)], { cwd, stdio });
if (pm === 'pnpm') return runAsync('pnpm', ['add', ...list], { cwd, stdio });
if (pm === 'yarn') return runAsync('yarn', ['add', ...list], { cwd, stdio });
if (pm === 'bun') return runAsync('bun', ['add', ...list], { cwd, stdio });
return runAsync('npm', ['install', ...list], { cwd, stdio });
}
/** @param {{ stdio?: 'pipe' | 'inherit' }} [opts] */
async function pmAddDevAsync(cwd, pm, pkgs, opts = {}) {
const list = Array.isArray(pkgs) ? pkgs : [pkgs];
if (list.length === 0) return { status: 0 };
const stdio = opts.stdio ?? 'pipe';
if (pm === 'deno') return runAsync('deno', ['add', ...list.map((p) => 'npm:' + p)], { cwd, stdio });
if (pm === 'pnpm') return runAsync('pnpm', ['add', '-D', ...list], { cwd, stdio });
if (pm === 'yarn') return runAsync('yarn', ['add', '-D', ...list], { cwd, stdio });
if (pm === 'bun') return runAsync('bun', ['add', '-d', ...list], { cwd, stdio });
return runAsync('npm', ['install', '-D', ...list], { cwd, stdio });
}
async function pmInstallAsync(cwd, pm) {
if (pm === 'deno') return runAsync('deno', ['run', 'npm:install'], { cwd, stdio: 'pipe' });
if (pm === 'pnpm') return runAsync('pnpm', ['install'], { cwd, stdio: 'pipe' });
if (pm === 'yarn') return runAsync('yarn', ['install'], { cwd, stdio: 'pipe' });
if (pm === 'bun') return runAsync('bun', ['install'], { cwd, stdio: 'pipe' });
return runAsync('npm', ['install'], { cwd, stdio: 'pipe' });
}
/**
* @param {string} cwd
* @param {string} pm
* @param {string} script
* @param {string[]} [args]
* @param {{ stdio?: 'pipe' | 'ignore' }} [opts] - Use stdio: 'ignore' so child doesn't block on stdin or affect terminal (e.g. for i18n:extract before more prompts).
*/
function pmRun(cwd, pm, script, args = [], opts = {}) {
const stdio = opts.stdio ?? 'pipe';
if (pm === 'deno') return run('deno', ['task', script, ...args], { cwd, stdio });
if (pm === 'pnpm') return run('pnpm', ['run', script, ...args], { cwd, stdio });
if (pm === 'yarn') return run('yarn', [script, ...args], { cwd, stdio });
if (pm === 'bun') return run('bun', ['run', script, ...args], { cwd, stdio });
return run('npm', ['run', script, ...args], { cwd, stdio });
}
/** Async pmRun so event loop runs during execution (keeps TTY responsive for next prompts). Returns Promise<{ status }>. */
async function pmRunAsync(cwd, pm, script, args = [], opts = {}) {
const stdio = opts.stdio ?? 'pipe';
if (pm === 'deno') return runAsync('deno', ['task', script, ...args], { cwd, stdio });
if (pm === 'pnpm') return runAsync('pnpm', ['run', script, ...args], { cwd, stdio });
if (pm === 'yarn') return runAsync('yarn', [script, ...args], { cwd, stdio });
if (pm === 'bun') return runAsync('bun', ['run', script, ...args], { cwd, stdio });
return runAsync('npm', ['run', script, ...args], { cwd, stdio });
}
function getProjectDir() {
const cwd = process.cwd();
if (
fs.existsSync(path.join(cwd, 'package.json')) &&
(fs.existsSync(path.join(cwd, 'svelte.config.js')) || fs.existsSync(path.join(cwd, 'svelte.config.ts')))
) {
return '.';
}
const entries = fs.readdirSync(cwd, { withFileTypes: true });
let best = null;
let bestTime = 0;
for (const e of entries) {
if (!e.isDirectory()) continue;
const dir = e.name;
const pj = path.join(cwd, dir, 'package.json');
const sc = path.join(cwd, dir, 'svelte.config.js');
const st = path.join(cwd, dir, 'svelte.config.ts');
if (!fs.existsSync(pj)) continue;
if (!fs.existsSync(sc) && !fs.existsSync(st)) continue;
const stat = fs.statSync(path.join(cwd, dir));
const mtime = stat.mtimeMs || 0;
if (mtime > bestTime) {
bestTime = mtime;
best = dir;
}
}
return best || '.';
}
async function runUpdateMode(tplUrl, tplVersion = null) {
intro('Update from template');
const cwd = process.cwd();
const vitePath = path.join(cwd, 'vite.config.ts');
let viteBackup = null;
if (fs.existsSync(vitePath)) {
viteBackup = fs.readFileSync(vitePath, 'utf8');
}
const doCommit = await confirm({
message: 'Create a git commit before updating (breakpoint)?',
initialValue: true
});
if (!isCancel(doCommit) && doCommit) {
const addResult = run('git', ['add', '-A'], { cwd, stdio: 'pipe' });
const commitResult = run('git', ['commit', '-m', 'MOTA update checkpoint 💾'], { cwd, stdio: 'pipe' });
if (commitResult.status !== 0) {
log.warn('Nothing to commit or commit failed. Continuing.');
} else {
log.success('Checkpoint commit created.');
}
}
const s1 = spinner({ frames: randomEmojiFrames(), delay: 300 });
const { baseUrl, refFromUrl } = parseTemplateUrl(tplUrl);
const tpl = baseUrl.replace(/\.git$/, '') + '.git';
const ref = refFromUrl ?? tplVersion ?? getDefaultBranch(tpl);
s1.start(`Cloning template (${ref})`);
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sv-starter-update-'));
const cloneDir = path.join(tmpDir, 'clone');
const cloneArgs = ['clone', '--depth=1', '-b', ref, tpl, cloneDir];
const cloneResult = run('git', cloneArgs, { stdio: 'pipe' });
if (cloneResult.status !== 0) {
s1.stop('Clone failed.');
log.error('Failed to clone template.');
fs.rmSync(tmpDir, { recursive: true, force: true });
process.exit(1);
}
s1.stop('Template cloned.');
s1.start('Copying files (excluding vite.config.ts, src/i18n, src/routes/[[lang]]/+page.svelte, static, src/css, src/data)');
const tarExcludes = [
'.git', 'node_modules', 'src/i18n', 'static', 'src/css', 'src/data',
'src/routes/[[lang]]/+page.svelte'
].map((e) => `--exclude='${e}'`);
run('sh', ['-c', `(cd "${cloneDir}" && tar -cf - ${tarExcludes.join(' ')} .) | tar -xf - -C "${cwd}"`], { stdio: 'pipe' });
if (viteBackup !== null) {
fs.writeFileSync(vitePath, viteBackup);
}
fs.rmSync(tmpDir, { recursive: true, force: true });
s1.stop('Done.');
log.success('Project updated from template. vite.config.ts, src/i18n, src/routes/[[lang]]/+page.svelte, static, src/css, and src/data were preserved.');
outro('Update complete.');
}
async function main() {
if (updateMode) {
await runUpdateMode(templateUrl, templateVersion);
return;
}
intro('MOTA - ĐApp Starter 🖋️');
const s1 = spinner({ frames: randomEmojiFrames(), delay: 300 });
s1.start('Creating SvelteKit project');
const svResult = run('npx', ['sv', 'create', ...passArgs], { stdio: 'inherit' });
s1.stop(svResult.status === 0 ? 'SvelteKit project created.' : 'sv create finished.');
if (svResult.status !== 0) {
log.error('sv create failed.');
process.exit(1);
}
s1.start('Preparing');
const projectDir = getProjectDir();
log.step(`Project directory: ${projectDir}`);
process.chdir(projectDir);
// We do not create .npmignore. If you see "npm warn gitignore-fallback", npm is using .gitignore
// for pack/publish exclusion; the warning is harmless. Add a .npmignore yourself to control published files.
const npmrcPath = path.join(process.cwd(), '.npmrc');
const pm = detectPm(process.cwd());
if (pm === 'npm') {
ensureNpmLegacyPeerDeps(process.cwd());
} else if (fs.existsSync(npmrcPath)) {
fs.unlinkSync(npmrcPath);
}
log.step(`Package manager: ${pm}`);
s1.stop('Ready.');
// Do not run the clack spinner during `npm install`: it redraws the TTY and can hide/fight the child process.
// Use inherited stdio so npm output streams to the terminal (avoids pipe buffer stalls and silent failures).
log.step('Installing base packages (showing package manager output)…');
const baseRun = await pmAddAsync(process.cwd(), pm, STARTER_RUNTIME_PACKAGES, { stdio: 'inherit' });
if (baseRun.status !== 0) {
log.error(`Starter runtime packages failed to install (exit ${baseRun.status}).`);
process.exit(1);
}
const baseDevRun = await pmAddDevAsync(process.cwd(), pm, STARTER_DEV_TOOL_PACKAGES, { stdio: 'inherit' });
if (baseDevRun.status !== 0) {
log.error(`Starter dev tooling failed to install (exit ${baseDevRun.status}).`);
process.exit(1);
}
log.success('Base packages and addon tooling installed.');
fs.mkdirSync(path.join(process.cwd(), 'bin'), { recursive: true });
const scriptsDir = path.join(STARTER_DIR, 'scripts');
if (!fs.existsSync(scriptsDir)) {
log.error('Starter scripts folder not found. Ensure scripts/ exists next to start.mjs.');
process.exit(1);
}
const scriptFiles = fs.readdirSync(scriptsDir, { withFileTypes: true })
.filter((d) => d.isFile())
.map((d) => d.name);
if (scriptFiles.length === 0) {
log.error('No files in scripts/. Add at least one script (e.g. addon.mjs).');
process.exit(1);
}
for (const name of scriptFiles) {
const src = path.join(scriptsDir, name);
const dest = path.join(process.cwd(), 'bin', name);
fs.writeFileSync(dest, fs.readFileSync(src, 'utf8'), { mode: 0o755 });
}
log.success('Created ' + scriptFiles.map((n) => 'bin/' + n).join(', '));
ensureLineInFile(path.join(process.cwd(), '.gitignore'), '/bin/');
const pkgPath = path.join(process.cwd(), 'package.json');
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
pkg.bin = pkg.bin || {};
for (const name of scriptFiles) {
const stem = name.replace(/\.[^.]+$/, '') || name;
pkg.bin[stem] = `./bin/${name}`;
}
pkg.devDependencies = pkg.devDependencies || {};
pkg.devDependencies.hygen = pkg.devDependencies.hygen || '*';
pkg.devDependencies.tiged = pkg.devDependencies.tiged || '*';
pkg.devDependencies.json5 = pkg.devDependencies.json5 || '*';
pkg.devDependencies.ejs = pkg.devDependencies.ejs || '*';
pkg.devDependencies.prompts = pkg.devDependencies.prompts || '*';
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n');
s1.start('Running package install');
await pmInstallAsync(process.cwd(), pm);
s1.stop('Package install done.');
const installTranslations = await confirm({
message: 'Install translations using typesafe-i18n?',
initialValue: true
});
if (isCancel(installTranslations)) {
cancel('Cancelled.');
process.exit(0);
}
/** User choice for additional locales: null = not asked, [] = none, ['all'] or ['es','pt-br',...] */
let additionalTranslationLocales = null;
if (installTranslations) {
s1.start('Installing typesafe-i18n');
const i18nAdd = await pmAddAsync(process.cwd(), pm, 'typesafe-i18n');
if (i18nAdd.status !== 0) {
log.error(`typesafe-i18n failed to install (exit ${i18nAdd.status}).`);
process.exit(1);
}
addScriptsToPackageJson(pkgPath, {
'typesafe-i18n': 'typesafe-i18n',
'i18n:extract': 'typesafe-i18n --no-watch',
'i18n:watch': 'typesafe-i18n'
});
s1.stop('typesafe-i18n installed.');
// i18n types are initialized after template merge and/or additional translations (so all languages are present)
const additionalInput = await text({
message: 'Install additional translations from bchainhub/mota-translations?',
placeholder: 'es, pt-br, ja or "all" or "none"',
validate: (value) => {
const v = (value || '').trim().toLowerCase();
if (v === '' || v === 'none') return undefined;
if (v === 'all') return undefined;
const parts = v.split(',').map((s) => s.trim()).filter(Boolean);
if (parts.some((p) => !/^[a-z]{2}(-[a-z0-9]{2,8})?$/i.test(p))) {
return 'Use comma-separated locale codes (e.g. es, pt-br), or "all", or "none"/empty.';
}
return undefined;
}
});
if (!isCancel(additionalInput)) {
const v = (additionalInput || '').trim().toLowerCase();
if (v === '' || v === 'none') {
additionalTranslationLocales = [];
} else if (v === 'all') {
additionalTranslationLocales = ['all'];
} else {
additionalTranslationLocales = v.split(',').map((s) => s.trim()).filter(Boolean);
}
} else {
additionalTranslationLocales = [];
}
}
log.info('Agent skills: https://skills.sh/');
const skillChoice = await select({
message: 'Add agent skills?',
options: [
{ value: 'none', label: 'None (skip)' },
{ value: 'find', label: 'Interactive search (npx skills find) – discover and add skills' },
{ value: 'mota', label: 'MOTA Skills (bchainhub/mota-skills)' },
{ value: 'custom', label: 'Add your own repo (owner/repo)' }
],
initialValue: 'none'
});
if (isCancel(skillChoice)) {
cancel('Cancelled.');
process.exit(0);
}
const selections = skillChoice === 'none' ? [] : [skillChoice];
if (skillChoice === 'find') {
runNpx(['skills', 'find'], { cwd: process.cwd(), stdio: 'inherit' });
} else if (skillChoice === 'mota') {
runNpx(['skills', 'add', 'bchainhub/mota-skills'], { cwd: process.cwd(), stdio: 'inherit' });
for (;;) {
const another = await text({ message: 'Add another skill repo? (empty to finish)', placeholder: 'owner/repo' });
if (isCancel(another) || !another || !another.trim()) break;
runNpx(['skills', 'add', another.trim()], { cwd: process.cwd(), stdio: 'inherit' });
}
} else if (skillChoice === 'custom') {
let repo = await text({ message: 'Repo (owner/repo or URL; empty to skip)', placeholder: 'owner/repo' });
if (!isCancel(repo) && repo && repo.trim()) {
runNpx(['skills', 'add', repo.trim()], { cwd: process.cwd(), stdio: 'inherit' });
for (;;) {
repo = await text({ message: 'Another repo (empty to finish)', placeholder: '' });
if (isCancel(repo) || !repo || !repo.trim()) break;
runNpx(['skills', 'add', repo.trim()], { cwd: process.cwd(), stdio: 'inherit' });
}
}
}
const hasSkills = skillChoice !== 'none';
let ignoreSkills = false;
if (hasSkills) {
const ignoreSkillsAnswer = await confirm({
message: 'Add .agents/ and skills-lock.json to .gitignore?',
initialValue: true
});
ignoreSkills = !isCancel(ignoreSkillsAnswer) && ignoreSkillsAnswer;
if (ignoreSkills) {
const gi = path.join(process.cwd(), '.gitignore');
let gic = fs.existsSync(gi) ? fs.readFileSync(gi, 'utf8') : '';
if (!gic.includes('# AI Agents')) {
fs.appendFileSync(gi, (gic.endsWith('\n') ? '' : '\n') + '# AI Agents\n');
}
appendIfMissing(gi, '/.agents/');
appendIfMissing(gi, '/skills-lock.json');
log.success('Added .agents/ and skills-lock.json to .gitignore');
}
}
let templateMerged = false;
if (templateUrl) {
const { baseUrl } = parseTemplateUrl(templateUrl);
const normalizedDefault = TEMPLATE_URL.replace(/\.git$/, '');
const normalizedCurrent = baseUrl.replace(/\.git$/, '');
const isDefaultTemplate = normalizedCurrent === normalizedDefault;
let doTemplate = isDefaultTemplate;
if (!isDefaultTemplate) {
const templateLabel = templateVersion ? `${templateUrl} @ ${templateVersion}` : templateUrl;
const answer = await confirm({
message: `Merge template from ${templateLabel}?`,
initialValue: true
});
doTemplate = !isCancel(answer) && answer;
}
if (doTemplate) {
const defaultPage = path.join(process.cwd(), 'src', 'routes', '+page.svelte');
if (fs.existsSync(defaultPage)) fs.unlinkSync(defaultPage);
const { baseUrl, refFromUrl } = parseTemplateUrl(templateUrl);
const tpl = baseUrl.replace(/\.git$/, '') + '.git';
const ref = refFromUrl ?? templateVersion ?? getDefaultBranch(tpl);
// Don't run spinner during blocking git/tar so TTY state stays clean for later prompts
log.step(`Cloning and merging template (${ref})`);
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sv-starter-'));
const cloneDir = path.join(tmpDir, 'clone');
const cloneArgs = ['clone', '--depth=1', '-b', ref, tpl, cloneDir];
const cloneResult = run('git', cloneArgs, { stdio: 'ignore' });
if (cloneResult.status === 0) {
const projectCwd = process.cwd();
const pkgPathForMerge = path.join(projectCwd, 'package.json');
run('sh', ['-c', `(cd "${cloneDir}" && tar -cf - --exclude=.git --exclude=node_modules .) | tar -xf - -C "${projectCwd}"`], { stdio: 'pipe' });
const pkgFromTemplate = JSON.parse(fs.readFileSync(pkgPathForMerge, 'utf8'));
addMissingStarterDependencyEntries(pkgFromTemplate);
applyStarterBinToPackageJson(pkgFromTemplate, scriptFiles);
fs.writeFileSync(pkgPathForMerge, JSON.stringify(pkgFromTemplate, null, 2) + '\n');
if (pm === 'npm') ensureNpmLegacyPeerDeps(projectCwd);
templateMerged = true;
log.success('MOTA template merged.');
s1.start('Installing dependencies');
await pmInstallAsync(process.cwd(), pm);
s1.stop('Dependencies installed.');
// Copy additional translations from mota-translations when user chose some (no spinner during blocking git clone to avoid TTY corruption)
if (installTranslations && additionalTranslationLocales !== null) {
const wantAll = additionalTranslationLocales.length === 1 && additionalTranslationLocales[0] === 'all';
const toInstall = wantAll ? 'all' : additionalTranslationLocales;
if (toInstall === 'all' || toInstall.length > 0) {
log.step('Copying additional translations from mota-translations');
const { success, copied } = copyAdditionalTranslations(projectCwd, toInstall);
if (success && copied.length > 0) {
log.success(`Copied locales: ${copied.join(', ')}`);
} else if (!success) {
log.warn('Failed to clone or copy from mota-translations.');
} else {
log.success('Additional translations done.');
}
}
}
// i18n:extract is run after all prompts (below) so the TTY/spinner state is not corrupted.
} else {
log.error('Failed to clone template.');
}
fs.rmSync(tmpDir, { recursive: true, force: true });
log.success('Template merge done.');
}
}
// When user skipped template merge: copy additional translations if any. i18n:extract runs after all prompts (below).
if (!templateMerged && installTranslations && additionalTranslationLocales !== null) {
const wantAll = additionalTranslationLocales.length === 1 && additionalTranslationLocales[0] === 'all';
const toInstall = wantAll ? 'all' : additionalTranslationLocales;
if (toInstall === 'all' || toInstall.length > 0) {
log.step('Copying additional translations from mota-translations');
const { success, copied } = copyAdditionalTranslations(process.cwd(), toInstall);
if (success && copied.length > 0) log.success(`Copied locales: ${copied.join(', ')}`);
else if (!success) log.warn('Failed to clone or copy from mota-translations.');
else log.success('Additional translations done.');
}
}
if (!fs.existsSync(path.join(process.cwd(), '.git'))) {
run('git', ['init'], { stdio: 'pipe' });
log.success('Initialized git repository.');
}
const excludeLockfiles = await confirm({
message: 'Exclude lock files via .gitignore (cleaner, avoid cross-PM conflicts)?',
initialValue: true
});
if (!isCancel(excludeLockfiles)) {
const gi = path.join(process.cwd(), '.gitignore');
if (!fs.existsSync(gi)) fs.writeFileSync(gi, '');
const extras = [
'', '# Extra ignores', '._*', 'npm-debug.log*', 'yarn-debug.log*',
'yarn-error.log*', 'pnpm-debug.log*', 'pnpm-error.log*', 'bun-debug.log*', 'lerna-debug.log*',
'*.log', '*.log.*', 'logs', '*.pid', '*.seed', '*.pid.lock',
'', '# Editor folders', '/.idea/', '/.vscode/', '/.history/', '/.swp', '/*.sublime-workspace', '/*.sublime-project',
'', '# Addon cache', '/.addon-cache/', '/.hygen-tmp-*', '/_templates/',
'', '# Output files', '/.output/', '/.vercel/', '/.netlify/', '/.wrangler/', '/.svelte-kit/', '/build/',
'', '# Wrangler', '/wrangler.toml', '/wrangler.jsonc',
'', '# Migration files', '/_migrations/', '/better-auth_migrations/'
];
for (const line of extras) {
if (line === '' || line.startsWith('#')) fs.appendFileSync(gi, line + '\n');
else appendIfMissing(gi, line);
}
if (excludeLockfiles) {
fs.appendFileSync(gi, '\n# Lock files\n');
for (const lock of ['/package-lock.json', '/pnpm-lock.yaml', '/yarn.lock', '/bun.lockb', '/deno.lock', '/npm-shrinkwrap.json', '/shrinkwrap.yaml', '/.pnp.cjs', '/.pnp.loader.mjs']) {
appendIfMissing(gi, lock);
}
}
log.success('Updated .gitignore');
}
const copyEditorconfig = await confirm({
message: 'Copy .editorconfig from starter repo?',
initialValue: true
});
if (!isCancel(copyEditorconfig) && copyEditorconfig) {
try {
const res = await fetch(`${STARTER_REPO_RAW}/data/.editorconfig`);
if (res.ok) {
fs.writeFileSync(path.join(process.cwd(), '.editorconfig'), await res.text());
log.success('.editorconfig copied.');
}
} catch {
log.error('Failed to fetch .editorconfig');
}
}
const copyCodeOfConductContributing = await confirm({
message: 'Copy CODE_OF_CONDUCT.md and CONTRIBUTING.md from starter repo?',
initialValue: false
});
const providerChoice = await select({
message: 'Add provider-specific issue templates?',
options: [
{ value: '0', label: 'None (skip)' },
{ value: 'github', label: '.github (GitHub issue templates)' },
{ value: 'gitlab', label: '.gitlab (GitLab issue templates)' },
{ value: 'custom', label: 'Custom URL (paste base URL)' }
],
initialValue: '0'
});
let providerCopied = ''; // e.g. '.github', '.gitlab', 'custom'
if (providerChoice && providerChoice !== '0' && !isCancel(providerChoice)) {
let baseUrl;
let files;
let destDir;
let localProviderDir = null;
if (providerChoice === 'github') {
baseUrl = `${STARTER_REPO_RAW}/providers/.github/ISSUE_TEMPLATE`;
files = ['bug.yml', 'feature.yml', 'config.yml'];
destDir = path.join(process.cwd(), '.github', 'ISSUE_TEMPLATE');
localProviderDir = path.join(STARTER_DIR, 'providers', '.github', 'ISSUE_TEMPLATE');
providerCopied = '.github';
} else if (providerChoice === 'gitlab') {
baseUrl = `${STARTER_REPO_RAW}/providers/.gitlab/issue_templates`;
files = ['bug_report.md', 'feature_request.md'];
destDir = path.join(process.cwd(), '.gitlab', 'issue_templates');
localProviderDir = path.join(STARTER_DIR, 'providers', '.gitlab', 'issue_templates');
providerCopied = '.gitlab';
} else if (providerChoice === 'custom') {
const urlInput = await text({
message: 'Base URL for issue templates',
placeholder: 'e.g. https://.../providers/.github/ISSUE_TEMPLATE or .../providers/.gitlab/issue_templates'
});
const rawUrl = !isCancel(urlInput) && typeof urlInput === 'string' ? urlInput.trim() : '';
if (!rawUrl) {
log.warn('No URL provided. Skipping provider templates.');
} else {
const structure = await select({
message: 'Structure to copy',
options: [
{ value: 'github', label: '.github (bug.yml, feature.yml, config.yml)' },
{ value: 'gitlab', label: '.gitlab (bug_report.md, feature_request.md)' }
],
initialValue: 'github'
});
if (!isCancel(structure) && structure) {
baseUrl = rawUrl.replace(/\/$/, '');
if (structure === 'github') {
files = ['bug.yml', 'feature.yml', 'config.yml'];
destDir = path.join(process.cwd(), '.github', 'ISSUE_TEMPLATE');
} else {
files = ['bug_report.md', 'feature_request.md'];
destDir = path.join(process.cwd(), '.gitlab', 'issue_templates');
}
providerCopied = 'custom';
}
}
}
if (providerCopied && baseUrl && files && destDir) {
fs.mkdirSync(destDir, { recursive: true });
let ok = 0;
const useLocal = localProviderDir && fs.existsSync(localProviderDir);
for (const f of files) {
try {
let copied = false;
if (useLocal) {
const localPath = path.join(localProviderDir, f);
if (fs.existsSync(localPath)) {
fs.writeFileSync(path.join(destDir, f), fs.readFileSync(localPath, 'utf8'));
copied = true;
ok++;
}
}
if (!copied) {
const res = await fetch(`${baseUrl}/${f}`);
if (res.ok) {
fs.writeFileSync(path.join(destDir, f), await res.text());
ok++;
}
}