@knighted/css 1.0.0-rc.1 → 1.0.0-rc.11

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 (51) hide show
  1. package/bin/generate-types.js +31 -0
  2. package/dist/cjs/css.cjs +100 -22
  3. package/dist/cjs/css.d.cts +5 -6
  4. package/dist/cjs/generateTypes.cjs +683 -0
  5. package/dist/cjs/generateTypes.d.cts +108 -0
  6. package/dist/cjs/loader.cjs +65 -55
  7. package/dist/cjs/loader.d.cts +1 -0
  8. package/dist/cjs/loaderInternals.cjs +108 -0
  9. package/dist/cjs/loaderInternals.d.cts +23 -0
  10. package/dist/cjs/moduleGraph.cjs +431 -0
  11. package/dist/cjs/moduleGraph.d.cts +15 -0
  12. package/dist/cjs/moduleInfo.cjs +62 -0
  13. package/dist/cjs/moduleInfo.d.cts +10 -0
  14. package/dist/cjs/sassInternals.cjs +135 -0
  15. package/dist/cjs/sassInternals.d.cts +25 -0
  16. package/dist/cjs/stableNamespace.cjs +12 -0
  17. package/dist/cjs/stableNamespace.d.cts +3 -0
  18. package/dist/cjs/stableSelectors.cjs +44 -0
  19. package/dist/cjs/stableSelectors.d.cts +13 -0
  20. package/dist/cjs/stableSelectorsLiteral.cjs +104 -0
  21. package/dist/cjs/stableSelectorsLiteral.d.cts +19 -0
  22. package/dist/cjs/types.cjs +2 -0
  23. package/dist/cjs/types.d.cts +4 -0
  24. package/dist/css.d.ts +5 -6
  25. package/dist/css.js +101 -23
  26. package/dist/generateTypes.d.ts +108 -0
  27. package/dist/generateTypes.js +675 -0
  28. package/dist/loader.d.ts +1 -0
  29. package/dist/loader.js +63 -53
  30. package/dist/loaderInternals.d.ts +23 -0
  31. package/dist/loaderInternals.js +96 -0
  32. package/dist/moduleGraph.d.ts +15 -0
  33. package/dist/moduleGraph.js +425 -0
  34. package/dist/moduleInfo.d.ts +10 -0
  35. package/dist/moduleInfo.js +55 -0
  36. package/dist/sassInternals.d.ts +25 -0
  37. package/dist/sassInternals.js +124 -0
  38. package/dist/stableNamespace.d.ts +3 -0
  39. package/dist/stableNamespace.js +8 -0
  40. package/dist/stableSelectors.d.ts +13 -0
  41. package/dist/stableSelectors.js +36 -0
  42. package/dist/stableSelectorsLiteral.d.ts +19 -0
  43. package/dist/stableSelectorsLiteral.js +98 -0
  44. package/dist/types.d.ts +4 -0
  45. package/dist/types.js +1 -0
  46. package/loader-queries.d.ts +61 -0
  47. package/package.json +58 -8
  48. package/stable/_index.scss +57 -0
  49. package/stable/stable.css +15 -0
  50. package/types-stub/index.d.ts +5 -0
  51. package/types.d.ts +4 -0
