-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnode.js
More file actions
296 lines (294 loc) · 8.82 KB
/
node.js
File metadata and controls
296 lines (294 loc) · 8.82 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
import process from 'node:process';
import { ModuleScopeEnumOptions } from './lib/ast/types.js';
export { ColorType, EnumToken, ModuleCaseTransformEnum, ValidationLevel } from './lib/ast/types.js';
export { minify } from './lib/ast/minify.js';
export { WalkerEvent, WalkerOptionEnum, walk, walkValues } from './lib/ast/walk.js';
export { expand } from './lib/ast/expand.js';
import { doRender } from './lib/renderer/render.js';
export { renderToken } from './lib/renderer/render.js';
export { SourceMap } from './lib/renderer/sourcemap/sourcemap.js';
import { doParse } from './lib/parser/parse.js';
export { parseDeclarations, parseString, parseTokens } from './lib/parser/parse.js';
import { tokenizeStream, tokenize } from './lib/parser/tokenize.js';
import './lib/parser/utils/config.js';
export { convertColor } from './lib/syntax/color/color.js';
import './lib/syntax/color/utils/constants.js';
export { isOkLabClose, okLabDistance } from './lib/syntax/color/utils/distance.js';
import './lib/validation/config.js';
import './lib/validation/parser/parse.js';
import './lib/validation/syntaxes/complex-selector.js';
import './lib/validation/syntax.js';
import { resolve, matchUrl, dirname } from './lib/fs/resolve.js';
import { Readable } from 'node:stream';
import { createReadStream } from 'node:fs';
import { lstat, readFile } from 'node:fs/promises';
import { ResponseType } from './types.js';
export { FeatureWalkMode } from './lib/ast/features/type.js';
/**
* load file or url
* @param url
* @param currentDirectory
* @param responseType
* @throws Error file not found
*
* ```ts
* import {load, ResponseType} from '@tbela99/css-parser';
* const result = await load(file, '.', ResponseType.ArrayBuffer) as ArrayBuffer;
* ```
*/
async function load(url, currentDirectory = '.', responseType = false) {
const resolved = resolve(url, currentDirectory);
if (typeof responseType == 'boolean') {
responseType = responseType ? ResponseType.ReadableStream : ResponseType.Text;
}
if (matchUrl.test(resolved.absolute)) {
return fetch(resolved.absolute).then(async (response) => {
if (!response.ok) {
throw new Error(`${response.status} ${response.statusText} ${response.url}`);
}
if (responseType == ResponseType.ArrayBuffer) {
return response.arrayBuffer();
}
return responseType == ResponseType.ReadableStream ? response.body : response.text();
});
}
try {
const stats = await lstat(resolved.absolute);
if (stats.isFile()) {
if (responseType == ResponseType.Text) {
return readFile(resolved.absolute, 'utf-8');
}
if (responseType == ResponseType.ArrayBuffer) {
return readFile(resolved.absolute).then(buffer => buffer.buffer);
}
return Readable.toWeb(createReadStream(resolved.absolute, {
encoding: 'utf-8',
highWaterMark: 64 * 1024
}));
}
}
catch (error) {
console.warn(error);
}
throw new Error(`File not found: '${resolved.absolute || url}'`);
}
/**
* render the ast tree
* @param data
* @param options
* @param mapping
*
* Example:
*
* ```ts
*
* import {render, ColorType} from '@tbela99/css-parser';
*
* const css = 'body { color: color(from hsl(0 100% 50%) xyz x y z); }';
* const parseResult = await parse(css);
*
* let renderResult = render(parseResult.ast);
* console.log(result.code);
*
* // body{color:red}
*
*
* renderResult = render(parseResult.ast, {beautify: true, convertColor: ColorType.SRGB});
* console.log(renderResult.code);
*
* // body {
* // color: color(srgb 1 0 0)
* // }
* ```
*/
function render(data, options = {}, mapping) {
return doRender(data, Object.assign(options, { resolve, dirname, cwd: options.cwd ?? process.cwd() }), mapping);
}
/**
* parse css file
* @param file url or path
* @param options
* @param asStream load file as stream
*
* @throws Error file not found
*
* Example:
*
* ```ts
*
* import {parseFile} from '@tbela99/css-parser';
*
* // remote file
* let result = await parseFile('https://docs.deno.com/styles.css');
* console.log(result.ast);
*
* // local file
* result = await parseFile('./css/styles.css');
* console.log(result.ast);
* ```
*/
async function parseFile(file, options = {}, asStream = false) {
return Promise.resolve((options.load ?? load)(file, '.', asStream)).then(stream => parse(stream, { src: file, ...options }));
}
/**
* parse css
* @param stream
* @param options
*
* Example:
*
* ```ts
*
* import {parse} from '@tbela99/css-parser';
*
* // css string
* let result = await parse(css);
* console.log(result.ast);
* ```
*
* Example using stream
*
* ```ts
*
* import {parse} from '@tbela99/css-parser';
* import {Readable} from "node:stream";
*
* // usage: node index.ts < styles.css or cat styles.css | node index.ts
*
* const readableStream = Readable.toWeb(process.stdin);
* let result = await parse(readableStream, {beautify: true});
*
* console.log(result.ast);
* ```
*
* Example using fetch and readable stream
*
* ```ts
*
* import {parse} from '@tbela99/css-parser';
*
* const response = await fetch('https://docs.deno.com/styles.css');
* const result = await parse(response.body, {beautify: true});
*
* console.log(result.ast);
* ```
*/
async function parse(stream, options = {}) {
return doParse(stream instanceof ReadableStream ? tokenizeStream(stream) : tokenize({
stream,
buffer: '',
offset: 0,
position: { ind: 0, lin: 1, col: 1 },
currentPosition: { ind: -1, lin: 1, col: 0 }
}), Object.assign(options, {
load,
resolve,
dirname,
cwd: options.cwd ?? process.cwd()
})).then(result => {
const { revMapping, ...res } = result;
return res;
});
}
/**
* transform css file
* @param file url or path
* @param options
* @param asStream load file as stream
*
* @throws Error file not found
*
* Example:
*
* ```ts
*
* import {transformFile} from '@tbela99/css-parser';
*
* // remote file
* let result = await transformFile('https://docs.deno.com/styles.css');
* console.log(result.code);
*
* // local file
* result = await transformFile('./css/styles.css');
* console.log(result.code);
* ```
*/
async function transformFile(file, options = {}, asStream = false) {
return Promise.resolve((options.load ?? load)(file, '.', asStream)).then(stream => transform(stream, { src: file, ...options }));
}
/**
* transform css
* @param css
* @param options
*
* Example:
*
* ```ts
*
* import {transform} from '@tbela99/css-parser';
*
* // css string
* const result = await transform(css);
* console.log(result.code);
* ```
*
* Example using stream
*
* ```ts
*
* import {transform} from '@tbela99/css-parser';
* import {Readable} from "node:stream";
*
* // usage: node index.ts < styles.css or cat styles.css | node index.ts
*
* const readableStream = Readable.toWeb(process.stdin);
* const result = await transform(readableStream, {beautify: true});
*
* console.log(result.code);
* ```
*
* Example using fetch
*
* ```ts
*
* import {transform} from '@tbela99/css-parser';
*
* const response = await fetch('https://docs.deno.com/styles.css');
* result = await transform(response.body, {beautify: true});
*
* console.log(result.code);
* ```
*/
async function transform(css, options = {}) {
options = { minify: true, removeEmpty: true, removeCharset: true, ...options };
const startTime = performance.now();
return parse(css, options).then((parseResult) => {
let mapping = null;
let importMapping = null;
if (typeof options.module == 'number' && (options.module & ModuleScopeEnumOptions.ICSS)) {
mapping = parseResult.mapping;
importMapping = parseResult.importMapping;
}
else if (typeof options.module == 'object' && typeof options.module.scoped == 'number' && (options.module.scoped & ModuleScopeEnumOptions.ICSS)) {
mapping = parseResult.mapping;
importMapping = parseResult.importMapping;
}
// ast already expanded by parse
const rendered = render(parseResult.ast, {
...options,
expandNestingRules: false
}, mapping != null ? { mapping, importMapping } : null);
return {
...parseResult,
...rendered,
errors: parseResult.errors.concat(rendered.errors),
stats: {
bytesOut: rendered.code.length,
...parseResult.stats,
render: rendered.stats.total,
total: `${(performance.now() - startTime).toFixed(2)}ms`
}
};
});
}
export { ModuleScopeEnumOptions, ResponseType, dirname, load, parse, parseFile, render, resolve, transform, transformFile };