-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathat-value-parser.ts
More file actions
212 lines (194 loc) · 8 KB
/
at-value-parser.ts
File metadata and controls
212 lines (194 loc) · 8 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
import type { AtRule } from 'postcss';
import type { DiagnosticPosition, DiagnosticWithDetachedLocation, Location } from '../type.js';
import { JS_IDENTIFIER_PATTERN } from '../util.js';
interface ValueDeclaration {
type: 'valueDeclaration';
name: string;
// value: string; // unused
loc: Location;
/**
* NOTE: The `declarationLoc` for value declaration does not include the trailing semicolon.
* @example `@value white: #fff` has `declarationLoc` as `{ start: { line: 1, column: 1, offset: 0 }, end: { line: 1, column: 19, offset: 18 } }`.
*/
declarationLoc: Location;
}
interface ValueImportDeclaration {
type: 'valueImportDeclaration';
values: {
name: string;
loc: Location;
localName?: string;
localLoc?: Location;
}[];
from: string;
fromLoc: Location;
}
type ParsedAtValue = ValueDeclaration | ValueImportDeclaration;
interface ParseAtValueResult {
atValue?: ParsedAtValue;
diagnostics: DiagnosticWithDetachedLocation[];
}
const VALUE_IMPORT_PATTERN = /^(.+?)\s+from\s+("[^"]*"|'[^']*')$/du;
const VALUE_DEFINITION_PATTERN = /(?:\s+|^)([\w-]+):?(.*?)$/du;
const IMPORTED_ITEM_PATTERN = /^([\w-]+)(?:\s+as\s+([\w-]+))?/du;
/**
* Parse the `@value` rule.
* Forked from https://github.com/css-modules/postcss-modules-values/blob/v4.0.0/src/index.js.
*
* @license
* ISC License (ISC)
* Copyright (c) 2015, Glen Maddern
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
* provided that the above copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING
* ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH
* THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
// MEMO: css-modules-kit does not support `@value` with parentheses (e.g., `@value (a, b) from '...';`) to simplify the implementation.
// MEMO: css-modules-kit does not support `@value` with variable module name (e.g., `@value a from moduleName;`) to simplify the implementation.
export function parseAtValue(atValue: AtRule): ParseAtValueResult {
const matchesForValueImport = atValue.params.match(VALUE_IMPORT_PATTERN);
const diagnostics: DiagnosticWithDetachedLocation[] = [];
if (matchesForValueImport) {
const [, importedItems, from] = matchesForValueImport as [string, string, string];
// The length of the `@value ` part in `@value import1 from '...'`
const baseLength = 6 + (atValue.raws.afterName?.length ?? 0);
let lastItemIndex = 0;
const values: ValueImportDeclaration['values'] = [];
for (const alias of importedItems.split(/\s*,\s*/u)) {
const currentItemIndex = importedItems.indexOf(alias, lastItemIndex);
lastItemIndex = currentItemIndex;
const matchesForImportedItem = alias.match(IMPORTED_ITEM_PATTERN);
if (matchesForImportedItem) {
const [, name, localName] = matchesForImportedItem as [string, string, string | undefined];
const nameIndex = matchesForImportedItem.indices![1]![0];
const start = {
line: atValue.source!.start!.line,
column: atValue.source!.start!.column + baseLength + currentItemIndex + nameIndex,
offset: atValue.source!.start!.offset + baseLength + currentItemIndex + nameIndex,
};
const end = {
line: start.line,
column: start.column + name.length,
offset: start.offset + name.length,
};
if (!JS_IDENTIFIER_PATTERN.test(name)) {
diagnostics.push({
start: { line: start.line, column: start.column },
length: name.length,
text: `css-modules-kit does not support non-JavaScript identifier as value names.`,
category: 'error',
});
continue;
}
const result = { name, loc: { start, end } };
if (localName === undefined) {
values.push(result);
} else {
const localNameIndex = matchesForImportedItem.indices![2]![0];
const start = {
line: atValue.source!.start!.line,
column: atValue.source!.start!.column + baseLength + currentItemIndex + localNameIndex,
offset: atValue.source!.start!.offset + baseLength + currentItemIndex + localNameIndex,
};
const end = {
line: start.line,
column: start.column + localName.length,
offset: start.offset + localName.length,
};
if (!JS_IDENTIFIER_PATTERN.test(localName)) {
diagnostics.push({
start: { line: start.line, column: start.column },
length: localName.length,
text: `css-modules-kit does not support non-JavaScript identifier as value names.`,
category: 'error',
});
continue;
}
values.push({ ...result, localName, localLoc: { start, end } });
}
} else {
const start: DiagnosticPosition = {
line: atValue.source!.start!.line,
column: atValue.source!.start!.column + baseLength + currentItemIndex,
};
diagnostics.push({
start,
length: alias.length,
text: `\`${alias}\` is invalid syntax.`,
category: 'error',
});
}
}
// `from` is surrounded by quotes (e.g., `"./test.module.css"`). So, remove the quotes.
const normalizedFrom = from.slice(1, -1);
const fromIndex = matchesForValueImport.indices![2]![0] + 1;
const start = {
line: atValue.source!.start!.line,
column: atValue.source!.start!.column + baseLength + fromIndex,
offset: atValue.source!.start!.offset + baseLength + fromIndex,
};
const end = {
line: start.line,
column: start.column + normalizedFrom.length,
offset: start.offset + normalizedFrom.length,
};
const parsedAtValue: ValueImportDeclaration = {
type: 'valueImportDeclaration',
values,
from: normalizedFrom,
fromLoc: { start, end },
};
return { atValue: parsedAtValue, diagnostics };
}
const matchesForValueDefinition = `${atValue.params}${atValue.raws.between!}`.match(VALUE_DEFINITION_PATTERN);
if (matchesForValueDefinition) {
const [, name, _value] = matchesForValueDefinition;
if (name === undefined) throw new Error(`unreachable`);
/** The index of the `<name>` in `@value <name>: <value>;`. */
const nameIndex = 6 + (atValue.raws.afterName?.length ?? 0) + matchesForValueDefinition.indices![1]![0];
const start = {
line: atValue.source!.start!.line,
column: atValue.source!.start!.column + nameIndex,
offset: atValue.source!.start!.offset + nameIndex,
};
const end = {
line: start.line,
column: start.column + name.length,
offset: start.offset + name.length,
};
if (!JS_IDENTIFIER_PATTERN.test(name)) {
diagnostics.push({
start: { line: start.line, column: start.column },
length: name.length,
text: `css-modules-kit does not support non-JavaScript identifier as value names.`,
category: 'error',
});
return { diagnostics };
}
const parsedAtValue: ValueDeclaration = {
type: 'valueDeclaration',
name,
loc: { start, end },
declarationLoc: {
start: atValue.source!.start!,
end: atValue.positionBy({ index: atValue.toString().length }),
},
} as const;
return { atValue: parsedAtValue, diagnostics };
}
diagnostics.push({
start: {
line: atValue.source!.start!.line,
column: atValue.source!.start!.column,
},
length: atValue.source!.end!.offset - atValue.source!.start!.offset,
text: `\`${atValue.toString()}\` is a invalid syntax.`,
category: 'error',
});
return { diagnostics };
}