-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.ts
More file actions
1427 lines (1317 loc) · 40.1 KB
/
cli.ts
File metadata and controls
1427 lines (1317 loc) · 40.1 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 { basename, dirname, join } from '../platform/path.ts';
import ts from 'typescript';
import {
buildProject,
type BuildProjectArtifacts,
type BuildProjectOptions,
type BuildProjectResult,
} from '../build/build_package.ts';
import { formatDiagnostics, type MergedDiagnostic } from '../checker/diagnostics.ts';
import {
type CompileArtifacts,
compileProject,
type CompileProjectOptions,
type CompileProjectResult,
} from '../compiler/compile_project.ts';
import {
expandProject,
type ExpandProjectArtifacts,
type ExpandProjectOptions,
type ExpandProjectResult,
} from '../frontend/expand_project.ts';
import {
type BuildCommand,
type DenoCommand,
type EditorProjectCommand,
type InitCommand,
type OutputFormat,
parseCommand,
} from '../project/config.ts';
import {
getDiagnosticDocsUrl,
type MachineDiagnostic,
toMachineDiagnostic,
} from '../diagnostics/diagnostic_metadata.ts';
import {
type DiagnosticRepairExample,
type DiagnosticSuggestion,
getDiagnosticReference,
} from '../diagnostics/diagnostic_reference.ts';
import {
createTempDirectory,
fileExistsSync,
type HostFileSystemWatchEvent,
makeDirectory,
readStdinText,
removePath,
runCommand,
runtimeCwd,
watchFileSystem,
writeStdout,
writeTextFile,
} from '../platform/host.ts';
import {
materializeRuntimeGraph,
type MaterializeRuntimeGraphArtifacts,
} from '../runtime/materialize.ts';
import { runProgram, type RunProgramOptions, type RunProgramResult } from './run_program.ts';
import { projectEditorFile } from '../editor/editor_projection.ts';
import { VERSION } from '../version.ts';
export { VERSION } from '../version.ts';
const FINDINGS_EXIT_CODE = 1;
const CLI_FAILURE_EXIT_CODE = 2;
export interface CliResult {
exitCode: number;
output: string;
diagnostics: MergedDiagnostic[];
projectPath: string;
workingDirectory: string;
}
export interface CliDependencies {
buildProject?: (options: BuildProjectOptions) => Promise<BuildProjectResult>;
compileProject?: (options: CompileProjectOptions) => CompileProjectResult;
expandProject?: (options: ExpandProjectOptions) => Promise<ExpandProjectResult>;
runSubprocess?: (
command: string,
args: readonly string[],
cwd: string,
) => Promise<{ exitCode: number; output: string }>;
runProgram?: (options: RunProgramOptions) => RunProgramResult;
watchFileSystem?: (path: string) => AsyncIterable<HostFileSystemWatchEvent>;
}
type MachineReadableCommand = 'build' | 'check' | 'cli' | 'compile' | 'expand' | 'explain';
interface JsonSummary {
total: number;
errors: number;
warnings: number;
messages: number;
}
interface JsonCliOutput {
schemaVersion: 1;
toolVersion: string;
command: MachineReadableCommand;
projectPath: string;
workingDirectory: string;
exitCode: number;
summary: JsonSummary;
diagnostics: MachineDiagnostic[];
artifacts?: BuildProjectArtifacts | CompileArtifacts | ExpandProjectArtifacts;
}
interface NdjsonRunEvent {
event: 'run';
schemaVersion: 1;
toolVersion: string;
command: MachineReadableCommand;
projectPath: string;
workingDirectory: string;
}
interface NdjsonDiagnosticEvent {
event: 'diagnostic';
diagnostic: MachineDiagnostic;
}
interface NdjsonSummaryEvent {
event: 'summary';
schemaVersion: 1;
toolVersion: string;
command: MachineReadableCommand;
projectPath: string;
workingDirectory: string;
exitCode: number;
summary: JsonSummary;
artifacts?: BuildProjectArtifacts | CompileArtifacts | ExpandProjectArtifacts;
}
interface JsonExplainOutput {
schemaVersion: 1;
toolVersion: string;
command: 'explain';
code: string;
title: string;
summary: string;
details: string[];
docsUrl?: string;
examples?: DiagnosticRepairExample[];
repairHeuristic?: string;
suggestions: DiagnosticSuggestion[];
}
interface JsonEditorProjectOutput {
schemaVersion: 1;
toolVersion: string;
command: 'editor-project';
filePath: string;
projectPath: string;
originalText: string;
postRewriteStage?: ReturnType<typeof projectEditorFile>['postRewriteStage'];
projectedText: string;
rewriteStage: ReturnType<typeof projectEditorFile>['rewriteStage'];
virtualModules: ReturnType<typeof projectEditorFile>['virtualModules'];
}
function createCliDiagnostic(
code: string,
message: string,
filePath?: string,
details?: Pick<MergedDiagnostic, 'hint' | 'notes'>,
): MergedDiagnostic {
return {
source: 'cli',
code,
category: 'error',
message,
notes: details?.notes,
hint: details?.hint,
filePath,
line: 1,
column: 1,
endLine: 1,
endColumn: 1,
};
}
function isOutputFormatValue(value: string | undefined): value is OutputFormat {
return value === 'json' || value === 'ndjson' || value === 'text';
}
function detectRequestedOutputFormat(args: readonly string[]): OutputFormat {
for (let index = 0; index < args.length; index += 1) {
if (args[index] !== '--format') {
continue;
}
const value = args[index + 1];
if (isOutputFormatValue(value)) {
return value;
}
}
return 'text';
}
function detectRequestedCommand(args: readonly string[]): MachineReadableCommand {
const subcommand = args[0];
if (
subcommand === 'build' || subcommand === 'check' || subcommand === 'compile' ||
subcommand === 'expand' ||
subcommand === 'explain'
) {
return subcommand;
}
return 'cli';
}
function pathExists(path: string): boolean {
return fileExistsSync(path);
}
function toSoundscriptIncludePattern(pattern: string): string | undefined {
if (pattern.includes('.sts') || pattern.endsWith('.d.ts')) {
return undefined;
}
if (pattern.endsWith('.ts')) {
return `${pattern.slice(0, -3)}.sts`;
}
if (pattern.endsWith('.tsx')) {
return `${pattern.slice(0, -4)}.sts`;
}
return undefined;
}
function toSoundscriptIncludePatternForFile(filePath: string): string | undefined {
if (filePath.endsWith('.d.ts') || filePath.endsWith('.sts')) {
return undefined;
}
if (!filePath.endsWith('.ts') && !filePath.endsWith('.tsx')) {
return undefined;
}
const directory = dirname(filePath);
return directory === '.' ? '*.sts' : join(directory, '**', '*.sts');
}
function deriveExistingProjectInclude(baseProjectPath: string): readonly string[] | undefined {
const configFile = ts.readConfigFile(baseProjectPath, ts.sys.readFile);
if (configFile.error) {
return undefined;
}
const rawConfig = configFile.config as {
files?: readonly string[];
include?: readonly string[];
} | undefined;
if (rawConfig?.include) {
const include = [...rawConfig.include];
const augmentedInclude = new Set(include);
for (const pattern of rawConfig.include) {
const soundscriptPattern = toSoundscriptIncludePattern(pattern);
if (soundscriptPattern) {
augmentedInclude.add(soundscriptPattern);
}
}
return augmentedInclude.size === include.length ? undefined : [...augmentedInclude];
}
if (!rawConfig?.files) {
return undefined;
}
const include = new Set<string>();
for (const filePath of rawConfig.files) {
const soundscriptPattern = toSoundscriptIncludePatternForFile(filePath);
if (soundscriptPattern) {
include.add(soundscriptPattern);
}
}
return include.size === 0 ? undefined : [...include];
}
async function runEditorProjectCommand(command: EditorProjectCommand): Promise<CliResult> {
const fileOverrides = command.useStdin
? new Map([[command.filePath, await readStdinText()]])
: new Map<string, string>();
const projection = projectEditorFile({
fileOverrides,
filePath: command.filePath,
projectPath: command.projectPath,
});
const payload: JsonEditorProjectOutput = {
schemaVersion: 1,
toolVersion: VERSION,
command: 'editor-project',
filePath: projection.filePath,
originalText: projection.originalText,
postRewriteStage: projection.postRewriteStage,
projectedText: projection.projectedText,
projectPath: projection.projectPath,
rewriteStage: projection.rewriteStage,
virtualModules: projection.virtualModules,
};
return {
exitCode: 0,
output: `${JSON.stringify(payload, null, 2)}\n`,
diagnostics: [],
projectPath: command.projectPath,
workingDirectory: command.workingDirectory,
};
}
function renderHelp(): string {
return [
'soundscript',
'',
'Usage:',
' soundscript init [--mode <new|existing>]',
' soundscript build [--project <path>] [--target <js-browser|js-node|wasm-browser|wasm-node|wasm-wasi>] [--out-dir <path>] [--references] [--watch] [--verbose] [--format <text|json|ndjson>]',
' soundscript check [--project <path>] [--target <js-browser|js-node|wasm-browser|wasm-node|wasm-wasi>] [--format <text|json|ndjson>] [--references] [--no-cache] [--cache-dir <path>]',
' soundscript compile [--project <path>] [--target <js-browser|js-node|wasm-browser|wasm-node|wasm-wasi>] [--format <text|json|ndjson>]',
' soundscript deno <run|test> [...]',
' soundscript expand [--project <path>] [--target <js-browser|js-node|wasm-browser|wasm-node|wasm-wasi>] [--out-dir <path>] [--format <text|json|ndjson>]',
' soundscript expand [--project <path>] [--target <js-browser|js-node|wasm-browser|wasm-node|wasm-wasi>] --file <path> [--stage <rewrite|prepared|expanded|projected>] [--trace]',
' soundscript explain <code> [--format <text|json|ndjson>]',
' soundscript lsp',
' soundscript [--help] [--version]',
'',
'Commands:',
' init Create a new soundscript project or adoption config.',
' build Build a publishable soundscript package.',
' check Analyze a project with the checker.',
' compile Experimental compiler entrypoint.',
' deno Run Deno against a temporary transformed graph.',
' expand Expand macros and emit base TypeScript files.',
' explain Explain a soundscript diagnostic code.',
' lsp Start the language server over stdio.',
'',
'Command options:',
' --mode Init mode: new (default) or existing.',
' -p, --project Path to a tsconfig.json file for build, check, compile, or expand.',
' --target Experimental runtime target override: js-node (default), js-browser, wasm-browser, wasm-node, or wasm-wasi.',
' --format Output format for build, check, compile, expand, or explain: text (default), json, or ndjson.',
' --references Recursively check or build project references before the selected project.',
' --no-cache Disable persistent full-check cache reads and writes for check.',
' --cache-dir Override the base directory for the persistent check cache.',
' --file Print one expanded file instead of writing an output directory for expand.',
' --out-dir Output directory for build (default: dist) or expand (default: soundscript-expanded).',
' --verbose Print emitted file paths for build.',
' --stage Expansion stage for expand --file: rewrite, prepared, expanded, or projected (default: expanded).',
' --trace Include structured macro trace data with expand --file.',
' --watch Rebuild on file changes for build.',
'',
'Experimental:',
' soundscript compile and runtime target overrides, especially Wasm targets, are not part of stable v1.',
' soundscript deno requires @soundscript/soundscript in the current project or an ancestor workspace.',
'',
'Examples:',
' soundscript init',
' soundscript init --mode existing',
' soundscript build',
' soundscript build --references',
' soundscript build --out-dir dist --verbose',
' soundscript check',
' soundscript check --references',
' soundscript check --project tsconfig.soundscript.json --format json',
' soundscript check --project tsconfig.soundscript.json --format ndjson',
' soundscript expand --file src/main.sts --stage expanded',
' soundscript deno run src/main.sts',
' soundscript explain SOUND1002',
' soundscript lsp',
'',
'Global options:',
' -h, --help Show this help text.',
' -v, --version Show the current version.',
].join('\n');
}
function renderInvalidCommand(message: string): string {
return `${message}\n\n${renderHelp()}\n`;
}
function summarizeDiagnostics(diagnostics: readonly MergedDiagnostic[]): JsonSummary {
return {
total: diagnostics.length,
errors: diagnostics.filter((diagnostic) => diagnostic.category === 'error').length,
warnings: diagnostics.filter((diagnostic) => diagnostic.category === 'warning').length,
messages: diagnostics.filter((diagnostic) => diagnostic.category === 'message').length,
};
}
function renderJsonOutput(
command: MachineReadableCommand,
projectPath: string,
workingDirectory: string,
exitCode: number,
diagnostics: readonly MergedDiagnostic[],
artifacts?: BuildProjectArtifacts | CompileArtifacts | ExpandProjectArtifacts,
): string {
const machineDiagnostics = diagnostics.map((diagnostic) =>
toMachineDiagnostic(diagnostic, workingDirectory)
);
const payload: JsonCliOutput = {
schemaVersion: 1,
toolVersion: VERSION,
command,
projectPath,
workingDirectory,
exitCode,
summary: summarizeDiagnostics(diagnostics),
diagnostics: machineDiagnostics,
...(artifacts ? { artifacts } : {}),
};
return `${JSON.stringify(payload, null, 2)}\n`;
}
function renderDiagnosticsOutput(
format: OutputFormat,
command: MachineReadableCommand,
projectPath: string,
workingDirectory: string,
exitCode: number,
diagnostics: readonly MergedDiagnostic[],
artifacts?: BuildProjectArtifacts | CompileArtifacts | ExpandProjectArtifacts,
): string {
if (format === 'json') {
return renderJsonOutput(
command,
projectPath,
workingDirectory,
exitCode,
diagnostics,
artifacts,
);
}
if (format === 'ndjson') {
return renderNdjsonOutput(
command,
projectPath,
workingDirectory,
exitCode,
diagnostics,
artifacts,
);
}
return formatDiagnostics(diagnostics, workingDirectory);
}
function renderNdjsonOutput(
command: MachineReadableCommand,
projectPath: string,
workingDirectory: string,
exitCode: number,
diagnostics: readonly MergedDiagnostic[],
artifacts?: BuildProjectArtifacts | CompileArtifacts | ExpandProjectArtifacts,
): string {
const machineDiagnostics = diagnostics.map((diagnostic) =>
toMachineDiagnostic(diagnostic, workingDirectory)
);
const runEvent: NdjsonRunEvent = {
event: 'run',
schemaVersion: 1,
toolVersion: VERSION,
command,
projectPath,
workingDirectory,
};
const diagnosticEvents: NdjsonDiagnosticEvent[] = machineDiagnostics.map((diagnostic) => ({
event: 'diagnostic',
diagnostic,
}));
const summaryEvent: NdjsonSummaryEvent = {
event: 'summary',
schemaVersion: 1,
toolVersion: VERSION,
command,
projectPath,
workingDirectory,
exitCode,
summary: summarizeDiagnostics(diagnostics),
...(artifacts ? { artifacts } : {}),
};
return [
JSON.stringify(runEvent),
...diagnosticEvents.map((event) => JSON.stringify(event)),
JSON.stringify(summaryEvent),
'',
].join('\n');
}
function renderExplainTextOutput(code: string): string {
const reference = getDiagnosticReference(code);
if (!reference) {
return [
`No built-in explanation is available for diagnostic code ${code}.`,
'',
'soundscript explain currently covers built-in soundscript diagnostic codes.',
'',
].join('\n');
}
const lines = [
`${reference.code}: ${reference.title}`,
'',
reference.summary,
];
if (reference.repairHeuristic) {
lines.push('', 'Repair heuristic:', reference.repairHeuristic);
}
if (reference.details.length > 0) {
lines.push('', 'Details:');
for (const detail of reference.details) {
lines.push(`- ${detail}`);
}
}
if ((reference.examples?.length ?? 0) > 0) {
lines.push('', 'Examples:');
reference.examples?.forEach((example, index) => {
lines.push('', `Example ${index + 1}:`, 'Before:', '```ts', example.bad, '```');
lines.push('After:', '```ts', example.good, '```');
});
}
if (reference.suggestions.length > 0) {
lines.push('', 'Suggestions:');
for (const suggestion of reference.suggestions) {
lines.push(`- ${suggestion.title}: ${suggestion.message}`);
}
}
lines.push(
'',
`Docs: ${getDiagnosticDocsUrl(reference.code)}`,
'',
);
return lines.join('\n');
}
function renderExplainJsonOutput(code: string): string {
const reference = getDiagnosticReference(code);
if (!reference) {
return `${
JSON.stringify(
{
schemaVersion: 1,
toolVersion: VERSION,
command: 'explain',
code,
found: false,
message: `No built-in explanation is available for diagnostic code ${code}.`,
},
null,
2,
)
}\n`;
}
const payload: JsonExplainOutput = {
schemaVersion: 1,
toolVersion: VERSION,
command: 'explain',
code: reference.code,
title: reference.title,
summary: reference.summary,
details: [...reference.details],
repairHeuristic: reference.repairHeuristic,
examples: reference.examples ? [...reference.examples] : undefined,
docsUrl: getDiagnosticDocsUrl(reference.code),
suggestions: reference.suggestions.map((suggestion) => ({
...suggestion,
source: 'reference',
})),
};
return `${JSON.stringify(payload, null, 2)}\n`;
}
function renderExplainNdjsonOutput(code: string): string {
const reference = getDiagnosticReference(code);
if (!reference) {
return `${
JSON.stringify({
event: 'explain',
schemaVersion: 1,
toolVersion: VERSION,
code,
found: false,
message: `No built-in explanation is available for diagnostic code ${code}.`,
})
}\n`;
}
return `${
JSON.stringify({
event: 'explain',
schemaVersion: 1,
toolVersion: VERSION,
code: reference.code,
title: reference.title,
summary: reference.summary,
details: reference.details,
repairHeuristic: reference.repairHeuristic,
examples: reference.examples,
docsUrl: getDiagnosticDocsUrl(reference.code),
suggestions: reference.suggestions.map((suggestion) => ({
...suggestion,
source: 'reference',
})),
})
}\n`;
}
function renderExplainOutput(code: string, format: OutputFormat): string {
if (format === 'json') {
return renderExplainJsonOutput(code);
}
if (format === 'ndjson') {
return renderExplainNdjsonOutput(code);
}
return renderExplainTextOutput(code);
}
function detectSuggestedProjectPath(workingDirectory: string): string | undefined {
const soundscriptProjectPath = join(workingDirectory, 'tsconfig.soundscript.json');
return pathExists(soundscriptProjectPath) ? soundscriptProjectPath : undefined;
}
function createMissingProjectResult(
format: OutputFormat,
command: 'build' | 'check' | 'compile' | 'expand',
projectPath: string,
workingDirectory: string,
): CliResult {
const requestedProjectName = basename(projectPath);
const suggestedProjectPath = requestedProjectName === 'tsconfig.json'
? detectSuggestedProjectPath(workingDirectory)
: undefined;
const diagnostics = [
createCliDiagnostic(
'SOUNDSCRIPT_NO_PROJECT',
'No tsconfig.json was found for this command.',
projectPath,
{
notes: suggestedProjectPath
? [
`Found '${
basename(suggestedProjectPath)
}' in this directory instead of 'tsconfig.json'.`,
]
: undefined,
hint: suggestedProjectPath
? `Try 'soundscript ${command} --project ${basename(suggestedProjectPath)}'.`
: "Run 'soundscript init' to create a new project, or pass --project to an existing tsconfig.",
},
),
];
return {
exitCode: CLI_FAILURE_EXIT_CODE,
output: renderDiagnosticsOutput(
format,
command,
projectPath,
workingDirectory,
CLI_FAILURE_EXIT_CODE,
diagnostics,
),
diagnostics,
projectPath,
workingDirectory,
};
}
function createCliFailureResult(
format: OutputFormat,
command: MachineReadableCommand,
workingDirectory: string,
details: {
code: string;
hint?: string;
message: string;
notes?: string[];
projectPath?: string;
},
): CliResult {
const projectPath = details.projectPath ?? '';
const diagnostics = [
createCliDiagnostic(
details.code,
details.message,
details.projectPath ?? workingDirectory,
{
hint: details.hint,
notes: details.notes,
},
),
];
return {
exitCode: CLI_FAILURE_EXIT_CODE,
output: renderDiagnosticsOutput(
format,
command,
projectPath,
workingDirectory,
CLI_FAILURE_EXIT_CODE,
diagnostics,
),
diagnostics,
projectPath,
workingDirectory,
};
}
function describeUnexpectedError(error: unknown): string | undefined {
if (error instanceof Error) {
return error.message;
}
if (typeof error === 'string') {
return error;
}
if (error === undefined || error === null) {
return undefined;
}
return String(error);
}
function createInternalErrorResult(
format: OutputFormat,
command: 'build' | 'check' | 'compile' | 'expand',
projectPath: string,
workingDirectory: string,
error?: unknown,
commandOutput?: string,
): CliResult {
const notes: string[] = [];
const errorMessage = describeUnexpectedError(error);
if (errorMessage) {
notes.push(`Internal error: ${errorMessage}`);
}
if (commandOutput && commandOutput.trim().length > 0 && commandOutput !== errorMessage) {
notes.push(`Command output: ${commandOutput}`);
}
return createCliFailureResult(format, command, workingDirectory, {
code: 'SOUNDSCRIPT_INTERNAL_ERROR',
message: `soundscript hit an unexpected internal error while running '${command}'.`,
notes: notes.length > 0 ? notes : undefined,
hint:
'Retry with the smallest reproduction you can share. If it still fails, file an issue with the command and input that triggered it.',
projectPath,
});
}
async function initializeProject(
command: InitCommand,
workingDirectory: string,
): Promise<CliResult> {
if (command.mode === 'new') {
const projectPath = join(workingDirectory, 'tsconfig.json');
const entryPath = join(workingDirectory, 'src/main.sts');
if (pathExists(projectPath) || pathExists(entryPath)) {
const diagnostics = [
createCliDiagnostic(
'SOUNDSCRIPT_INIT_CONFLICT',
'Cannot initialize a new project because soundscript files already exist.',
pathExists(projectPath) ? projectPath : entryPath,
{
hint:
"Remove the existing files first, or run 'soundscript init --mode existing' in an existing TypeScript project.",
},
),
];
return {
exitCode: CLI_FAILURE_EXIT_CODE,
output: formatDiagnostics(diagnostics, workingDirectory),
diagnostics,
projectPath,
workingDirectory,
};
}
await makeDirectory(join(workingDirectory, 'src'));
await writeTextFile(
projectPath,
`${
JSON.stringify(
{
compilerOptions: {
strict: true,
noEmit: true,
target: 'ES2022',
module: 'ESNext',
moduleResolution: 'Bundler',
},
include: ['src/**/*.ts', 'src/**/*.sts'],
},
null,
2,
)
}\n`,
);
await writeTextFile(
entryPath,
[
"console.log('Hello from soundscript');",
'',
].join('\n'),
);
return {
exitCode: 0,
output: [
`Initialized a new soundscript project in ${workingDirectory}.`,
'',
'Next steps:',
' 1. Edit src/main.sts',
' 2. Run soundscript check',
'',
].join('\n'),
diagnostics: [],
projectPath,
workingDirectory,
};
}
const baseProjectPath = join(workingDirectory, 'tsconfig.json');
const projectPath = join(workingDirectory, 'tsconfig.soundscript.json');
if (!pathExists(baseProjectPath)) {
const diagnostics = [
createCliDiagnostic(
'SOUNDSCRIPT_INIT_BASE_PROJECT_MISSING',
'Cannot initialize existing-project mode without a tsconfig.json.',
baseProjectPath,
{
hint:
"Create a base tsconfig.json first, or run 'soundscript init' to create a fresh soundscript project.",
},
),
];
return {
exitCode: CLI_FAILURE_EXIT_CODE,
output: formatDiagnostics(diagnostics, workingDirectory),
diagnostics,
projectPath,
workingDirectory,
};
}
if (pathExists(projectPath)) {
const diagnostics = [
createCliDiagnostic(
'SOUNDSCRIPT_INIT_CONFLICT',
'Cannot initialize existing-project mode because tsconfig.soundscript.json already exists.',
projectPath,
{
hint: `Use 'soundscript check --project ${
basename(projectPath)
}' with the existing config, or delete it before re-running init.`,
},
),
];
return {
exitCode: CLI_FAILURE_EXIT_CODE,
output: formatDiagnostics(diagnostics, workingDirectory),
diagnostics,
projectPath,
workingDirectory,
};
}
const include = deriveExistingProjectInclude(baseProjectPath);
await writeTextFile(
projectPath,
`${
JSON.stringify(
{
extends: './tsconfig.json',
compilerOptions: {
strict: true,
noEmit: true,
target: 'ES2022',
module: 'ESNext',
moduleResolution: 'Bundler',
},
...(include ? { include } : {}),
},
null,
2,
)
}\n`,
);
return {
exitCode: 0,
output: [
'Initialized soundscript for an existing TypeScript project.',
'',
`Use: soundscript check --project ${basename(projectPath)}`,
'',
].join('\n'),
diagnostics: [],
projectPath,
workingDirectory,
};
}
async function runBuildWatch(
command: BuildCommand,
buildProjectFn: (options: BuildProjectOptions) => Promise<BuildProjectResult>,
watchFileSystemFn: (path: string) => AsyncIterable<HostFileSystemWatchEvent>,
): Promise<never> {
const watcher = watchFileSystemFn(dirname(command.projectPath));
let building = false;
let pending = false;
const rebuild = async (): Promise<void> => {
if (building) {
pending = true;
return;
}
building = true;
try {
const result = await buildProjectFn(command);
writeStdout(result.output);
} finally {
building = false;
if (pending) {
pending = false;
await rebuild();
}
}
};
await rebuild();
for await (const event of watcher) {
if (event.kind === 'other') {
continue;
}
await rebuild();
}
throw new Error('soundscript build watch ended unexpectedly.');
}
function maybeResolveLocalCliPath(argument: string, workingDirectory: string): string | undefined {
if (argument.startsWith('-')) {
return undefined;
}
const resolved = argument.startsWith('/') ? argument : join(workingDirectory, argument);
return pathExists(resolved) ? resolved : undefined;
}
async function runSubprocess(
command: string,
args: readonly string[],
cwd: string,
): Promise<{ exitCode: number; output: string }> {
return await runCommand(command, args, cwd);
}
function replaceLocalDenoEntryArgs(
denoSubcommand: DenoCommand['denoSubcommand'],
forwardedArgs: readonly string[],
materialized: MaterializeRuntimeGraphArtifacts,
workingDirectory: string,
): string[] {
const rewrittenArgs = [...forwardedArgs];
if (denoSubcommand === 'run') {
for (let index = 0; index < rewrittenArgs.length; index += 1) {
const candidate = maybeResolveLocalCliPath(rewrittenArgs[index]!, workingDirectory);
if (!candidate) {
continue;
}
rewrittenArgs[index] = materialized.entryOutputPaths[0]!;
break;
}
return rewrittenArgs;
}