@chikx/compiler 0.1.0 → 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.
Files changed (85) hide show
  1. package/README.md +5 -5
  2. package/package.json +3 -3
  3. package/src/emitter/index.ts +658 -0
  4. package/src/formatter/index.ts +544 -0
  5. package/src/host/node.ts +85 -0
  6. package/src/index.ts +1021 -0
  7. package/src/ir/factories.ts +85 -0
  8. package/src/ir/index.ts +28 -0
  9. package/src/ir/types.ts +145 -0
  10. package/src/lexer/at-keywords.ts +35 -0
  11. package/src/lexer/characters.ts +82 -0
  12. package/src/lexer/comments.ts +27 -0
  13. package/src/lexer/diagnostics.ts +42 -0
  14. package/src/lexer/dollar-refs.ts +23 -0
  15. package/src/lexer/index.ts +37 -0
  16. package/src/lexer/names.ts +49 -0
  17. package/src/lexer/numbers.ts +59 -0
  18. package/src/lexer/scanner.ts +199 -0
  19. package/src/lexer/strings.ts +52 -0
  20. package/src/lexer/urls.ts +63 -0
  21. package/src/lowering/expand-groups.ts +206 -0
  22. package/src/lowering/group.ts +119 -0
  23. package/src/lowering/index.ts +43 -0
  24. package/src/lowering/lower.ts +441 -0
  25. package/src/lowering/media.ts +314 -0
  26. package/src/lowering/merge.ts +163 -0
  27. package/src/lowering/property-families.ts +194 -0
  28. package/src/lowering/spans.ts +118 -0
  29. package/src/naming/index.ts +44 -0
  30. package/src/naming/mapgen.ts +252 -0
  31. package/src/naming/merge.ts +114 -0
  32. package/src/naming/rewrite.ts +333 -0
  33. package/src/naming/scan.ts +267 -0
  34. package/src/naming/table.ts +153 -0
  35. package/src/naming/types.ts +100 -0
  36. package/src/output/import-path.ts +30 -0
  37. package/src/output/index.ts +213 -0
  38. package/src/output/manifest.ts +28 -0
  39. package/src/output/paths.ts +200 -0
  40. package/src/output/resolve.ts +401 -0
  41. package/src/output/validate.ts +251 -0
  42. package/src/parser/cursor.ts +138 -0
  43. package/src/parser/declaration.ts +247 -0
  44. package/src/parser/diagnostics.ts +75 -0
  45. package/src/parser/group.ts +303 -0
  46. package/src/parser/index.ts +50 -0
  47. package/src/parser/modifier.ts +60 -0
  48. package/src/parser/recovery.ts +88 -0
  49. package/src/parser/rule.ts +370 -0
  50. package/src/parser/statement.ts +47 -0
  51. package/src/parser/statements.ts +667 -0
  52. package/src/parser/value.ts +265 -0
  53. package/src/resolver/graph.ts +467 -0
  54. package/src/resolver/groups.ts +177 -0
  55. package/src/resolver/index.ts +68 -0
  56. package/src/resolver/keyframes.ts +131 -0
  57. package/src/resolver/paths.ts +142 -0
  58. package/src/resolver/rules.ts +54 -0
  59. package/src/resolver/scopes.ts +342 -0
  60. package/src/resolver/types.ts +259 -0
  61. package/src/selectors/flatten.ts +448 -0
  62. package/src/selectors/index.ts +14 -0
  63. package/src/selectors/scan.ts +227 -0
  64. package/src/selectors/specificity.ts +319 -0
  65. package/src/setup-list.ts +172 -0
  66. package/src/sourcemaps/index.ts +25 -0
  67. package/src/sourcemaps/mappings.ts +190 -0
  68. package/src/sourcemaps/vlq.ts +29 -0
  69. package/src/types/ast.ts +318 -0
  70. package/src/types/diagnostics.ts +124 -0
  71. package/src/types/options.ts +286 -0
  72. package/src/types/result.ts +121 -0
  73. package/src/types/span.ts +18 -0
  74. package/src/types/token.ts +77 -0
  75. package/src/variables/ast.ts +182 -0
  76. package/src/variables/expand.ts +319 -0
  77. package/src/variables/index.ts +38 -0
  78. package/src/variables/naming.ts +46 -0
  79. package/src/variables/runtime.ts +336 -0
  80. package/src/variables/substitute.ts +148 -0
  81. package/src/variables/walk.ts +147 -0
  82. package/dist/output/importPath.d.ts +0 -27
  83. package/dist/output/importPath.d.ts.map +0 -1
  84. package/dist/output/importPath.js +0 -84
  85. package/dist/output/importPath.js.map +0 -1
