@xessa/cli 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +42 -2
- package/dist/args.d.ts +43 -0
- package/dist/args.d.ts.map +1 -0
- package/dist/args.js +202 -0
- package/dist/args.js.map +1 -0
- package/dist/commands/build.d.ts +44 -0
- package/dist/commands/build.d.ts.map +1 -0
- package/dist/commands/build.js +533 -0
- package/dist/commands/build.js.map +1 -0
- package/dist/commands/check.d.ts +11 -0
- package/dist/commands/check.d.ts.map +1 -0
- package/dist/commands/check.js +35 -0
- package/dist/commands/check.js.map +1 -0
- package/dist/commands/clean.d.ts +12 -0
- package/dist/commands/clean.d.ts.map +1 -0
- package/dist/commands/clean.js +140 -0
- package/dist/commands/clean.js.map +1 -0
- package/dist/commands/format.d.ts +41 -0
- package/dist/commands/format.d.ts.map +1 -0
- package/dist/commands/format.js +127 -0
- package/dist/commands/format.js.map +1 -0
- package/dist/commands/watch.d.ts +38 -0
- package/dist/commands/watch.d.ts.map +1 -0
- package/dist/commands/watch.js +338 -0
- package/dist/commands/watch.js.map +1 -0
- package/dist/compiler.d.ts +20 -0
- package/dist/compiler.d.ts.map +1 -0
- package/dist/compiler.js +57 -0
- package/dist/compiler.js.map +1 -0
- package/dist/config.d.ts +93 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +331 -0
- package/dist/config.js.map +1 -0
- package/dist/formatter.d.ts +21 -0
- package/dist/formatter.d.ts.map +1 -0
- package/dist/formatter.js +38 -0
- package/dist/formatter.js.map +1 -0
- package/dist/glob.d.ts +52 -0
- package/dist/glob.d.ts.map +1 -0
- package/dist/glob.js +214 -0
- package/dist/glob.js.map +1 -0
- package/dist/index.d.ts +34 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +114 -0
- package/dist/index.js.map +1 -0
- package/dist/manifest.d.ts +56 -0
- package/dist/manifest.d.ts.map +1 -0
- package/dist/manifest.js +138 -0
- package/dist/manifest.js.map +1 -0
- package/dist/paths.d.ts +24 -0
- package/dist/paths.d.ts.map +1 -0
- package/dist/paths.js +42 -0
- package/dist/paths.js.map +1 -0
- package/dist/project.d.ts +44 -0
- package/dist/project.d.ts.map +1 -0
- package/dist/project.js +92 -0
- package/dist/project.js.map +1 -0
- package/dist/report.d.ts +128 -0
- package/dist/report.d.ts.map +1 -0
- package/dist/report.js +128 -0
- package/dist/report.js.map +1 -0
- package/dist/setup.d.ts +58 -0
- package/dist/setup.d.ts.map +1 -0
- package/dist/setup.js +181 -0
- package/dist/setup.js.map +1 -0
- package/dist/writer.d.ts +32 -0
- package/dist/writer.d.ts.map +1 -0
- package/dist/writer.js +93 -0
- package/dist/writer.js.map +1 -0
- package/package.json +40 -4
- package/src/args.ts +246 -0
- package/src/commands/build.ts +682 -0
- package/src/commands/check.ts +45 -0
- package/src/commands/clean.ts +168 -0
- package/src/commands/format.ts +169 -0
- package/src/commands/watch.ts +366 -0
- package/src/compiler-api.d.ts +261 -0
- package/src/compiler.ts +65 -0
- package/src/config.ts +443 -0
- package/src/formatter.ts +56 -0
- package/src/glob.ts +230 -0
- package/src/index.ts +137 -0
- package/src/manifest.ts +176 -0
- package/src/paths.ts +50 -0
- package/src/project.ts +122 -0
- package/src/report.ts +230 -0
- package/src/setup.ts +218 -0
- package/src/writer.ts +102 -0
package/src/project.ts
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Project resolution shared by every command.
|
|
3
|
+
*
|
|
4
|
+
* A project is the workspace root (nearest `xessa.config.json`, else nearest
|
|
5
|
+
* `package.json`, ADR-0007), the configuration found there and the entry list:
|
|
6
|
+
* either one explicit file or the sources matched by the config include globs.
|
|
7
|
+
* Configuration is optional for project runs: without a file the root still
|
|
8
|
+
* comes from the workspace walk and discovery uses {@link DEFAULT_INCLUDE}.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { stat } from "node:fs/promises";
|
|
12
|
+
import type { CliInvocation } from "./args.js";
|
|
13
|
+
import { type CliConfig, DEFAULT_INCLUDE, findWorkspaceRoot, loadConfig } from "./config.js";
|
|
14
|
+
import { discoverSources } from "./glob.js";
|
|
15
|
+
import { absolutePath, dirnamePosix, isWithin, relativePosix } from "./paths.js";
|
|
16
|
+
|
|
17
|
+
/** Resolved project inputs for one CLI run. */
|
|
18
|
+
export interface ProjectContext {
|
|
19
|
+
/** Absolute POSIX workspace root. */
|
|
20
|
+
readonly root: string;
|
|
21
|
+
/** Loaded configuration, or `null` for a config-less project/single-file run. */
|
|
22
|
+
readonly config: CliConfig | null;
|
|
23
|
+
/** Non-fatal configuration notes (ignored unknown keys outside strict mode). */
|
|
24
|
+
readonly configWarnings: readonly string[];
|
|
25
|
+
/** Entry sources, workspace-relative POSIX and deterministically sorted. */
|
|
26
|
+
readonly entries: readonly string[];
|
|
27
|
+
/** Whether the run targets one explicit file instead of the whole project. */
|
|
28
|
+
readonly singleEntry: boolean;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Outcome of {@link prepareProject}. */
|
|
32
|
+
export type ProjectContextResult =
|
|
33
|
+
| { readonly ok: true; readonly context: ProjectContext }
|
|
34
|
+
| { readonly ok: false; readonly message: string };
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Resolve configuration, workspace root and entries for build/check/watch.
|
|
38
|
+
*
|
|
39
|
+
* Configuration is optional. Without a file, the workspace root is the nearest
|
|
40
|
+
* `package.json` ancestor (ADR-0007) and project discovery uses
|
|
41
|
+
* {@link DEFAULT_INCLUDE}; a single-entry run falls back to the file's
|
|
42
|
+
* directory when no package boundary exists. Explicitly configuring an empty
|
|
43
|
+
* `include` list remains an invocation error, and an empty discovery result is
|
|
44
|
+
* reported by the command as a configuration error (typo protection).
|
|
45
|
+
*/
|
|
46
|
+
export async function prepareProject(
|
|
47
|
+
invocation: CliInvocation,
|
|
48
|
+
cwd: string,
|
|
49
|
+
): Promise<ProjectContextResult> {
|
|
50
|
+
const fileArgument = invocation.file;
|
|
51
|
+
let fileAbsolute: string | undefined;
|
|
52
|
+
let startDir = cwd;
|
|
53
|
+
|
|
54
|
+
if (fileArgument !== undefined) {
|
|
55
|
+
fileAbsolute = absolutePath(cwd, fileArgument);
|
|
56
|
+
if (!(await isFile(fileAbsolute))) {
|
|
57
|
+
return { ok: false, message: `Source file not found: ${fileArgument}` };
|
|
58
|
+
}
|
|
59
|
+
startDir = dirnamePosix(fileAbsolute);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const loaded = await loadConfig({
|
|
63
|
+
cwd,
|
|
64
|
+
startDir,
|
|
65
|
+
...(invocation.configPath === undefined ? {} : { explicitPath: invocation.configPath }),
|
|
66
|
+
});
|
|
67
|
+
if (!loaded.ok) return { ok: false, message: loaded.message };
|
|
68
|
+
|
|
69
|
+
const config = loaded.config;
|
|
70
|
+
const root = config === null ? await findWorkspaceRoot(startDir) : config.root;
|
|
71
|
+
|
|
72
|
+
if (fileAbsolute !== undefined) {
|
|
73
|
+
if (!isWithin(root, fileAbsolute)) {
|
|
74
|
+
return {
|
|
75
|
+
ok: false,
|
|
76
|
+
message: `Source file "${fileArgument ?? fileAbsolute}" is outside the workspace root "${root}". Pass --config for the containing project.`,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
return {
|
|
80
|
+
ok: true,
|
|
81
|
+
context: {
|
|
82
|
+
root,
|
|
83
|
+
config,
|
|
84
|
+
configWarnings: loaded.warnings,
|
|
85
|
+
entries: [relativePosix(root, fileAbsolute)],
|
|
86
|
+
singleEntry: true,
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
if (config !== null && config.include.length === 0) {
|
|
92
|
+
return {
|
|
93
|
+
ok: false,
|
|
94
|
+
message: `"include" in ${config.file} must list at least one glob.`,
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const entries = await discoverSources({
|
|
99
|
+
root,
|
|
100
|
+
include: config?.include ?? DEFAULT_INCLUDE,
|
|
101
|
+
exclude: config?.exclude ?? [],
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
return {
|
|
105
|
+
ok: true,
|
|
106
|
+
context: {
|
|
107
|
+
root,
|
|
108
|
+
config,
|
|
109
|
+
configWarnings: loaded.warnings,
|
|
110
|
+
entries,
|
|
111
|
+
singleEntry: false,
|
|
112
|
+
},
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async function isFile(path: string): Promise<boolean> {
|
|
117
|
+
try {
|
|
118
|
+
return (await stat(path)).isFile();
|
|
119
|
+
} catch {
|
|
120
|
+
return false;
|
|
121
|
+
}
|
|
122
|
+
}
|
package/src/report.ts
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reporting helpers: diagnostic positioning, text output and JSON shapes.
|
|
3
|
+
*
|
|
4
|
+
* Compiler diagnostics carry UTF-16 offsets (`Span`), so the CLI converts them
|
|
5
|
+
* to 1-based line and column numbers using the entry sources it already reads.
|
|
6
|
+
* Machine-readable output is stable and documented in the A11 report.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { readFile } from "node:fs/promises";
|
|
10
|
+
import { isAbsolute } from "node:path";
|
|
11
|
+
import type { Diagnostic, OutputKind } from "@xessa/compiler";
|
|
12
|
+
import { joinPosix, relativePosix, toPosix } from "./paths.js";
|
|
13
|
+
|
|
14
|
+
/** A compiler diagnostic positioned for humans and machine consumers. */
|
|
15
|
+
export interface CliDiagnostic {
|
|
16
|
+
/** Stable compiler code (`XESSA####`) or CLI code (`XESSACLI###`). */
|
|
17
|
+
readonly code: string;
|
|
18
|
+
/** `error` fails a build/check; `warning` is advisory. */
|
|
19
|
+
readonly severity: "error" | "warning";
|
|
20
|
+
/** User-facing explanation. */
|
|
21
|
+
readonly message: string;
|
|
22
|
+
/** Workspace-relative POSIX path of the diagnostic origin. */
|
|
23
|
+
readonly file: string;
|
|
24
|
+
/** 1-based line number. */
|
|
25
|
+
readonly line: number;
|
|
26
|
+
/** 1-based column number. */
|
|
27
|
+
readonly column: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** One planned artifact and whether this run wrote it. */
|
|
31
|
+
export interface OutputRecord {
|
|
32
|
+
/** Artifact kind. */
|
|
33
|
+
readonly kind: OutputKind;
|
|
34
|
+
/** Workspace-relative POSIX destination. */
|
|
35
|
+
readonly path: string;
|
|
36
|
+
/** Absolute destination. */
|
|
37
|
+
readonly absolutePath: string;
|
|
38
|
+
/** Whether the artifact was written by this run. */
|
|
39
|
+
readonly written: boolean;
|
|
40
|
+
/** Why the artifact was not written, when applicable. */
|
|
41
|
+
readonly reason?: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Per-entry result of a build or check. */
|
|
45
|
+
export interface EntryReport {
|
|
46
|
+
/** Workspace-relative POSIX path of the entry source. */
|
|
47
|
+
readonly file: string;
|
|
48
|
+
/** Workspace-relative POSIX paths of reachable modules, excluding the entry. */
|
|
49
|
+
readonly dependencies: readonly string[];
|
|
50
|
+
/** Planned artifacts in planner order. */
|
|
51
|
+
readonly outputs: readonly OutputRecord[];
|
|
52
|
+
/** Positioned diagnostics for this entry and its modules. */
|
|
53
|
+
readonly diagnostics: readonly CliDiagnostic[];
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Result of one build or check run. */
|
|
57
|
+
export interface BuildReport {
|
|
58
|
+
/** Command that produced the report. */
|
|
59
|
+
readonly command: "build" | "check";
|
|
60
|
+
/** Absolute POSIX workspace root. */
|
|
61
|
+
readonly workspaceRoot: string;
|
|
62
|
+
/** Absolute path of the configuration file, when one was used. */
|
|
63
|
+
readonly configFile: string | null;
|
|
64
|
+
/** Whether the run only reported planned work. */
|
|
65
|
+
readonly dryRun: boolean;
|
|
66
|
+
/** One report per entry, sorted like the input entries. */
|
|
67
|
+
readonly entries: readonly EntryReport[];
|
|
68
|
+
/** All positioned diagnostics, deduplicated. */
|
|
69
|
+
readonly diagnostics: readonly CliDiagnostic[];
|
|
70
|
+
/** Non-diagnostic notes and warnings. */
|
|
71
|
+
readonly warnings: readonly string[];
|
|
72
|
+
/** Non-diagnostic failures such as write or manifest errors. */
|
|
73
|
+
readonly errors: readonly string[];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Machine-readable artifact record. */
|
|
77
|
+
export interface JsonOutputFile {
|
|
78
|
+
readonly kind: OutputKind;
|
|
79
|
+
readonly path: string;
|
|
80
|
+
readonly written: boolean;
|
|
81
|
+
readonly reason?: string;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Machine-readable entry record. */
|
|
85
|
+
export interface JsonEntry {
|
|
86
|
+
readonly file: string;
|
|
87
|
+
readonly dependencies: readonly string[];
|
|
88
|
+
readonly outputs: readonly JsonOutputFile[];
|
|
89
|
+
readonly diagnostics: readonly CliDiagnostic[];
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Machine-readable build/check report (`--json`). */
|
|
93
|
+
export interface JsonBuildReport {
|
|
94
|
+
readonly command: "build" | "check";
|
|
95
|
+
readonly success: boolean;
|
|
96
|
+
readonly exitCode: number;
|
|
97
|
+
readonly dryRun: boolean;
|
|
98
|
+
readonly workspaceRoot: string;
|
|
99
|
+
readonly configFile: string | null;
|
|
100
|
+
readonly entries: readonly JsonEntry[];
|
|
101
|
+
readonly diagnostics: readonly CliDiagnostic[];
|
|
102
|
+
readonly warnings: readonly string[];
|
|
103
|
+
readonly errors: readonly string[];
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Maximum offset-to-line scan cost per distinct source file. */
|
|
107
|
+
const POSITION_CACHE_LIMIT = 512;
|
|
108
|
+
|
|
109
|
+
/** Converts compiler spans into 1-based line/column diagnostics. */
|
|
110
|
+
export class DiagnosticPositions {
|
|
111
|
+
private readonly root: string;
|
|
112
|
+
private readonly cache = new Map<string, string | null>();
|
|
113
|
+
|
|
114
|
+
constructor(root: string) {
|
|
115
|
+
this.root = root;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Convert raw compiler diagnostics to positioned CLI diagnostics. */
|
|
119
|
+
async convert(diagnostics: readonly Diagnostic[]): Promise<CliDiagnostic[]> {
|
|
120
|
+
const result: CliDiagnostic[] = [];
|
|
121
|
+
for (const diagnostic of diagnostics) {
|
|
122
|
+
const absolute = isAbsolute(diagnostic.span.file)
|
|
123
|
+
? toPosix(diagnostic.span.file)
|
|
124
|
+
: joinPosix(this.root, diagnostic.span.file);
|
|
125
|
+
const text = await this.readSource(absolute);
|
|
126
|
+
const position =
|
|
127
|
+
text === null ? { line: 1, column: 1 } : positionAt(text, diagnostic.span.start);
|
|
128
|
+
result.push({
|
|
129
|
+
code: diagnostic.code,
|
|
130
|
+
severity: diagnostic.severity,
|
|
131
|
+
message: diagnostic.message,
|
|
132
|
+
file: this.displayPath(absolute),
|
|
133
|
+
line: position.line,
|
|
134
|
+
column: position.column,
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
return result;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
private displayPath(absolute: string): string {
|
|
141
|
+
const relative = relativePosix(this.root, absolute);
|
|
142
|
+
if (relative === "" || relative === ".." || relative.startsWith("../")) {
|
|
143
|
+
return toPosix(absolute);
|
|
144
|
+
}
|
|
145
|
+
return relative;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
private async readSource(absolute: string): Promise<string | null> {
|
|
149
|
+
if (this.cache.has(absolute)) return this.cache.get(absolute) ?? null;
|
|
150
|
+
let text: string | null = null;
|
|
151
|
+
try {
|
|
152
|
+
text = await readFile(absolute, "utf8");
|
|
153
|
+
} catch {
|
|
154
|
+
text = null;
|
|
155
|
+
}
|
|
156
|
+
if (this.cache.size >= POSITION_CACHE_LIMIT) this.cache.clear();
|
|
157
|
+
this.cache.set(absolute, text);
|
|
158
|
+
return text;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Convert a UTF-16 offset to 1-based line and column. */
|
|
163
|
+
export function positionAt(text: string, offset: number): { line: number; column: number } {
|
|
164
|
+
const limit = Math.max(0, Math.min(offset, text.length));
|
|
165
|
+
let line = 1;
|
|
166
|
+
let column = 1;
|
|
167
|
+
for (let index = 0; index < limit; index += 1) {
|
|
168
|
+
const character = text.charAt(index);
|
|
169
|
+
if (character === "\n") {
|
|
170
|
+
line += 1;
|
|
171
|
+
column = 1;
|
|
172
|
+
} else {
|
|
173
|
+
column += 1;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return { line, column };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** One-line human diagnostic: `file:line:col severity CODE: message`. */
|
|
180
|
+
export function formatDiagnostic(diagnostic: CliDiagnostic): string {
|
|
181
|
+
return `${diagnostic.file}:${diagnostic.line}:${diagnostic.column} ${diagnostic.severity} ${diagnostic.code}: ${diagnostic.message}`;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Write one line to stdout. */
|
|
185
|
+
export function writeLine(text: string): void {
|
|
186
|
+
process.stdout.write(`${text}\n`);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Write one line to stderr. */
|
|
190
|
+
export function writeErrorLine(text: string): void {
|
|
191
|
+
process.stderr.write(`${text}\n`);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Serialize a JSON report with a trailing newline. */
|
|
195
|
+
export function toJson(report: unknown): string {
|
|
196
|
+
return `${JSON.stringify(report, null, 2)}\n`;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Whether any diagnostics in the list are errors. */
|
|
200
|
+
export function hasErrors(diagnostics: readonly CliDiagnostic[]): boolean {
|
|
201
|
+
return diagnostics.some((diagnostic) => diagnostic.severity === "error");
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Deduplicate positioned diagnostics while preserving first-seen order. */
|
|
205
|
+
export function dedupeDiagnostics(diagnostics: readonly CliDiagnostic[]): CliDiagnostic[] {
|
|
206
|
+
const seen = new Set<string>();
|
|
207
|
+
const result: CliDiagnostic[] = [];
|
|
208
|
+
for (const diagnostic of diagnostics) {
|
|
209
|
+
const key = `${diagnostic.code}\u0000${diagnostic.severity}\u0000${diagnostic.file}\u0000${diagnostic.line}\u0000${diagnostic.column}\u0000${diagnostic.message}`;
|
|
210
|
+
if (seen.has(key)) continue;
|
|
211
|
+
seen.add(key);
|
|
212
|
+
result.push(diagnostic);
|
|
213
|
+
}
|
|
214
|
+
return result;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Report an invocation or configuration failure and return exit code 2.
|
|
219
|
+
*
|
|
220
|
+
* With `--json` the failure is still machine-readable; otherwise it goes to
|
|
221
|
+
* stderr with a `xessa:` prefix.
|
|
222
|
+
*/
|
|
223
|
+
export function invocationFailure(command: string, message: string, json: boolean): number {
|
|
224
|
+
if (json) {
|
|
225
|
+
writeLine(toJson({ command, success: false, exitCode: 2, error: message }).trimEnd());
|
|
226
|
+
} else {
|
|
227
|
+
writeErrorLine(`xessa: ${message}`);
|
|
228
|
+
}
|
|
229
|
+
return 2;
|
|
230
|
+
}
|
package/src/setup.ts
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Effective output setup resolution for CLI planning.
|
|
3
|
+
*
|
|
4
|
+
* The compiler returns artifacts but not the output plan it used
|
|
5
|
+
* (`CompileResult` has no destination list), so the CLI must build the same
|
|
6
|
+
* `PlanOutputsInput` the compiler builds internally: defaults, project
|
|
7
|
+
* configuration and decoded file `@setup` values, in that order. This module
|
|
8
|
+
* mirrors the documented precedence and the planner's provenance rules from
|
|
9
|
+
* `.ai/reports/CSSX-A10.md`. A future public plan on `CompileResult` would
|
|
10
|
+
* remove the duplication.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { decodeSetupList } from "@xessa/compiler";
|
|
14
|
+
import type { ResolvedSetup, SetupBlock, Stylesheet, StylesheetItem } from "@xessa/compiler";
|
|
15
|
+
import type { CliConfig } from "./config.js";
|
|
16
|
+
import { basenamePosix, dirnamePosix } from "./paths.js";
|
|
17
|
+
|
|
18
|
+
/** Authored file-level `@setup` values; absent keys mean "not authored". */
|
|
19
|
+
export interface FileSetupValues {
|
|
20
|
+
readonly prefix?: string;
|
|
21
|
+
readonly cssDir?: string;
|
|
22
|
+
/** File-level `css-dir` list when more than one destination was authored. */
|
|
23
|
+
readonly cssDirs?: readonly string[];
|
|
24
|
+
readonly cssName?: string;
|
|
25
|
+
readonly mapDir?: string;
|
|
26
|
+
readonly mapName?: string;
|
|
27
|
+
readonly emitCss?: boolean;
|
|
28
|
+
readonly emitMap?: boolean;
|
|
29
|
+
/** Resolved declaration flag; `map-types` is canonical, `emit-types` the alias. */
|
|
30
|
+
readonly emitTypes?: boolean;
|
|
31
|
+
readonly sourceMap?: boolean;
|
|
32
|
+
readonly minify?: boolean;
|
|
33
|
+
/** Module map inheritance default (ADR-0020): `@setup { map-inherit: false; }`. */
|
|
34
|
+
readonly mapInherit?: boolean;
|
|
35
|
+
/** Class-map CSS side-effect import (ADR-0021): `@setup { import-css: true; }`. */
|
|
36
|
+
readonly importCss?: boolean;
|
|
37
|
+
/** `@setup { module: true }`: rule-bearing module with no artifacts of its own (ADR-0014). */
|
|
38
|
+
readonly module?: boolean;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const STRING_SETUP_KEYS = ["prefix", "css-name", "map-dir", "map-name"] as const;
|
|
42
|
+
const BOOLEAN_SETUP_KEYS = [
|
|
43
|
+
"emit-css",
|
|
44
|
+
"emit-map",
|
|
45
|
+
"map-types",
|
|
46
|
+
"emit-types",
|
|
47
|
+
"source-map",
|
|
48
|
+
"minify",
|
|
49
|
+
"module",
|
|
50
|
+
"map-inherit",
|
|
51
|
+
"import-css",
|
|
52
|
+
] as const;
|
|
53
|
+
|
|
54
|
+
/** Decode every top-level `@setup` block of an entry, first occurrence winning. */
|
|
55
|
+
export function decodeFileSetup(ast: Stylesheet): FileSetupValues {
|
|
56
|
+
const values: Record<string, string | boolean> = {};
|
|
57
|
+
const seen = new Set<string>();
|
|
58
|
+
let cssDir: string | undefined;
|
|
59
|
+
let cssDirs: readonly string[] | undefined;
|
|
60
|
+
|
|
61
|
+
for (const item of ast.items) {
|
|
62
|
+
if (!isSetupBlock(item)) continue;
|
|
63
|
+
for (const setting of item.settings) {
|
|
64
|
+
const key = setting.key;
|
|
65
|
+
if (seen.has(key)) continue;
|
|
66
|
+
if (key === "css-dir") {
|
|
67
|
+
seen.add(key);
|
|
68
|
+
const decoded = decodeSetupList(setting.value, setting.valueSpan);
|
|
69
|
+
const first = decoded.entries[0];
|
|
70
|
+
if (first !== undefined) cssDir = first.value;
|
|
71
|
+
if (decoded.entries.length > 1) {
|
|
72
|
+
cssDirs = decoded.entries.map((entry) => entry.value);
|
|
73
|
+
}
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (isStringKey(key)) {
|
|
77
|
+
seen.add(key);
|
|
78
|
+
values[key] = decodeScalar(setting.value);
|
|
79
|
+
} else if (isBooleanKey(key)) {
|
|
80
|
+
const decoded = decodeBoolean(setting.value);
|
|
81
|
+
if (decoded === undefined) continue;
|
|
82
|
+
seen.add(key);
|
|
83
|
+
values[key] = decoded;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// `map-types` is the canonical declaration flag; `emit-types` is its legacy
|
|
89
|
+
// alias, so the canonical key wins when both are authored in one layer.
|
|
90
|
+
const types =
|
|
91
|
+
typeof values["map-types"] === "boolean"
|
|
92
|
+
? values["map-types"]
|
|
93
|
+
: typeof values["emit-types"] === "boolean"
|
|
94
|
+
? values["emit-types"]
|
|
95
|
+
: undefined;
|
|
96
|
+
|
|
97
|
+
return {
|
|
98
|
+
...(typeof values.prefix === "string" ? { prefix: values.prefix } : {}),
|
|
99
|
+
...(cssDir === undefined ? {} : { cssDir }),
|
|
100
|
+
...(cssDirs === undefined ? {} : { cssDirs }),
|
|
101
|
+
...(typeof values["css-name"] === "string" ? { cssName: values["css-name"] } : {}),
|
|
102
|
+
...(typeof values["map-dir"] === "string" ? { mapDir: values["map-dir"] } : {}),
|
|
103
|
+
...(typeof values["map-name"] === "string" ? { mapName: values["map-name"] } : {}),
|
|
104
|
+
...(typeof values["emit-css"] === "boolean" ? { emitCss: values["emit-css"] } : {}),
|
|
105
|
+
...(typeof values["emit-map"] === "boolean" ? { emitMap: values["emit-map"] } : {}),
|
|
106
|
+
...(types === undefined ? {} : { emitTypes: types }),
|
|
107
|
+
...(typeof values["source-map"] === "boolean" ? { sourceMap: values["source-map"] } : {}),
|
|
108
|
+
...(typeof values.minify === "boolean" ? { minify: values.minify } : {}),
|
|
109
|
+
...(typeof values.module === "boolean" ? { module: values.module } : {}),
|
|
110
|
+
...(typeof values["map-inherit"] === "boolean" ? { mapInherit: values["map-inherit"] } : {}),
|
|
111
|
+
...(typeof values["import-css"] === "boolean" ? { importCss: values["import-css"] } : {}),
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Built-in setup defaults for a workspace-relative source path.
|
|
117
|
+
*
|
|
118
|
+
* Directories default to the source directory and names to `<stem>.css` /
|
|
119
|
+
* `<stem>.map.js`, matching SPECIFICATION.md §9 and the planner's defaults.
|
|
120
|
+
*/
|
|
121
|
+
export function defaultSetupFor(relativeFile: string): ResolvedSetup {
|
|
122
|
+
const base = basenamePosix(relativeFile);
|
|
123
|
+
const dot = base.lastIndexOf(".");
|
|
124
|
+
const stem = dot > 0 ? base.slice(0, dot) : base;
|
|
125
|
+
const directory = dirnamePosix(relativeFile);
|
|
126
|
+
return {
|
|
127
|
+
prefix: "",
|
|
128
|
+
cssDir: directory,
|
|
129
|
+
mapDir: directory,
|
|
130
|
+
cssName: `${stem}.css`,
|
|
131
|
+
mapName: `${stem}.map.js`,
|
|
132
|
+
emitCss: true,
|
|
133
|
+
emitMap: true,
|
|
134
|
+
emitTypes: false,
|
|
135
|
+
sourceMap: false,
|
|
136
|
+
minify: true,
|
|
137
|
+
mapInherit: true,
|
|
138
|
+
importCss: false,
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Merge built-in defaults, project configuration and file `@setup` into the
|
|
144
|
+
* effective setup for one entry.
|
|
145
|
+
*
|
|
146
|
+
* Precedence is defaults < project config < `module: true` suppression < file
|
|
147
|
+
* `@setup` < explicit overrides. The optional `--minify`/`--no-minify` flag is
|
|
148
|
+
* applied last for reporting; the compiler's project API cannot place it above
|
|
149
|
+
* file `@setup`, which the caller reports as a warning when a file authors a
|
|
150
|
+
* conflicting value. `@setup { module: true }` (ADR-0014) removes the default
|
|
151
|
+
* CSS, map and type outputs of a rule-bearing module; authoring one of those
|
|
152
|
+
* keys explicitly restores it.
|
|
153
|
+
*/
|
|
154
|
+
export function resolveEffectiveSetup(
|
|
155
|
+
relativeFile: string,
|
|
156
|
+
config: CliConfig | null,
|
|
157
|
+
fileSetup: FileSetupValues,
|
|
158
|
+
minifyFlag: boolean | undefined,
|
|
159
|
+
): ResolvedSetup {
|
|
160
|
+
const defaults = defaultSetupFor(relativeFile);
|
|
161
|
+
const project = config?.output;
|
|
162
|
+
const strategy = config?.classes?.strategy ?? "prefix";
|
|
163
|
+
const prefix = strategy === "none" ? "" : (fileSetup.prefix ?? config?.classes?.prefix ?? "");
|
|
164
|
+
const moduleDefaults = fileSetup.module === true;
|
|
165
|
+
const emitCssDefault = moduleDefaults ? false : (project?.emitCss ?? defaults.emitCss);
|
|
166
|
+
const emitMapDefault = moduleDefaults ? false : (project?.emitMap ?? defaults.emitMap);
|
|
167
|
+
const emitTypesDefault = moduleDefaults
|
|
168
|
+
? false
|
|
169
|
+
: (project?.mapTypes ?? project?.emitTypes ?? defaults.emitTypes);
|
|
170
|
+
|
|
171
|
+
return {
|
|
172
|
+
prefix,
|
|
173
|
+
cssDir: fileSetup.cssDir ?? project?.cssDir ?? defaults.cssDir,
|
|
174
|
+
...(fileSetup.cssDirs === undefined ? {} : { cssDirs: fileSetup.cssDirs }),
|
|
175
|
+
cssName: fileSetup.cssName ?? project?.cssName ?? defaults.cssName,
|
|
176
|
+
mapDir: fileSetup.mapDir ?? project?.mapDir ?? defaults.mapDir,
|
|
177
|
+
mapName: fileSetup.mapName ?? project?.mapName ?? defaults.mapName,
|
|
178
|
+
emitCss: fileSetup.emitCss ?? emitCssDefault,
|
|
179
|
+
emitMap: fileSetup.emitMap ?? emitMapDefault,
|
|
180
|
+
emitTypes: fileSetup.emitTypes ?? emitTypesDefault,
|
|
181
|
+
sourceMap: fileSetup.sourceMap ?? project?.sourceMap ?? defaults.sourceMap,
|
|
182
|
+
minify: minifyFlag ?? fileSetup.minify ?? project?.minify ?? defaults.minify,
|
|
183
|
+
mapInherit: fileSetup.mapInherit ?? project?.mapInherit ?? defaults.mapInherit,
|
|
184
|
+
importCss: fileSetup.importCss ?? project?.importCss ?? defaults.importCss,
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function isSetupBlock(item: StylesheetItem): item is SetupBlock {
|
|
189
|
+
return item.kind === "setup" && Array.isArray((item as { settings?: unknown }).settings);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function isStringKey(key: string): boolean {
|
|
193
|
+
return (STRING_SETUP_KEYS as readonly string[]).includes(key);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function isBooleanKey(key: string): boolean {
|
|
197
|
+
return (BOOLEAN_SETUP_KEYS as readonly string[]).includes(key);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function decodeBoolean(raw: string): boolean | undefined {
|
|
201
|
+
const value = raw.trim();
|
|
202
|
+
if (value === "true") return true;
|
|
203
|
+
if (value === "false") return false;
|
|
204
|
+
return undefined;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Decode a quoted CSS string scalar; unquoted scalars are trimmed verbatim. */
|
|
208
|
+
function decodeScalar(raw: string): string {
|
|
209
|
+
const trimmed = raw.trim();
|
|
210
|
+
if (trimmed.length >= 2) {
|
|
211
|
+
const first = trimmed.charAt(0);
|
|
212
|
+
const last = trimmed.charAt(trimmed.length - 1);
|
|
213
|
+
if ((first === '"' && last === '"') || (first === "'" && last === "'")) {
|
|
214
|
+
return trimmed.slice(1, -1).replace(/\\(.)/g, "$1");
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
return trimmed;
|
|
218
|
+
}
|
package/src/writer.ts
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-file atomic output writes.
|
|
3
|
+
*
|
|
4
|
+
* Each artifact is written to a temporary file in its destination directory and
|
|
5
|
+
* renamed into place, so a crash or failure leaves the previous artifact intact.
|
|
6
|
+
* This is per-file atomicity, never cross-file transactionality (SPECIFICATION.md
|
|
7
|
+
* §9.2). Missing destination directories are created.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { createHash } from "node:crypto";
|
|
11
|
+
import type { Dirent } from "node:fs";
|
|
12
|
+
import { mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
|
|
13
|
+
import { basename, dirname, join } from "node:path";
|
|
14
|
+
|
|
15
|
+
let temporaryCounter = 0;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The writer's temporary-file name shape: `.<artifact>.<pid>.<counter>.cssx-tmp`.
|
|
19
|
+
*
|
|
20
|
+
* Only names created by {@link atomicWrite} match, so a sweep can never remove a
|
|
21
|
+
* user file even when it happens to share a directory with generated artifacts.
|
|
22
|
+
*/
|
|
23
|
+
const TEMPORARY_PATTERN = /^\..+\.[0-9]+\.[0-9]+\.cssx-tmp$/;
|
|
24
|
+
|
|
25
|
+
/** SHA-256 content hash in a stable, comparable form. */
|
|
26
|
+
export function hashContent(content: string): string {
|
|
27
|
+
return `sha256:${createHash("sha256").update(content, "utf8").digest("hex")}`;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Hash of an existing file, or `null` when it does not exist or cannot be read. */
|
|
31
|
+
export async function hashFile(path: string): Promise<string | null> {
|
|
32
|
+
try {
|
|
33
|
+
const data = await readFile(path);
|
|
34
|
+
return `sha256:${createHash("sha256").update(data).digest("hex")}`;
|
|
35
|
+
} catch {
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Write `content` atomically and return its content hash.
|
|
42
|
+
*
|
|
43
|
+
* The temporary file lives in the destination directory so the final rename
|
|
44
|
+
* stays on one filesystem. A failure removes the temporary file and rethrows,
|
|
45
|
+
* leaving any previous artifact untouched.
|
|
46
|
+
*/
|
|
47
|
+
export async function atomicWrite(path: string, content: string): Promise<string> {
|
|
48
|
+
const directory = dirname(path);
|
|
49
|
+
await mkdir(directory, { recursive: true });
|
|
50
|
+
|
|
51
|
+
temporaryCounter += 1;
|
|
52
|
+
const temporary = join(
|
|
53
|
+
directory,
|
|
54
|
+
`.${basename(path)}.${process.pid}.${temporaryCounter}.cssx-tmp`,
|
|
55
|
+
);
|
|
56
|
+
|
|
57
|
+
try {
|
|
58
|
+
await writeFile(temporary, content, "utf8");
|
|
59
|
+
await rename(temporary, path);
|
|
60
|
+
} catch (error) {
|
|
61
|
+
await rm(temporary, { force: true }).catch(() => undefined);
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
return hashContent(content);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Remove a file if it exists. */
|
|
69
|
+
export async function removeFile(path: string): Promise<void> {
|
|
70
|
+
await rm(path, { force: true });
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Remove stale writer temporaries from `directories` and return the removed paths.
|
|
75
|
+
*
|
|
76
|
+
* A process killed between `writeFile` and `rename` cannot run its own cleanup,
|
|
77
|
+
* so every build and `clean` sweeps the output directories it owns. Only the
|
|
78
|
+
* documented writer pattern matches; unreadable or missing directories are
|
|
79
|
+
* skipped, and the sweep is silent because the files were never artifacts.
|
|
80
|
+
*/
|
|
81
|
+
export async function sweepTemporaries(directories: readonly string[]): Promise<readonly string[]> {
|
|
82
|
+
const removed: string[] = [];
|
|
83
|
+
for (const directory of new Set(directories)) {
|
|
84
|
+
let entries: Dirent[];
|
|
85
|
+
try {
|
|
86
|
+
entries = await readdir(directory, { withFileTypes: true });
|
|
87
|
+
} catch {
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
for (const entry of entries) {
|
|
91
|
+
if (!entry.isFile() || !TEMPORARY_PATTERN.test(entry.name)) continue;
|
|
92
|
+
const path = join(directory, entry.name);
|
|
93
|
+
try {
|
|
94
|
+
await rm(path, { force: true });
|
|
95
|
+
removed.push(path);
|
|
96
|
+
} catch {
|
|
97
|
+
// Another process may hold it; a later build retries.
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return removed;
|
|
102
|
+
}
|