@@ -0,0 +1,431 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.collectStyleImports = collectStyleImports;
7
+ const node_path_1 = __importDefault(require("node:path"));
8
+ const node_module_1 = require("node:module");
9
+ const node_fs_1 = require("node:fs");
10
+ const node_url_1 = require("node:url");
11
+ const oxc_parser_1 = require("oxc-parser");
12
+ const oxc_resolver_1 = require("oxc-resolver");
13
+ const tsconfig_paths_1 = require("tsconfig-paths");
14
+ const get_tsconfig_1 = require("get-tsconfig");
15
+ const SCRIPT_EXTENSIONS = ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs'];
16
+ const BUILTIN_SPECIFIERS = new Set([
17
+ ...node_module_1.builtinModules,
18
+ ...node_module_1.builtinModules.map(mod => `node:${mod}`),
19
+ ]);
20
+ const tsconfigResultCache = new Map();
21
+ const tsconfigFsCache = new Map();
22
+ async function collectStyleImports(entryPath, options) {
23
+ const { cwd, styleExtensions, filter, resolver, graphOptions } = options;
24
+ const normalizedStyles = normalizeExtensions(styleExtensions);
25
+ const scriptExtensions = normalizeExtensions([
26
+ ...SCRIPT_EXTENSIONS,
27
+ ...(graphOptions?.extensions ?? []),
28
+ ]);
29
+ const resolutionExtensions = dedupeExtensions([
30
+ ...scriptExtensions,
31
+ ...normalizedStyles,
32
+ ]);
33
+ const tsconfigMatcher = createTsconfigMatcher(graphOptions?.tsConfig, cwd, resolutionExtensions);
34
+ const seenScripts = new Set();
35
+ const seenStyles = new Set();
36
+ const styleOrder = [];
37
+ const resolutionCache = new Map();
38
+ const resolverFactory = createResolverFactory(cwd, resolutionExtensions, scriptExtensions, graphOptions);
39
+ async function walk(filePath) {
40
+ const absolutePath = node_path_1.default.resolve(filePath);
41
+ if (seenScripts.has(absolutePath)) {
42
+ return;
43
+ }
44
+ seenScripts.add(absolutePath);
45
+ const source = await readSourceFile(absolutePath);
46
+ if (!source) {
47
+ return;
48
+ }
49
+ const specifiers = extractModuleSpecifiers(source, absolutePath);
50
+ for (const specifier of specifiers) {
51
+ if (!specifier || isBuiltinSpecifier(specifier)) {
52
+ continue;
53
+ }
54
+ const resolved = await resolveImport(specifier, absolutePath);
55
+ if (!resolved) {
56
+ continue;
57
+ }
58
+ const normalized = node_path_1.default.resolve(resolved);
59
+ if (!filter(normalized)) {
60
+ continue;
61
+ }
62
+ if (isStyleExtension(normalized, normalizedStyles)) {
63
+ if (!seenStyles.has(normalized)) {
64
+ seenStyles.add(normalized);
65
+ styleOrder.push(normalized);
66
+ }
67
+ continue;
68
+ }
69
+ if (isScriptExtension(normalized, scriptExtensions)) {
70
+ await walk(normalized);
71
+ }
72
+ }
73
+ }
74
+ async function resolveImport(specifier, importer) {
75
+ const cacheKey = `${importer}::${specifier}`;
76
+ if (resolutionCache.has(cacheKey)) {
77
+ return resolutionCache.get(cacheKey);
78
+ }
79
+ let resolved;
80
+ if (resolver) {
81
+ resolved = normalizeResolverResult(await resolver(specifier, { cwd, from: importer }), cwd);
82
+ }
83
+ if (!resolved && tsconfigMatcher) {
84
+ resolved = tsconfigMatcher(specifier);
85
+ }
86
+ if (!resolved) {
87
+ resolved = resolveWithFactory(resolverFactory, specifier, importer, resolutionExtensions);
88
+ }
89
+ resolutionCache.set(cacheKey, resolved);
90
+ return resolved;
91
+ }
92
+ await walk(entryPath);
93
+ return styleOrder;
94
+ }
95
+ function normalizeExtensions(extensions) {
96
+ const result = new Set();
97
+ for (const ext of extensions) {
98
+ if (!ext)
99
+ continue;
100
+ const normalized = ext.startsWith('.') ? ext.toLowerCase() : `.${ext.toLowerCase()}`;
101
+ result.add(normalized);
102
+ }
103
+ return Array.from(result);
104
+ }
105
+ function dedupeExtensions(extensions) {
106
+ const result = new Set();
107
+ for (const ext of extensions) {
108
+ result.add(ext);
109
+ }
110
+ return Array.from(result);
111
+ }
112
+ function isBuiltinSpecifier(specifier) {
113
+ if (BUILTIN_SPECIFIERS.has(specifier)) {
114
+ return true;
115
+ }
116
+ if (specifier.startsWith('node:')) {
117
+ return true;
118
+ }
119
+ return false;
120
+ }
121
+ function isStyleExtension(filePath, extensions) {
122
+ const lower = filePath.toLowerCase();
123
+ return extensions.some(ext => lower.endsWith(ext));
124
+ }
125
+ function isScriptExtension(filePath, extensions) {
126
+ const ext = node_path_1.default.extname(filePath).toLowerCase();
127
+ return extensions.includes(ext);
128
+ }
129
+ async function readSourceFile(filePath) {
130
+ try {
131
+ return await node_fs_1.promises.readFile(filePath, 'utf8');
132
+ }
133
+ catch {
134
+ return undefined;
135
+ }
136
+ }
137
+ function extractModuleSpecifiers(sourceText, filePath) {
138
+ let program;
139
+ try {
140
+ ;
141
+ ({ program } = (0, oxc_parser_1.parseSync)(filePath, sourceText, { sourceType: 'unambiguous' }));
142
+ }
143
+ catch {
144
+ return [];
145
+ }
146
+ const specifiers = [];
147
+ const addSpecifier = (raw) => {
148
+ if (!raw) {
149
+ return;
150
+ }
151
+ const normalized = normalizeSpecifier(raw);
152
+ if (normalized) {
153
+ specifiers.push(normalized);
154
+ }
155
+ };
156
+ const visitor = new oxc_parser_1.Visitor({
157
+ ImportDeclaration(node) {
158
+ addSpecifier(node.source?.value);
159
+ },
160
+ ExportNamedDeclaration(node) {
161
+ if (node.source) {
162
+ addSpecifier(node.source.value);
163
+ }
164
+ },
165
+ ExportAllDeclaration(node) {
166
+ addSpecifier(node.source?.value);
167
+ },
168
+ TSImportEqualsDeclaration(node) {
169
+ const specifier = extractImportEqualsSpecifier(node);
170
+ if (specifier) {
171
+ addSpecifier(specifier);
172
+ }
173
+ },
174
+ ImportExpression(node) {
175
+ const specifier = getStringFromExpression(node.source);
176
+ if (specifier) {
177
+ addSpecifier(specifier);
178
+ }
179
+ },
180
+ CallExpression(node) {
181
+ if (!isRequireLikeCallee(node.callee)) {
182
+ return;
183
+ }
184
+ const specifier = getStringFromArgument(node.arguments[0]);
185
+ if (specifier) {
186
+ addSpecifier(specifier);
187
+ }
188
+ },
189
+ });
190
+ visitor.visit(program);
191
+ return specifiers;
192
+ }
193
+ function normalizeSpecifier(raw) {
194
+ if (!raw)
195
+ return '';
196
+ const trimmed = raw.trim();
197
+ if (!trimmed || trimmed.startsWith('\0')) {
198
+ return '';
199
+ }
200
+ const queryIndex = trimmed.search(/[?#]/);
201
+ const withoutQuery = queryIndex === -1 ? trimmed : trimmed.slice(0, queryIndex);
202
+ if (!withoutQuery) {
203
+ return '';
204
+ }
205
+ if (/^[a-z][\w+.-]*:/i.test(withoutQuery) && !withoutQuery.startsWith('file:')) {
206
+ return '';
207
+ }
208
+ return withoutQuery;
209
+ }
210
+ function extractImportEqualsSpecifier(node) {
211
+ if (node.moduleReference.type === 'TSExternalModuleReference') {
212
+ return node.moduleReference.expression.value;
213
+ }
214
+ return undefined;
215
+ }
216
+ function getStringFromArgument(argument) {
217
+ if (!argument || argument.type === 'SpreadElement') {
218
+ return undefined;
219
+ }
220
+ return getStringFromExpression(argument);
221
+ }
222
+ function getStringFromExpression(expression) {
223
+ if (!expression) {
224
+ return undefined;
225
+ }
226
+ if (expression.type === 'Literal') {
227
+ const literalValue = expression.value;
228
+ return typeof literalValue === 'string' ? literalValue : undefined;
229
+ }
230
+ if (expression.type === 'TemplateLiteral' && expression.expressions.length === 0) {
231
+ const [first] = expression.quasis;
232
+ return first?.value.cooked ?? first?.value.raw ?? undefined;
233
+ }
234
+ return undefined;
235
+ }
236
+ function isRequireLikeCallee(expression) {
237
+ const target = unwrapExpression(expression);
238
+ if (target.type === 'Identifier') {
239
+ return target.name === 'require';
240
+ }
241
+ if (target.type === 'MemberExpression') {
242
+ const object = target.object;
243
+ if (object.type === 'Identifier') {
244
+ return object.name === 'require';
245
+ }
246
+ }
247
+ return false;
248
+ }
249
+ function unwrapExpression(expression) {
250
+ if (expression.type === 'ChainExpression') {
251
+ const inner = expression.expression;
252
+ if (inner.type === 'CallExpression') {
253
+ return unwrapExpression(inner.callee);
254
+ }
255
+ return unwrapExpression(inner);
256
+ }
257
+ if (expression.type === 'TSNonNullExpression') {
258
+ return unwrapExpression(expression.expression);
259
+ }
260
+ return expression;
261
+ }
262
+ function normalizeResolverResult(result, cwd) {
263
+ if (!result) {
264
+ return undefined;
265
+ }
266
+ if (result.startsWith('file://')) {
267
+ try {
268
+ return (0, node_url_1.fileURLToPath)(new URL(result));
269
+ }
270
+ catch {
271
+ return undefined;
272
+ }
273
+ }
274
+ return node_path_1.default.isAbsolute(result) ? result : node_path_1.default.resolve(cwd, result);
275
+ }
276
+ function resolveWithFactory(factory, specifier, importer, extensions) {
277
+ if (specifier.startsWith('file://')) {
278
+ try {
279
+ return findExistingFile((0, node_url_1.fileURLToPath)(new URL(specifier)), extensions);
280
+ }
281
+ catch {
282
+ return undefined;
283
+ }
284
+ }
285
+ if (/^[a-z][\w+.-]*:/i.test(specifier)) {
286
+ return undefined;
287
+ }
288
+ try {
289
+ const result = factory.resolveFileSync(importer, specifier);
290
+ return result?.path;
291
+ }
292
+ catch {
293
+ return undefined;
294
+ }
295
+ }
296
+ function createResolverFactory(cwd, extensions, scriptExtensions, graphOptions) {
297
+ const options = {
298
+ extensions,
299
+ conditionNames: graphOptions?.conditions,
300
+ };
301
+ const extensionAlias = buildExtensionAlias(scriptExtensions);
302
+ if (extensionAlias) {
303
+ options.extensionAlias = extensionAlias;
304
+ }
305
+ const tsconfigOption = resolveResolverTsconfig(graphOptions?.tsConfig, cwd);
306
+ if (tsconfigOption) {
307
+ options.tsconfig = tsconfigOption;
308
+ }
309
+ return new oxc_resolver_1.ResolverFactory(options);
310
+ }
311
+ function buildExtensionAlias(scriptExtensions) {
312
+ const alias = {};
313
+ const jsTargets = dedupeExtensions(scriptExtensions.filter(ext => ['.js', '.ts', '.tsx', '.mjs', '.cjs', '.mts', '.cts'].includes(ext)));
314
+ if (jsTargets.length > 0) {
315
+ for (const key of ['.js', '.mjs', '.cjs']) {
316
+ alias[key] = jsTargets;
317
+ }
318
+ }
319
+ const jsxTargets = dedupeExtensions(scriptExtensions.filter(ext => ext === '.jsx' || ext === '.tsx'));
320
+ if (jsxTargets.length > 0) {
321
+ alias['.jsx'] = jsxTargets;
322
+ }
323
+ return Object.keys(alias).length > 0 ? alias : undefined;
324
+ }
325
+ function resolveResolverTsconfig(input, cwd) {
326
+ if (!input || typeof input !== 'string') {
327
+ return undefined;
328
+ }
329
+ const resolved = resolveTsconfigPath(input, cwd);
330
+ if (!resolved) {
331
+ return undefined;
332
+ }
333
+ return { configFile: resolved };
334
+ }
335
+ function createTsconfigMatcher(input, cwd, extensions) {
336
+ const config = loadTsconfigPaths(input, cwd);
337
+ if (!config) {
338
+ return undefined;
339
+ }
340
+ const matchPath = (0, tsconfig_paths_1.createMatchPath)(config.absoluteBaseUrl, config.paths);
341
+ return (specifier) => {
342
+ const matched = matchPath(specifier, undefined, undefined, extensions);
343
+ if (!matched) {
344
+ return undefined;
345
+ }
346
+ return findExistingFile(matched, extensions) ?? matched;
347
+ };
348
+ }
349
+ function loadTsconfigPaths(input, cwd) {
350
+ if (!input) {
351
+ return undefined;
352
+ }
353
+ if (typeof input === 'string') {
354
+ const target = node_path_1.default.isAbsolute(input) ? input : node_path_1.default.resolve(cwd, input);
355
+ const cached = tsconfigResultCache.get(target);
356
+ if (cached !== undefined) {
357
+ return cached ?? undefined;
358
+ }
359
+ const result = (0, get_tsconfig_1.getTsconfig)(target, undefined, tsconfigFsCache);
360
+ if (!result) {
361
+ tsconfigResultCache.set(target, null);
362
+ return undefined;
363
+ }
364
+ const normalized = normalizeTsconfigCompilerOptions(result.config.compilerOptions, node_path_1.default.dirname(result.path));
365
+ tsconfigResultCache.set(target, normalized ?? null);
366
+ return normalized;
367
+ }
368
+ const compilerOptions = input.compilerOptions;
369
+ return normalizeTsconfigCompilerOptions(compilerOptions, cwd);
370
+ }
371
+ function normalizeTsconfigCompilerOptions(compilerOptions, configDir) {
372
+ if (!compilerOptions?.baseUrl || !compilerOptions.paths) {
373
+ return undefined;
374
+ }
375
+ const normalizedPaths = {};
376
+ for (const [pattern, replacements] of Object.entries(compilerOptions.paths)) {
377
+ if (!replacements || replacements.length === 0) {
378
+ continue;
379
+ }
380
+ normalizedPaths[pattern] = Array.isArray(replacements)
381
+ ? [...replacements]
382
+ : [replacements];
383
+ }
384
+ if (Object.keys(normalizedPaths).length === 0) {
385
+ return undefined;
386
+ }
387
+ const absoluteBaseUrl = node_path_1.default.isAbsolute(compilerOptions.baseUrl)
388
+ ? compilerOptions.baseUrl
389
+ : node_path_1.default.resolve(configDir, compilerOptions.baseUrl);
390
+ return { absoluteBaseUrl, paths: normalizedPaths };
391
+ }
392
+ function resolveTsconfigPath(tsconfigPath, cwd) {
393
+ const absolute = node_path_1.default.isAbsolute(tsconfigPath)
394
+ ? tsconfigPath
395
+ : node_path_1.default.resolve(cwd, tsconfigPath);
396
+ if (!(0, node_fs_1.existsSync)(absolute)) {
397
+ return undefined;
398
+ }
399
+ const stats = (0, node_fs_1.statSync)(absolute);
400
+ if (stats.isDirectory()) {
401
+ const candidate = node_path_1.default.join(absolute, 'tsconfig.json');
402
+ return (0, node_fs_1.existsSync)(candidate) ? candidate : undefined;
403
+ }
404
+ return absolute;
405
+ }
406
+ function findExistingFile(candidate, extensions) {
407
+ const candidateHasExt = hasExtension(candidate);
408
+ if (candidateHasExt && (0, node_fs_1.existsSync)(candidate)) {
409
+ return candidate;
410
+ }
411
+ if (!candidateHasExt) {
412
+ for (const ext of extensions) {
413
+ const withExt = `${candidate}${ext}`;
414
+ if ((0, node_fs_1.existsSync)(withExt)) {
415
+ return withExt;
416
+ }
417
+ }
418
+ }
419
+ if ((0, node_fs_1.existsSync)(candidate) && (0, node_fs_1.statSync)(candidate).isDirectory()) {
420
+ for (const ext of extensions) {
421
+ const indexPath = node_path_1.default.join(candidate, `index${ext}`);
422
+ if ((0, node_fs_1.existsSync)(indexPath)) {
423
+ return indexPath;
424
+ }
425
+ }
426
+ }
427
+ return undefined;
428
+ }
429
+ function hasExtension(filePath) {
430
+ return Boolean(node_path_1.default.extname(filePath));
431
+ }
@@ -0,0 +1,15 @@
1
+ import type { CssResolver } from './types.cjs';
2
+ export interface ModuleGraphOptions {
3
+ tsConfig?: string | Record<string, unknown>;
4
+ extensions?: string[];
5
+ conditions?: string[];
6
+ }
7
+ interface CollectOptions {
8
+ cwd: string;
9
+ styleExtensions: string[];
10
+ filter: (filePath: string) => boolean;
11
+ resolver?: CssResolver;
12
+ graphOptions?: ModuleGraphOptions;
13
+ }
14
+ export declare function collectStyleImports(entryPath: string, options: CollectOptions): Promise<string[]>;
15
+ export {};
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.__moduleInfoInternals = void 0;
7
+ exports.detectModuleDefaultExport = detectModuleDefaultExport;
8
+ const promises_1 = require("node:fs/promises");
9
+ const node_path_1 = __importDefault(require("node:path"));
10
+ const es_module_lexer_1 = require("es-module-lexer");
11
+ const DETECTABLE_EXTENSIONS = new Set([
12
+ '.js',
13
+ '.jsx',
14
+ '.ts',
15
+ '.tsx',
16
+ '.mjs',
17
+ '.mts',
18
+ '.cjs',
19
+ '.cts',
20
+ ]);
21
+ let lexerInit;
22
+ let lexerOverrides;
23
+ function ensureLexerInitialized() {
24
+ if (!lexerInit) {
25
+ lexerInit = es_module_lexer_1.init;
26
+ }
27
+ return lexerInit;
28
+ }
29
+ async function detectModuleDefaultExport(filePath) {
30
+ if (!DETECTABLE_EXTENSIONS.has(node_path_1.default.extname(filePath))) {
31
+ return 'unknown';
32
+ }
33
+ let source;
34
+ try {
35
+ source = await (0, promises_1.readFile)(filePath, 'utf8');
36
+ }
37
+ catch {
38
+ return 'unknown';
39
+ }
40
+ try {
41
+ await ensureLexerInitialized();
42
+ const [, exports] = (lexerOverrides?.parse ?? es_module_lexer_1.parse)(source, filePath);
43
+ if (exports.some(entry => entry.n === 'default')) {
44
+ return 'has-default';
45
+ }
46
+ if (exports.length === 0) {
47
+ return 'unknown';
48
+ }
49
+ return 'no-default';
50
+ }
51
+ catch {
52
+ return 'unknown';
53
+ }
54
+ }
55
+ exports.__moduleInfoInternals = {
56
+ setLexerOverrides(overrides) {
57
+ lexerOverrides = overrides;
58
+ if (!overrides) {
59
+ lexerInit = undefined;
60
+ }
61
+ },
62
+ };
@@ -0,0 +1,10 @@
1
+ import { parse } from 'es-module-lexer';
2
+ export type ModuleDefaultSignal = 'has-default' | 'no-default' | 'unknown';
3
+ type LexerOverrides = {
4
+ parse?: typeof parse;
5
+ };
6
+ export declare function detectModuleDefaultExport(filePath: string): Promise<ModuleDefaultSignal>;
7
+ export declare const __moduleInfoInternals: {
8
+ setLexerOverrides(overrides?: LexerOverrides): void;
9
+ };
10
+ export {};
@@ -0,0 +1,135 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.__sassInternals = void 0;
7
+ exports.createSassImporter = createSassImporter;
8
+ exports.resolveAliasSpecifier = resolveAliasSpecifier;
9
+ exports.shouldNormalizeSpecifier = shouldNormalizeSpecifier;
10
+ exports.ensureSassPath = ensureSassPath;
11
+ exports.resolveRelativeSpecifier = resolveRelativeSpecifier;
12
+ const node_path_1 = __importDefault(require("node:path"));
13
+ const node_fs_1 = require("node:fs");
14
+ const node_url_1 = require("node:url");
15
+ function createSassImporter({ cwd, resolver, }) {
16
+ if (!resolver)
17
+ return undefined;
18
+ const debug = process.env.KNIGHTED_CSS_DEBUG_SASS === '1';
19
+ return {
20
+ async canonicalize(url, context) {
21
+ if (debug) {
22
+ console.error('[knighted-css:sass] canonicalize request:', url);
23
+ if (context?.containingUrl) {
24
+ console.error('[knighted-css:sass] containing url:', context.containingUrl.href);
25
+ }
26
+ }
27
+ const containingPath = context?.containingUrl
28
+ ? (0, node_url_1.fileURLToPath)(context.containingUrl)
29
+ : undefined;
30
+ if (shouldNormalizeSpecifier(url)) {
31
+ const resolvedPath = await resolveAliasSpecifier(url, resolver, cwd, containingPath);
32
+ if (!resolvedPath) {
33
+ if (debug) {
34
+ console.error('[knighted-css:sass] resolver returned no result for', url);
35
+ }
36
+ return null;
37
+ }
38
+ const fileUrl = (0, node_url_1.pathToFileURL)(resolvedPath);
39
+ if (debug) {
40
+ console.error('[knighted-css:sass] canonical url:', fileUrl.href);
41
+ }
42
+ return fileUrl;
43
+ }
44
+ const relativePath = resolveRelativeSpecifier(url, context?.containingUrl);
45
+ if (relativePath) {
46
+ const fileUrl = (0, node_url_1.pathToFileURL)(relativePath);
47
+ if (debug) {
48
+ console.error('[knighted-css:sass] canonical url:', fileUrl.href);
49
+ }
50
+ return fileUrl;
51
+ }
52
+ return null;
53
+ },
54
+ async load(canonicalUrl) {
55
+ if (debug) {
56
+ console.error('[knighted-css:sass] load request:', canonicalUrl.href);
57
+ }
58
+ const filePath = (0, node_url_1.fileURLToPath)(canonicalUrl);
59
+ const contents = await node_fs_1.promises.readFile(filePath, 'utf8');
60
+ return {
61
+ contents,
62
+ syntax: inferSassSyntax(filePath),
63
+ };
64
+ },
65
+ };
66
+ }
67
+ async function resolveAliasSpecifier(specifier, resolver, cwd, from) {
68
+ const resolved = await resolver(specifier, { cwd, from });
69
+ if (!resolved) {
70
+ return undefined;
71
+ }
72
+ if (resolved.startsWith('file://')) {
73
+ return ensureSassPath((0, node_url_1.fileURLToPath)(new URL(resolved)));
74
+ }
75
+ const normalized = node_path_1.default.isAbsolute(resolved) ? resolved : node_path_1.default.resolve(cwd, resolved);
76
+ return ensureSassPath(normalized);
77
+ }
78
+ function shouldNormalizeSpecifier(specifier) {
79
+ const schemeMatch = specifier.match(/^([a-z][\w+.-]*):/i);
80
+ if (!schemeMatch) {
81
+ return false;
82
+ }
83
+ const scheme = schemeMatch[1].toLowerCase();
84
+ if (scheme === 'file' ||
85
+ scheme === 'http' ||
86
+ scheme === 'https' ||
87
+ scheme === 'data' ||
88
+ scheme === 'sass') {
89
+ return false;
90
+ }
91
+ return true;
92
+ }
93
+ function inferSassSyntax(filePath) {
94
+ return filePath.endsWith('.sass') ? 'indented' : 'scss';
95
+ }
96
+ function ensureSassPath(filePath) {
97
+ if ((0, node_fs_1.existsSync)(filePath)) {
98
+ return filePath;
99
+ }
100
+ const ext = node_path_1.default.extname(filePath);
101
+ const dir = node_path_1.default.dirname(filePath);
102
+ const base = node_path_1.default.basename(filePath, ext);
103
+ const partialCandidate = node_path_1.default.join(dir, `_${base}${ext}`);
104
+ if (ext && (0, node_fs_1.existsSync)(partialCandidate)) {
105
+ return partialCandidate;
106
+ }
107
+ const indexCandidate = node_path_1.default.join(dir, base, `index${ext}`);
108
+ if (ext && (0, node_fs_1.existsSync)(indexCandidate)) {
109
+ return indexCandidate;
110
+ }
111
+ const partialIndexCandidate = node_path_1.default.join(dir, base, `_index${ext}`);
112
+ if (ext && (0, node_fs_1.existsSync)(partialIndexCandidate)) {
113
+ return partialIndexCandidate;
114
+ }
115
+ return undefined;
116
+ }
117
+ function resolveRelativeSpecifier(specifier, containingUrl) {
118
+ if (!containingUrl || containingUrl.protocol !== 'file:') {
119
+ return undefined;
120
+ }
121
+ if (/^[a-z][\w+.-]*:/i.test(specifier)) {
122
+ return undefined;
123
+ }
124
+ const containingPath = (0, node_url_1.fileURLToPath)(containingUrl);
125
+ const baseDir = node_path_1.default.dirname(containingPath);
126
+ const candidate = node_path_1.default.resolve(baseDir, specifier);
127
+ return ensureSassPath(candidate);
128
+ }
129
+ exports.__sassInternals = {
130
+ createSassImporter,
131
+ resolveAliasSpecifier,
132
+ shouldNormalizeSpecifier,
133
+ ensureSassPath,
134
+ resolveRelativeSpecifier,
135
+ };
@@ -0,0 +1,25 @@
1
+ import type { CssResolver } from './types.cjs';
2
+ export type { CssResolver } from './types.cjs';
3
+ export declare function createSassImporter({ cwd, resolver, }: {
4
+ cwd: string;
5
+ resolver?: CssResolver;
6
+ }): {
7
+ canonicalize(url: string, context?: {
8
+ containingUrl?: URL | null;
9
+ }): Promise<import("node:url").URL | null>;
10
+ load(canonicalUrl: URL): Promise<{
11
+ contents: string;
12
+ syntax: "scss" | "indented";
13
+ }>;
14
+ } | undefined;
15
+ export declare function resolveAliasSpecifier(specifier: string, resolver: CssResolver, cwd: string, from?: string): Promise<string | undefined>;
16
+ export declare function shouldNormalizeSpecifier(specifier: string): boolean;
17
+ export declare function ensureSassPath(filePath: string): string | undefined;
18
+ export declare function resolveRelativeSpecifier(specifier: string, containingUrl?: URL | null): string | undefined;
19
+ export declare const __sassInternals: {
20
+ createSassImporter: typeof createSassImporter;
21
+ resolveAliasSpecifier: typeof resolveAliasSpecifier;
22
+ shouldNormalizeSpecifier: typeof shouldNormalizeSpecifier;
23
+ ensureSassPath: typeof ensureSassPath;
24
+ resolveRelativeSpecifier: typeof resolveRelativeSpecifier;
25
+ };
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_STABLE_NAMESPACE = void 0;
4
+ exports.resolveStableNamespace = resolveStableNamespace;
5
+ const DEFAULT_STABLE_NAMESPACE = 'knighted';
6
+ exports.DEFAULT_STABLE_NAMESPACE = DEFAULT_STABLE_NAMESPACE;
7
+ function resolveStableNamespace(optionNamespace) {
8
+ if (typeof optionNamespace === 'string') {
9
+ return optionNamespace;
10
+ }
11
+ return DEFAULT_STABLE_NAMESPACE;
12
+ }
@@ -0,0 +1,3 @@
1
+ declare const DEFAULT_STABLE_NAMESPACE = "knighted";
2
+ export declare function resolveStableNamespace(optionNamespace?: string): string;
3
+ export { DEFAULT_STABLE_NAMESPACE };