@@ -0,0 +1,319 @@
1
+ import { isWhitespace, scanSelector, splitSelectorList } from "./scan.js";
2
+
3
+ /**
4
+ * Selector specificity estimation used only to decide whether a parent
5
+ * selector list may be expanded as a cross-product (`A, B` → `A x, B x`) or
6
+ * must be substituted as `:is(A, B)` (SPECIFICATION.md §7.1).
7
+ *
8
+ * The estimator is deliberately conservative: any construct it does not model
9
+ * returns `null`, and callers then fall back to `:is(...)`, which always
10
+ * preserves native nesting semantics. It is not a public validator.
11
+ */
12
+
13
+ /** CSS specificity triple, ordered from IDs to type selectors. */
14
+ export interface Specificity {
15
+ /** Number of ID selectors. */
16
+ readonly a: number;
17
+ /** Number of class, attribute and pseudo-class selectors. */
18
+ readonly b: number;
19
+ /** Number of type and pseudo-element selectors. */
20
+ readonly c: number;
21
+ }
22
+
23
+ /** Compare two specificity triples lexicographically. */
24
+ export function compareSpecificity(left: Specificity, right: Specificity): number {
25
+ if (left.a !== right.a) return left.a - right.a;
26
+ if (left.b !== right.b) return left.b - right.b;
27
+ return left.c - right.c;
28
+ }
29
+
30
+ /** Add two specificity triples, used when combining a parent and a child. */
31
+ export function addSpecificity(
32
+ left: Specificity | null,
33
+ right: Specificity | null,
34
+ ): Specificity | null {
35
+ if (left === null || right === null) return null;
36
+ return { a: left.a + right.a, b: left.b + right.b, c: left.c + right.c };
37
+ }
38
+
39
+ /** Largest specificity in a selector list, or `null` when any item is unknown. */
40
+ function maxSpecificityOfList(text: string): Specificity | null {
41
+ const split = splitSelectorList(text);
42
+ if (!split.ok) return null;
43
+ let max: Specificity | null = null;
44
+ for (const item of split.items) {
45
+ const one = specificityOfItem(item);
46
+ if (one === null) return null;
47
+ if (max === null || compareSpecificity(one, max) > 0) max = one;
48
+ }
49
+ return max;
50
+ }
51
+
52
+ /** Read a CSS name (ident or hash/class name), honoring backslash escapes. */
53
+ function readName(text: string, start: number): number {
54
+ let index = start;
55
+ while (index < text.length) {
56
+ const character = text.charAt(index);
57
+ if (character === "\\") {
58
+ index += 2;
59
+ continue;
60
+ }
61
+ if (/[A-Za-z0-9_-]/.test(character) || character.charCodeAt(0) >= 0x80) {
62
+ index += 1;
63
+ continue;
64
+ }
65
+ break;
66
+ }
67
+ return index;
68
+ }
69
+
70
+ /**
71
+ * Return the index just past the matching closer for the `(` or `[` at
72
+ * `openIndex`, or `-1` when it is unbalanced.
73
+ */
74
+ function skipBalanced(text: string, openIndex: number): number {
75
+ const open = text.charAt(openIndex);
76
+ if (open !== "(" && open !== "[") return -1;
77
+ const closers: string[] = [open === "(" ? ")" : "]"];
78
+ let quote: '"' | "'" | null = null;
79
+ let inComment = false;
80
+ let escaped = false;
81
+
82
+ for (let index = openIndex + 1; index < text.length; index += 1) {
83
+ const character = text.charAt(index);
84
+ if (inComment) {
85
+ if (character === "*" && text.charAt(index + 1) === "/") {
86
+ inComment = false;
87
+ index += 1;
88
+ }
89
+ continue;
90
+ }
91
+ if (quote !== null) {
92
+ if (escaped) {
93
+ escaped = false;
94
+ continue;
95
+ }
96
+ if (character === "\\") {
97
+ escaped = true;
98
+ continue;
99
+ }
100
+ if (character === quote) quote = null;
101
+ continue;
102
+ }
103
+ if (escaped) {
104
+ escaped = false;
105
+ continue;
106
+ }
107
+ if (character === "\\") {
108
+ escaped = true;
109
+ continue;
110
+ }
111
+ if (character === "/" && text.charAt(index + 1) === "*") {
112
+ inComment = true;
113
+ index += 1;
114
+ continue;
115
+ }
116
+ if (character === '"' || character === "'") {
117
+ quote = character;
118
+ continue;
119
+ }
120
+ if (character === "(") {
121
+ closers.push(")");
122
+ continue;
123
+ }
124
+ if (character === "[") {
125
+ closers.push("]");
126
+ continue;
127
+ }
128
+ if (character === ")" || character === "]") {
129
+ if (closers.pop() !== character) return -1;
130
+ if (closers.length === 0) return index + 1;
131
+ }
132
+ }
133
+ return -1;
134
+ }
135
+
136
+ /** Pseudo-class names whose arguments are selectors, scored with `:is` semantics. */
137
+ const SELECTOR_ARGUMENT_PSEUDOS: ReadonlySet<string> = new Set([
138
+ "is",
139
+ "not",
140
+ "has",
141
+ "matches",
142
+ "any",
143
+ "global",
144
+ ]);
145
+
146
+ /** Pseudo-class names whose arguments are An+B or other values, never selectors. */
147
+ const VALUE_ARGUMENT_PSEUDOS: ReadonlySet<string> = new Set(["lang", "dir", "state"]);
148
+
149
+ /** Legacy single-colon pseudo-elements counted in the type column. */
150
+ const LEGACY_PSEUDO_ELEMENTS: ReadonlySet<string> = new Set([
151
+ "before",
152
+ "after",
153
+ "first-line",
154
+ "first-letter",
155
+ ]);
156
+
157
+ /**
158
+ * Specificity of one selector (not a list), or `null` when the text contains a
159
+ * construct this estimator does not model.
160
+ */
161
+ export function specificityOfItem(text: string): Specificity | null {
162
+ const scan = scanSelector(text);
163
+ if (!scan.ok || scan.commas.length > 0) return null;
164
+
165
+ let a = 0;
166
+ let b = 0;
167
+ let c = 0;
168
+ let index = 0;
169
+
170
+ while (index < text.length) {
171
+ const character = text.charAt(index);
172
+
173
+ if (isWhitespace(character) || character === ">" || character === "+" || character === "~") {
174
+ index += 1;
175
+ continue;
176
+ }
177
+ if (character === "|" && text.charAt(index + 1) === "|") {
178
+ index += 2;
179
+ continue;
180
+ }
181
+ if (character === "," || character === "&") return null;
182
+ if (character === "|") return null;
183
+
184
+ if (character === "/" && text.charAt(index + 1) === "*") {
185
+ const end = text.indexOf("*/", index + 2);
186
+ if (end === -1) return null;
187
+ index = end + 2;
188
+ continue;
189
+ }
190
+
191
+ if (character === "#") {
192
+ const end = readName(text, index + 1);
193
+ if (end === index + 1) return null;
194
+ a += 1;
195
+ index = end;
196
+ continue;
197
+ }
198
+
199
+ if (character === ".") {
200
+ const end = readName(text, index + 1);
201
+ if (end === index + 1) return null;
202
+ b += 1;
203
+ index = end;
204
+ continue;
205
+ }
206
+
207
+ if (character === "[") {
208
+ const end = skipBalanced(text, index);
209
+ if (end === -1) return null;
210
+ b += 1;
211
+ index = end;
212
+ continue;
213
+ }
214
+
215
+ if (character === "*") {
216
+ if (text.charAt(index + 1) === "|" && text.charAt(index + 2) !== "|") {
217
+ index += 2;
218
+ continue;
219
+ }
220
+ index += 1;
221
+ continue;
222
+ }
223
+
224
+ if (character === ":") {
225
+ const doubleColon = text.charAt(index + 1) === ":";
226
+ const nameStart = index + (doubleColon ? 2 : 1);
227
+ const nameEnd = readName(text, nameStart);
228
+ if (nameEnd === nameStart) return null;
229
+ const name = text.slice(nameStart, nameEnd).toLowerCase();
230
+ const hasArguments = text.charAt(nameEnd) === "(";
231
+
232
+ if (doubleColon) {
233
+ c += 1;
234
+ if (!hasArguments) {
235
+ index = nameEnd;
236
+ continue;
237
+ }
238
+ const end = skipBalanced(text, nameEnd);
239
+ if (end === -1) return null;
240
+ index = end;
241
+ continue;
242
+ }
243
+
244
+ if (name === "where") {
245
+ if (!hasArguments) {
246
+ index = nameEnd;
247
+ continue;
248
+ }
249
+ const end = skipBalanced(text, nameEnd);
250
+ if (end === -1) return null;
251
+ index = end;
252
+ continue;
253
+ }
254
+
255
+ if (SELECTOR_ARGUMENT_PSEUDOS.has(name)) {
256
+ if (!hasArguments) return null;
257
+ const end = skipBalanced(text, nameEnd);
258
+ if (end === -1) return null;
259
+ const inner = text.slice(nameEnd + 1, end - 1);
260
+ const max = maxSpecificityOfList(inner);
261
+ if (max === null) return null;
262
+ a += max.a;
263
+ b += max.b;
264
+ c += max.c;
265
+ index = end;
266
+ continue;
267
+ }
268
+
269
+ if (name === "host" || name === "host-context" || name === "slotted") return null;
270
+
271
+ if (LEGACY_PSEUDO_ELEMENTS.has(name)) {
272
+ c += 1;
273
+ index = nameEnd;
274
+ continue;
275
+ }
276
+
277
+ if (name.startsWith("nth-")) {
278
+ b += 1;
279
+ if (!hasArguments) {
280
+ index = nameEnd;
281
+ continue;
282
+ }
283
+ const end = skipBalanced(text, nameEnd);
284
+ if (end === -1) return null;
285
+ const inner = text.slice(nameEnd + 1, end - 1);
286
+ if (/\bof\b/i.test(inner)) return null;
287
+ index = end;
288
+ continue;
289
+ }
290
+
291
+ b += 1;
292
+ if (!hasArguments) {
293
+ index = nameEnd;
294
+ continue;
295
+ }
296
+ if (!VALUE_ARGUMENT_PSEUDOS.has(name)) return null;
297
+ const end = skipBalanced(text, nameEnd);
298
+ if (end === -1) return null;
299
+ index = end;
300
+ continue;
301
+ }
302
+
303
+ if (character === "\\" || /[A-Za-z_-]/.test(character) || character.charCodeAt(0) >= 0x80) {
304
+ const end = readName(text, index);
305
+ if (end === index) return null;
306
+ if (text.charAt(end) === "|" && text.charAt(end + 1) !== "|") {
307
+ index = end + 1;
308
+ continue;
309
+ }
310
+ c += 1;
311
+ index = end;
312
+ continue;
313
+ }
314
+
315
+ return null;
316
+ }
317
+
318
+ return { a, b, c };
319
+ }
@@ -0,0 +1,172 @@
1
+ /**
2
+ * Comma-separated `@setup` value lists (ADR-0019).
3
+ *
4
+ * Only `css-dir` accepts a list in v0.1. Values are split on top-level commas
5
+ * (commas inside quotes stay literal), each item is decoded as a CSS string
6
+ * scalar, and empty or duplicate items become CHIKX2001 setup errors with a span
7
+ * inside the authored value. A value without a top-level comma keeps the
8
+ * single-scalar behaviour exactly.
9
+ */
10
+
11
+ import { normalizePath } from "./output/paths.js";
12
+ import { decodeCssString } from "./resolver/paths.js";
13
+ import { error } from "./types/diagnostics.js";
14
+ import type { Diagnostic } from "./types/diagnostics.js";
15
+ import type { Span } from "./types/span.js";
16
+
17
+ /** One decoded item in an authored list. */
18
+ export interface SetupListEntry {
19
+ /** Decoded scalar: quotes removed and CSS escapes resolved. */
20
+ readonly value: string;
21
+ /** Covers the trimmed authored item, quotes included. */
22
+ readonly span: Span;
23
+ }
24
+
25
+ /** Result of {@link decodeSetupList}. */
26
+ export interface SetupListResult {
27
+ /** Valid decoded items in authored order; empty items contribute nothing. */
28
+ readonly entries: readonly SetupListEntry[];
29
+ /** Whether a top-level comma was authored (single values keep legacy rules). */
30
+ readonly isList: boolean;
31
+ /** CHIKX2001 diagnostics for empty and duplicate items, in authored order. */
32
+ readonly diagnostics: readonly Diagnostic[];
33
+ }
34
+
35
+ interface RawSegment {
36
+ readonly raw: string;
37
+ readonly start: number;
38
+ readonly end: number;
39
+ /** Absolute offset of the comma that precedes this segment, or `-1`. */
40
+ readonly commaBefore: number;
41
+ }
42
+
43
+ /**
44
+ * Decode an authored `@setup` value that may be a comma-separated list.
45
+ *
46
+ * @param raw Raw value slice exactly as authored (quotes included).
47
+ * @param span Span of {@link raw} within the source, used for item diagnostics.
48
+ * @returns Valid entries, whether the value was a list, and CHIKX2001 errors.
49
+ */
50
+ export function decodeSetupList(raw: string, span: Span): SetupListResult {
51
+ const segments = splitSegments(raw, span);
52
+ const isList = segments.length > 1;
53
+ const entries: SetupListEntry[] = [];
54
+ const diagnostics: Diagnostic[] = [];
55
+ const seen = new Map<string, SetupListEntry>();
56
+
57
+ for (const segment of segments) {
58
+ const content = trimBounds(segment);
59
+ if (content === undefined) {
60
+ diagnostics.push(
61
+ error(
62
+ "CHIKX2001",
63
+ '@setup "css-dir" list contains an empty directory item.',
64
+ emptyItemSpan(segment, span.file),
65
+ ),
66
+ );
67
+ continue;
68
+ }
69
+ const entry: SetupListEntry = Object.freeze({
70
+ value: decodeSetupScalar(segment.raw.slice(content.start, content.end)),
71
+ span: {
72
+ start: segment.start + content.start,
73
+ end: segment.start + content.end,
74
+ file: span.file,
75
+ },
76
+ });
77
+ if (entry.value === "") {
78
+ diagnostics.push(
79
+ error("CHIKX2001", '@setup "css-dir" list contains an empty directory item.', entry.span),
80
+ );
81
+ continue;
82
+ }
83
+ if (seen.has(normalizePath(entry.value))) {
84
+ diagnostics.push(
85
+ error(
86
+ "CHIKX2001",
87
+ `Duplicate directory "${entry.value}" in the @setup "css-dir" list.`,
88
+ entry.span,
89
+ ),
90
+ );
91
+ continue;
92
+ }
93
+ seen.set(normalizePath(entry.value), entry);
94
+ entries.push(entry);
95
+ }
96
+
97
+ return Object.freeze({
98
+ entries: Object.freeze(entries),
99
+ isList,
100
+ diagnostics: Object.freeze(diagnostics),
101
+ });
102
+ }
103
+
104
+ /**
105
+ * Decode a setup scalar: quoted values lose their quotes and CSS escapes,
106
+ * unquoted values are trimmed verbatim.
107
+ */
108
+ export function decodeSetupScalar(raw: string): string {
109
+ const trimmed = raw.trim();
110
+ if (trimmed.length >= 2) {
111
+ const first = trimmed.charAt(0);
112
+ const last = trimmed.charAt(trimmed.length - 1);
113
+ if ((first === '"' && last === '"') || (first === "'" && last === "'")) {
114
+ return decodeCssString(trimmed.slice(1, -1));
115
+ }
116
+ }
117
+ return trimmed;
118
+ }
119
+
120
+ function splitSegments(raw: string, span: Span): RawSegment[] {
121
+ const segments: RawSegment[] = [];
122
+ let start = 0;
123
+ let quote: string | undefined;
124
+ let escaped = false;
125
+ let commaBefore = -1;
126
+
127
+ for (let index = 0; index <= raw.length; index++) {
128
+ const atEnd = index === raw.length;
129
+ const character = atEnd ? "" : raw.charAt(index);
130
+
131
+ if (!atEnd && quote !== undefined) {
132
+ if (escaped) escaped = false;
133
+ else if (character === "\\") escaped = true;
134
+ else if (character === quote) quote = undefined;
135
+ continue;
136
+ }
137
+ if (!atEnd && (character === '"' || character === "'")) {
138
+ quote = character;
139
+ continue;
140
+ }
141
+ if (atEnd || character === ",") {
142
+ segments.push({
143
+ raw: raw.slice(start, index),
144
+ start: span.start + start,
145
+ end: span.start + index,
146
+ commaBefore,
147
+ });
148
+ if (!atEnd) {
149
+ commaBefore = span.start + index;
150
+ start = index + 1;
151
+ }
152
+ }
153
+ }
154
+
155
+ return segments;
156
+ }
157
+
158
+ /** Trimmed content offsets inside a raw segment, or `undefined` when empty. */
159
+ function trimBounds(
160
+ segment: RawSegment,
161
+ ): { readonly start: number; readonly end: number } | undefined {
162
+ const leading = segment.raw.length - segment.raw.trimStart().length;
163
+ const trailing = segment.raw.length - segment.raw.trimEnd().length;
164
+ if (leading === segment.raw.length) return undefined;
165
+ return { start: leading, end: segment.raw.length - trailing };
166
+ }
167
+
168
+ /** A non-empty span at the gap an empty item leaves (the comma when possible). */
169
+ function emptyItemSpan(segment: RawSegment, file: string): Span {
170
+ const start = segment.commaBefore >= 0 ? segment.commaBefore : segment.start;
171
+ return { start, end: Math.max(start + 1, segment.end), file };
172
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Zero-dependency CSS source-map support (standard v3).
3
+ *
4
+ * The public surface is intentionally small: {@link encodeVlq} for the encoding
5
+ * primitive, {@link encodeMappings} and {@link generateSourceMap} for assembly,
6
+ * {@link serializeSourceMap} for text artifacts, and the locating helpers used
7
+ * by the emitter to turn authored UTF-16 spans into line/column pairs. Mapping
8
+ * granularity is documented in `./mappings.ts`: one mapping per emitted rule
9
+ * selector and per emitted declaration.
10
+ */
11
+
12
+ export {
13
+ encodeMappings,
14
+ generateSourceMap,
15
+ offsetToLineColumn,
16
+ serializeSourceMap,
17
+ sourceMapComment,
18
+ sourceMapUrlFor,
19
+ } from "./mappings.js";
20
+ export type {
21
+ GenerateSourceMapOptions,
22
+ SourceMapV3,
23
+ SourceMapping,
24
+ } from "./mappings.js";
25
+ export { encodeVlq } from "./vlq.js";
@@ -0,0 +1,190 @@
1
+ /**
2
+ * Standard v3 source-map assembly for emitted CSS.
3
+ *
4
+ * Granularity is declaration-level: the emitter records one mapping for each
5
+ * emitted rule selector and one for each emitted declaration property. Tokens
6
+ * inside a selector or value are not mapped individually, so no `names` array
7
+ * is needed. Generated and source positions are zero-based here because that is
8
+ * what the v3 `mappings` payload encodes; callers deriving positions from UTF-16
9
+ * offsets get one-based lines/columns from {@link offsetToLineColumn} and must
10
+ * subtract one.
11
+ */
12
+
13
+ import { encodeVlq } from "./vlq.js";
14
+
15
+ /** One decoded mapping between an emitted CSS position and an authored source. */
16
+ export interface SourceMapping {
17
+ /** Zero-based line in the emitted CSS. */
18
+ readonly generatedLine: number;
19
+ /** Zero-based column in the emitted CSS. */
20
+ readonly generatedColumn: number;
21
+ /** Workspace-relative POSIX path of the authored source file. */
22
+ readonly source: string;
23
+ /** Zero-based line in the authored source. */
24
+ readonly sourceLine: number;
25
+ /** Zero-based UTF-16 column in the authored source. */
26
+ readonly sourceColumn: number;
27
+ }
28
+
29
+ /** A rendered source-map v3 document. */
30
+ export interface SourceMapV3 {
31
+ /** Always `3`. */
32
+ readonly version: 3;
33
+ /** Planned CSS output basename, when known. */
34
+ readonly file?: string;
35
+ /** Optional prefix applied to every `sources` entry. */
36
+ readonly sourceRoot?: string;
37
+ /** Distinct authored sources in deterministic (sorted) order. */
38
+ readonly sources: readonly string[];
39
+ /** Optional authored text parallel to `sources`. */
40
+ readonly sourcesContent?: readonly (string | null)[];
41
+ /** VLQ-encoded mappings, standard segment format. */
42
+ readonly mappings: string;
43
+ }
44
+
45
+ /** Options for {@link generateSourceMap}. */
46
+ export interface GenerateSourceMapOptions {
47
+ /** Planned CSS output basename recorded in the map `file` field. */
48
+ readonly file?: string;
49
+ /** Optional `sourceRoot` for environments that relocate sources. */
50
+ readonly sourceRoot?: string;
51
+ /** Authored text per source, included as `sourcesContent` when supplied. */
52
+ readonly sourcesContent?: Readonly<Record<string, string>>;
53
+ }
54
+
55
+ /**
56
+ * Encode mappings as a standard v3 `mappings` string.
57
+ *
58
+ * Segments are sorted by generated line and column; the generated-column delta
59
+ * resets on each line while source, source-line and source-column deltas carry
60
+ * across the whole document, exactly as the v3 specification requires. Sources
61
+ * missing from `sources` are skipped rather than producing an invalid index.
62
+ */
63
+ export function encodeMappings(
64
+ mappings: readonly SourceMapping[],
65
+ sources: readonly string[],
66
+ ): string {
67
+ const indexBySource = new Map<string, number>();
68
+ for (let index = 0; index < sources.length; index += 1) {
69
+ const source = sources[index];
70
+ if (source !== undefined) indexBySource.set(source, index);
71
+ }
72
+
73
+ const sorted = [...mappings].sort(
74
+ (left, right) =>
75
+ left.generatedLine - right.generatedLine || left.generatedColumn - right.generatedColumn,
76
+ );
77
+ const lines: string[][] = [];
78
+ let lastSource = 0;
79
+ let lastSourceLine = 0;
80
+ let lastSourceColumn = 0;
81
+ let currentLine = -1;
82
+ let previousColumn = 0;
83
+ let previous: SourceMapping | undefined;
84
+
85
+ for (const mapping of sorted) {
86
+ const sourceIndex = indexBySource.get(mapping.source);
87
+ if (sourceIndex === undefined) continue;
88
+ if (
89
+ previous !== undefined &&
90
+ previous.generatedLine === mapping.generatedLine &&
91
+ previous.generatedColumn === mapping.generatedColumn &&
92
+ previous.source === mapping.source &&
93
+ previous.sourceLine === mapping.sourceLine &&
94
+ previous.sourceColumn === mapping.sourceColumn
95
+ ) {
96
+ continue;
97
+ }
98
+
99
+ if (mapping.generatedLine !== currentLine) {
100
+ currentLine = mapping.generatedLine;
101
+ previousColumn = 0;
102
+ }
103
+
104
+ const segment =
105
+ encodeVlq(mapping.generatedColumn - previousColumn) +
106
+ encodeVlq(sourceIndex - lastSource) +
107
+ encodeVlq(mapping.sourceLine - lastSourceLine) +
108
+ encodeVlq(mapping.sourceColumn - lastSourceColumn);
109
+
110
+ let line = lines[currentLine];
111
+ if (line === undefined) {
112
+ line = [];
113
+ lines[currentLine] = line;
114
+ }
115
+ line.push(segment);
116
+ previousColumn = mapping.generatedColumn;
117
+ lastSource = sourceIndex;
118
+ lastSourceLine = mapping.sourceLine;
119
+ lastSourceColumn = mapping.sourceColumn;
120
+ previous = mapping;
121
+ }
122
+
123
+ const maxLine = lines.length - 1;
124
+ const encoded: string[] = [];
125
+ for (let line = 0; line <= maxLine; line += 1) {
126
+ encoded.push((lines[line] ?? []).join(","));
127
+ }
128
+ return encoded.join(";");
129
+ }
130
+
131
+ /** Build the complete v3 document for a set of mappings. */
132
+ export function generateSourceMap(
133
+ mappings: readonly SourceMapping[],
134
+ options: GenerateSourceMapOptions = {},
135
+ ): SourceMapV3 {
136
+ const sources = [...new Set(mappings.map((mapping) => mapping.source))].sort();
137
+ const sourcesContent =
138
+ options.sourcesContent === undefined
139
+ ? undefined
140
+ : sources.map((source) => options.sourcesContent?.[source] ?? null);
141
+
142
+ return {
143
+ version: 3,
144
+ ...(options.file === undefined ? {} : { file: options.file }),
145
+ ...(options.sourceRoot === undefined ? {} : { sourceRoot: options.sourceRoot }),
146
+ sources,
147
+ ...(sourcesContent === undefined ? {} : { sourcesContent }),
148
+ mappings: encodeMappings(mappings, sources),
149
+ };
150
+ }
151
+
152
+ /** Serialize a v3 map as deterministic JSON text with a trailing newline. */
153
+ export function serializeSourceMap(map: SourceMapV3): string {
154
+ return `${JSON.stringify(map)}\n`;
155
+ }
156
+
157
+ /**
158
+ * Convert a UTF-16 offset into a one-based line and column.
159
+ *
160
+ * Offsets past the end are clamped. Line breaks are `\n`; a `\r\n` sequence
161
+ * therefore moves the column past the `\r` before the line break resets it,
162
+ * matching the tokenizer's line accounting.
163
+ */
164
+ export function offsetToLineColumn(
165
+ text: string,
166
+ offset: number,
167
+ ): { readonly line: number; readonly column: number } {
168
+ const limit = Math.max(0, Math.min(offset, text.length));
169
+ let line = 1;
170
+ let column = 1;
171
+ for (let index = 0; index < limit; index += 1) {
172
+ if (text.charAt(index) === "\n") {
173
+ line += 1;
174
+ column = 1;
175
+ } else {
176
+ column += 1;
177
+ }
178
+ }
179
+ return { line, column };
180
+ }
181
+
182
+ /** The `sourceMappingURL` value for a planned CSS output basename. */
183
+ export function sourceMapUrlFor(cssFile: string): string {
184
+ return `${cssFile}.map`;
185
+ }
186
+
187
+ /** The CSS comment that points at a planned source-map artifact. */
188
+ export function sourceMapComment(cssFile: string): string {
189
+ return `/*# sourceMappingURL=${sourceMapUrlFor(cssFile)} */`;
190
+ }