@hamur/css 0.0.0-stage → 0.0.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 ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 productdevbook
4
+ Copyright (c) 2019 Material-UI SAS
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,25 @@
1
- # Temporary Holding Version
1
+ # @hamur/css
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The first-party CSS module for [Hamur](https://github.com/productdevbook/hamur), a full-stack web framework for Bun. It compiles `.scss`, `.sass`, `.less` and `.styl` files, and the matching style blocks of Vue and Svelte components, with the app's own `sass` or `sass-embedded`, `less` or `stylus`, then hands the CSS to Bun's CSS bundler. It has no dependency.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ bun add @hamur/css sass # or less, or stylus
9
+ ```
10
+
11
+ Add it to `modules` in `hamur.config.ts`; its options are the `cssCompilers` key:
12
+
13
+ ```ts
14
+ import { defineConfig } from "hamur"
15
+ import css from "@hamur/css"
16
+
17
+ export default defineConfig({
18
+ modules: [css],
19
+ cssCompilers: { sass: { additionalData: '@use "#app/styles/vars" as *;', loadPaths: ["styles"] } },
20
+ })
21
+ ```
22
+
23
+ ## Docs
24
+
25
+ [Documentation](https://docs.productdevbook.com/) and the [API reference](https://docs.productdevbook.com/api-reference/css). MIT license.
@@ -0,0 +1,535 @@
1
+ // packages/css/src/module.ts
2
+ import { readFile as readFile2 } from "node:fs/promises";
3
+ import { extname, isAbsolute as isAbsolute3, relative as relative2, resolve as resolve6, sep as sep2 } from "node:path";
4
+ import { addBunPlugin, addTransform, addWatchFile, defineModule, setStylePreprocessor, useLogger } from "hamur/kit";
5
+
6
+ // packages/css/src/less.ts
7
+ import { resolve as resolve2 } from "node:path";
8
+
9
+ // packages/css/src/shared.ts
10
+ import { readFileSync } from "node:fs";
11
+ import { readFile } from "node:fs/promises";
12
+ import { isAbsolute, join, relative, resolve } from "node:path";
13
+ import { pathToFileURL } from "node:url";
14
+ async function importFromRoot(name, rootDir) {
15
+ let file;
16
+ try {
17
+ file = Bun.resolveSync(name, rootDir);
18
+ } catch {
19
+ return;
20
+ }
21
+ return import(pathToFileURL(file).href);
22
+ }
23
+ var missingCompiler = (name) => `@hamur/css needs "${name}" installed in the app`;
24
+ function shownPath(rootDir, file) {
25
+ const path = relative(rootDir, file);
26
+ return path === "" || path.startsWith("..") || isAbsolute(path) ? file : path.split("\\").join("/");
27
+ }
28
+ var lines = (text) => text.split(/\r?\n/);
29
+ function frame(place, line, column, message, text) {
30
+ const head = `${place}:${line}:${column}: ${message}`;
31
+ if (text === undefined)
32
+ return head;
33
+ const gutter = String(line);
34
+ const pad = [...text.slice(0, Math.max(0, column - 1))].map((char) => char === "\t" ? "\t" : " ").join("");
35
+ return [head, ` ${gutter} | ${text}`, ` ${" ".repeat(gutter.length)} | ${pad}^`].join(`
36
+ `);
37
+ }
38
+ async function located(rootDir, language, file, source, data, position, cause) {
39
+ const { message, column } = position;
40
+ let { line } = position;
41
+ const at = position.at ?? file;
42
+ if (at !== file) {
43
+ const text = await readFile(at, "utf8").catch(() => {
44
+ return;
45
+ });
46
+ return new Error(frame(shownPath(rootDir, at), line, column, message, text === undefined ? undefined : lines(text)[line - 1]), { cause });
47
+ }
48
+ const dataLines = data ? lines(data).length : 0;
49
+ if (line <= dataLines)
50
+ return new Error(frame(`cssCompilers.${language}.additionalData`, line, column, message, lines(data)[line - 1]), {
51
+ cause
52
+ });
53
+ line -= dataLines;
54
+ return new Error(frame(shownPath(rootDir, file), line, column, message, lines(source)[line - 1]), { cause });
55
+ }
56
+ var dataOf = async (additionalData, source, file) => typeof additionalData === "function" ? additionalData(source, file) : additionalData ?? "";
57
+ var withData = (data, source) => data ? `${data}
58
+ ${source}` : source;
59
+ function fromImports(rootDir, spec) {
60
+ if (!spec.startsWith("#"))
61
+ return;
62
+ let imports;
63
+ try {
64
+ imports = JSON.parse(readFileSync(join(rootDir, "package.json"), "utf8")).imports ?? {};
65
+ } catch {
66
+ return;
67
+ }
68
+ const key = Object.hasOwn(imports, spec) ? spec : Object.keys(imports).filter((name) => {
69
+ const [prefix, suffix, ...more] = name.split("*");
70
+ return suffix !== undefined && !more.length && spec.length >= name.length && spec.startsWith(prefix) && spec.endsWith(suffix);
71
+ }).sort((a, b) => b.indexOf("*") - a.indexOf("*"))[0];
72
+ const target = key === undefined ? undefined : imports[key];
73
+ if (key === undefined || typeof target !== "string" || !target.startsWith("./"))
74
+ return;
75
+ const star = key.indexOf("*");
76
+ return resolve(rootDir, star === -1 ? target : target.replaceAll("*", spec.slice(star, spec.length - (key.length - star - 1))));
77
+ }
78
+ function createMemo() {
79
+ const memo = new Map;
80
+ const key = (file, source) => `${file}\x00${Bun.hash(source)}`;
81
+ const unchanged = async (loaded) => {
82
+ for (const [file, hash] of loaded) {
83
+ const text = await readFile(file, "utf8").catch(() => {
84
+ return;
85
+ });
86
+ if (text === undefined || Bun.hash(text) !== hash)
87
+ return false;
88
+ }
89
+ return true;
90
+ };
91
+ return {
92
+ async get(file, source, data) {
93
+ const kept = memo.get(key(file, source));
94
+ return kept && kept.data === Bun.hash(data) && await unchanged(kept.loaded) ? kept.result : undefined;
95
+ },
96
+ async set(file, source, data, code, read) {
97
+ const dependencies = [...new Set(read)].filter((path) => path !== file);
98
+ const loaded = [];
99
+ for (const path of dependencies)
100
+ loaded.push([path, Bun.hash(await readFile(path, "utf8"))]);
101
+ const result = { code, dependencies };
102
+ memo.set(key(file, source), { data: Bun.hash(data), loaded, result });
103
+ return result;
104
+ }
105
+ };
106
+ }
107
+
108
+ // packages/css/src/less.ts
109
+ import { DiagnosticError } from "hamur/kit";
110
+ var MISSING_LESS = missingCompiler("less");
111
+ var apiOf = (loaded) => {
112
+ const module = loaded;
113
+ return typeof module.render === "function" ? module : module.default;
114
+ };
115
+ var isLessError = (error) => typeof error?.message === "string" && typeof error.line === "number" && typeof error.column === "number";
116
+ function createLess({ rootDir, options, load = (name) => importFromRoot(name, rootDir) }) {
117
+ let api;
118
+ const compiler = () => api ??= (async () => {
119
+ const loaded = await load("less");
120
+ if (!loaded)
121
+ throw new DiagnosticError("HAMUR_E5409", MISSING_LESS);
122
+ return apiOf(loaded);
123
+ })();
124
+ const paths = (options.loadPaths ?? []).map((path) => resolve2(rootDir, path));
125
+ const importsPlugin = {
126
+ install(less, plugins) {
127
+
128
+ class ImportsFileManager extends less.FileManager {
129
+ supports(filename) {
130
+ return fromImports(rootDir, filename) !== undefined;
131
+ }
132
+ loadFile(filename, currentDirectory, loadOptions, environment) {
133
+ return super.loadFile(fromImports(rootDir, filename) ?? filename, currentDirectory, loadOptions, environment);
134
+ }
135
+ }
136
+ plugins.addFileManager(new ImportsFileManager);
137
+ }
138
+ };
139
+ const memo = createMemo();
140
+ return {
141
+ async compile(file, source) {
142
+ const data = await dataOf(options.additionalData, source, file);
143
+ const kept = await memo.get(file, source, data);
144
+ if (kept)
145
+ return kept;
146
+ const less = await compiler();
147
+ let output;
148
+ try {
149
+ output = await less.render(withData(data, source), { filename: file, paths, plugins: [importsPlugin] });
150
+ } catch (error) {
151
+ if (!isLessError(error))
152
+ throw error;
153
+ const position = { message: error.message, line: error.line, column: error.column + 1, at: error.filename };
154
+ throw await located(rootDir, "less", file, source, data, position, error);
155
+ }
156
+ return memo.set(file, source, data, output.css, output.imports);
157
+ }
158
+ };
159
+ }
160
+
161
+ // packages/css/src/postcss.ts
162
+ import { existsSync, realpathSync } from "node:fs";
163
+ import { isAbsolute as isAbsolute2, join as join2, resolve as resolve3, sep } from "node:path";
164
+ import { pathToFileURL as pathToFileURL2 } from "node:url";
165
+ import { DiagnosticError as DiagnosticError2, diagnostic } from "hamur/kit";
166
+ var MISSING_POSTCSS = missingCompiler("postcss");
167
+ var NO_PLUGINS = "cssCompilers.postcss is on and has no plugins: add postcss.config.mjs or cssCompilers.postcss.plugins";
168
+ var notNeeded = (name) => `postcss plugin "${name}" is not needed: Bun's CSS bundler already prefixes`;
169
+ var CONFIG_FILES = ["postcss.config.js", "postcss.config.mjs", "postcss.config.ts"];
170
+ var COVERED = new Set(["autoprefixer", "postcss-nesting", "postcss-preset-env", "postcss-import"]);
171
+ var STYLE_ID = /^hamur-(?:vue|svelte)-style:/;
172
+ function withRealPaths(dirs) {
173
+ return [
174
+ ...new Set(dirs.flatMap((dir) => {
175
+ try {
176
+ return [dir, realpathSync(dir)];
177
+ } catch {
178
+ return [dir];
179
+ }
180
+ }))
181
+ ];
182
+ }
183
+ var isPostcssError = (error) => error?.name === "CssSyntaxError" && typeof error.reason === "string";
184
+ var pluginName = (plugin) => {
185
+ const named = plugin;
186
+ const name = named?.postcssPlugin ?? (typeof plugin === "function" ? named?.name : undefined);
187
+ return typeof name === "string" && name ? name : undefined;
188
+ };
189
+ function configFile(rootDir, options) {
190
+ if (options === false)
191
+ return;
192
+ if (typeof options === "object" && options.config !== undefined)
193
+ return resolve3(rootDir, options.config);
194
+ return CONFIG_FILES.map((name) => join2(rootDir, name)).find(existsSync);
195
+ }
196
+ function createPostcss({
197
+ rootDir,
198
+ srcDirs,
199
+ options,
200
+ load = (name) => importFromRoot(name, rootDir),
201
+ warn
202
+ }) {
203
+ const config = configFile(rootDir, options);
204
+ const given = typeof options === "object" ? options.plugins : undefined;
205
+ const on = options !== false && (options !== undefined || config !== undefined);
206
+ const seen = withRealPaths(srcDirs);
207
+ if (on && config && !given && !existsSync(config))
208
+ throw new DiagnosticError2("HAMUR_E5408", "cannot find the PostCSS config file", { at: shownPath(rootDir, config) });
209
+ if (on && (config || given?.length)) {
210
+ try {
211
+ Bun.resolveSync("postcss", rootDir);
212
+ } catch {
213
+ throw new DiagnosticError2("HAMUR_E5409", MISSING_POSTCSS, config && !given ? { at: shownPath(rootDir, config) } : undefined);
214
+ }
215
+ }
216
+ let ready;
217
+ const pluginsOf = async () => {
218
+ if (given)
219
+ return given;
220
+ if (!config)
221
+ return [];
222
+ const exported = (await import(pathToFileURL2(config).href)).default;
223
+ const resolved = typeof exported === "function" ? await exported({ env: process.env.NODE_ENV ?? "development" }) : exported;
224
+ const plugins = resolved?.plugins;
225
+ if (Array.isArray(plugins))
226
+ return plugins;
227
+ if (!plugins || typeof plugins !== "object")
228
+ return [];
229
+ const list = [];
230
+ for (const [name, settings] of Object.entries(plugins)) {
231
+ if (settings === false)
232
+ continue;
233
+ const loaded = await load(name);
234
+ if (!loaded)
235
+ throw new DiagnosticError2("HAMUR_E5410", `plugin "${name}" is not installed in the app`, {
236
+ at: shownPath(rootDir, config)
237
+ });
238
+ const factory = loaded.default ?? loaded;
239
+ list.push(typeof factory === "function" ? factory(settings === true ? undefined : settings) : factory);
240
+ }
241
+ return list;
242
+ };
243
+ const prepare = () => ready ??= (async () => {
244
+ const plugins = await pluginsOf();
245
+ if (!plugins.length) {
246
+ warn(diagnostic("HAMUR_W5411", NO_PLUGINS));
247
+ return;
248
+ }
249
+ for (const name of new Set(plugins.map(pluginName)))
250
+ if (name && COVERED.has(name))
251
+ warn(diagnostic("HAMUR_W5412", notNeeded(name)));
252
+ const loaded = await load("postcss");
253
+ if (!loaded?.default)
254
+ throw new DiagnosticError2("HAMUR_E5409", MISSING_POSTCSS);
255
+ return { run: loaded.default, plugins };
256
+ })();
257
+ return {
258
+ on,
259
+ config: given ? undefined : config,
260
+ sees(id) {
261
+ const path = id.replace(STYLE_ID, "");
262
+ if (!isAbsolute2(path) || path.includes(`${sep}node_modules${sep}`) || path.includes("/node_modules/"))
263
+ return false;
264
+ return seen.some((dir) => path.startsWith(dir.endsWith(sep) ? dir : dir + sep));
265
+ },
266
+ async process(code, id) {
267
+ const setup = await prepare();
268
+ if (!setup)
269
+ return;
270
+ const file = id.replace(STYLE_ID, "");
271
+ try {
272
+ return (await setup.run(setup.plugins).process(code, { from: file, map: false })).css;
273
+ } catch (error) {
274
+ if (!isPostcssError(error) || error.line === undefined)
275
+ throw error;
276
+ const column = error.column ?? 1;
277
+ throw new Error(frame(shownPath(rootDir, file), error.line, column, error.reason, lines(code)[error.line - 1]), { cause: error });
278
+ }
279
+ }
280
+ };
281
+ }
282
+
283
+ // packages/css/src/sass.ts
284
+ import { resolve as resolve4 } from "node:path";
285
+ import { fileURLToPath, pathToFileURL as pathToFileURL3 } from "node:url";
286
+ import { DiagnosticError as DiagnosticError3 } from "hamur/kit";
287
+ var MISSING_SASS = '@hamur/css needs "sass" or "sass-embedded" installed in the app';
288
+ var COMPILERS = ["sass-embedded", "sass"];
289
+ var apiOf2 = (loaded) => {
290
+ const module = loaded;
291
+ return typeof module.compileStringAsync === "function" ? module : module.default;
292
+ };
293
+ var SPECIFIER_HASH = /(@(?:use|forward|import)\s+["'])#/g;
294
+ var isSassException = (error) => typeof error?.sassMessage === "string" && typeof error.span?.start?.line === "number";
295
+ function createSass({ rootDir, options, load = (name) => importFromRoot(name, rootDir) }) {
296
+ let api;
297
+ const compiler = () => api ??= (async () => {
298
+ for (const name of COMPILERS) {
299
+ const loaded = await load(name);
300
+ if (loaded)
301
+ return apiOf2(loaded);
302
+ }
303
+ throw new DiagnosticError3("HAMUR_E5409", MISSING_SASS);
304
+ })();
305
+ const loadPaths = (options.loadPaths ?? []).map((path) => resolve4(rootDir, path));
306
+ const importsImporter = {
307
+ findFileUrl(url) {
308
+ const found = fromImports(rootDir, url.startsWith("%23") ? `#${url.slice(3)}` : url);
309
+ return found ? pathToFileURL3(found) : null;
310
+ }
311
+ };
312
+ const memo = createMemo();
313
+ return {
314
+ async compile(file, source, syntax) {
315
+ const data = await dataOf(options.additionalData, source, file);
316
+ const kept = await memo.get(file, source, data);
317
+ if (kept)
318
+ return kept;
319
+ const sass = await compiler();
320
+ let output;
321
+ try {
322
+ output = await sass.compileStringAsync(withData(data, source).replace(SPECIFIER_HASH, "$1%23"), {
323
+ url: pathToFileURL3(file),
324
+ syntax,
325
+ style: "expanded",
326
+ loadPaths,
327
+ importers: [importsImporter, ...sass.NodePackageImporter ? [new sass.NodePackageImporter(rootDir)] : []]
328
+ });
329
+ } catch (error) {
330
+ if (!isSassException(error))
331
+ throw error;
332
+ const { span, sassMessage } = error;
333
+ const at = span.url?.protocol === "file:" ? fileURLToPath(span.url) : file;
334
+ throw await located(rootDir, "sass", file, source, data, { message: sassMessage, line: span.start.line + 1, column: span.start.column + 1, at }, error);
335
+ }
336
+ return memo.set(file, source, data, output.css, output.loadedUrls.filter((url) => url.protocol === "file:").map((url) => fileURLToPath(url)));
337
+ }
338
+ };
339
+ }
340
+
341
+ // packages/css/src/stylus.ts
342
+ import { resolve as resolve5 } from "node:path";
343
+ import { DiagnosticError as DiagnosticError4 } from "hamur/kit";
344
+ var MISSING_STYLUS = missingCompiler("stylus");
345
+ var apiOf3 = (loaded) => {
346
+ const module = loaded;
347
+ return typeof module.default === "function" ? module.default : loaded;
348
+ };
349
+ var POSITION = /^(.+):(\d+):(\d+)\n[\s\S]*?\n\n([^\n]*)/;
350
+ function positionOf(error) {
351
+ const match = typeof error?.message === "string" ? POSITION.exec(error.message) : null;
352
+ return match ? { message: match[4], line: Number(match[2]), column: Number(match[3]), at: match[1] } : undefined;
353
+ }
354
+ function createStylus({ rootDir, options, load = (name) => importFromRoot(name, rootDir) }) {
355
+ let api;
356
+ const compiler = () => api ??= (async () => {
357
+ const loaded = await load("stylus");
358
+ if (!loaded)
359
+ throw new DiagnosticError4("HAMUR_E5409", MISSING_STYLUS);
360
+ return apiOf3(loaded);
361
+ })();
362
+ const paths = (options.loadPaths ?? []).map((path) => resolve5(rootDir, path));
363
+ const memo = createMemo();
364
+ return {
365
+ async compile(file, source) {
366
+ const data = await dataOf(options.additionalData, source, file);
367
+ const kept = await memo.get(file, source, data);
368
+ if (kept)
369
+ return kept;
370
+ const stylus = await compiler();
371
+
372
+ class ImportsEvaluator extends stylus.Evaluator {
373
+ visitImport(imported) {
374
+ const spec = imported.path.first;
375
+ const found = typeof spec?.string === "string" ? fromImports(rootDir, spec.string) : undefined;
376
+ if (spec && found) {
377
+ spec.string = found;
378
+ spec.val = found;
379
+ }
380
+ return super.visitImport(imported);
381
+ }
382
+ }
383
+ const renderer = stylus(withData(data, source)).set("filename", file).set("paths", [...paths]).set("Evaluator", ImportsEvaluator).set("_imports", []);
384
+ const builtin = renderer.options.imports[0];
385
+ let css;
386
+ try {
387
+ css = await new Promise((done, fail) => renderer.render((error, output) => error ? fail(error) : done(output)));
388
+ } catch (error) {
389
+ const position = positionOf(error);
390
+ throw position ? await located(rootDir, "stylus", file, source, data, position, error) : error;
391
+ }
392
+ return memo.set(file, source, data, css, renderer.options._imports.map((node) => node.path).filter((path) => path !== builtin));
393
+ }
394
+ };
395
+ }
396
+
397
+ // packages/css/src/module.ts
398
+ import { DiagnosticError as DiagnosticError5 } from "hamur/kit";
399
+ var COMPILERS2 = ["sass", "less", "stylus", "postcss"];
400
+ var LANGUAGES = ["sass", "less", "stylus"];
401
+ var shown = (value) => typeof value === "function" ? "a function" : JSON.stringify(value) ?? String(value);
402
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
403
+ function checkOptions(options) {
404
+ const input = options;
405
+ for (const key of Object.keys(input)) {
406
+ if (!COMPILERS2.includes(key))
407
+ throw new DiagnosticError5("HAMUR_E5401", `cssCompilers.${key} is not a compiler; use sass, less, stylus or postcss`);
408
+ }
409
+ for (const name of LANGUAGES) {
410
+ const given = input[name];
411
+ if (given === undefined)
412
+ continue;
413
+ if (!isObject(given))
414
+ throw new DiagnosticError5("HAMUR_E5402", `cssCompilers.${name} must be { additionalData?, loadPaths? } (got ${shown(given)})`);
415
+ const { additionalData, loadPaths } = given;
416
+ if (additionalData !== undefined && typeof additionalData !== "string" && typeof additionalData !== "function") {
417
+ throw new DiagnosticError5("HAMUR_E5403", `cssCompilers.${name}.additionalData must be a string or a function (got ${shown(additionalData)})`);
418
+ }
419
+ if (loadPaths !== undefined && (!Array.isArray(loadPaths) || loadPaths.some((path) => typeof path !== "string"))) {
420
+ throw new DiagnosticError5("HAMUR_E5404", `cssCompilers.${name}.loadPaths must be an array of strings (got ${shown(loadPaths)})`);
421
+ }
422
+ }
423
+ const { postcss } = input;
424
+ if (postcss !== undefined && typeof postcss !== "boolean" && !isObject(postcss))
425
+ throw new DiagnosticError5("HAMUR_E5405", `cssCompilers.postcss must be a boolean or { config?, plugins? } (got ${shown(postcss)})`);
426
+ if (isObject(postcss)) {
427
+ if (postcss.config !== undefined && typeof postcss.config !== "string")
428
+ throw new DiagnosticError5("HAMUR_E5406", `cssCompilers.postcss.config must be a string (got ${shown(postcss.config)})`);
429
+ if (postcss.plugins !== undefined && !Array.isArray(postcss.plugins))
430
+ throw new DiagnosticError5("HAMUR_E5407", `cssCompilers.postcss.plugins must be an array (got ${shown(postcss.plugins)})`);
431
+ }
432
+ return options;
433
+ }
434
+ var SCRIPT_IMPORTS = new Set(["import-statement", "dynamic-import", "require-call"]);
435
+ var LANGUAGE = "s[ac]ss|less|styl";
436
+ var MAPPED = new RegExp(`\\.(?:${LANGUAGE})(?:\\.module)?\\.css$`);
437
+ var cssPath = (file) => `${file}${new RegExp(`\\.module\\.(?:${LANGUAGE})$`).test(file) ? ".module.css" : ".css"}`;
438
+ var stylePath = (path) => new RegExp(`\\.module\\.(?:${LANGUAGE})\\.module\\.css$`).test(path) ? path.slice(0, -".module.css".length) : MAPPED.test(path) ? path.slice(0, -".css".length) : path;
439
+ var compile = (compilers, file, text) => {
440
+ switch (extname(file)) {
441
+ case ".less":
442
+ return compilers.less.compile(file, text);
443
+ case ".styl":
444
+ return compilers.stylus.compile(file, text);
445
+ default:
446
+ return compilers.sass.compile(file, text, file.endsWith(".sass") ? "indented" : "scss");
447
+ }
448
+ };
449
+ var LOCATED = /^[^\s:][^\n]*?:\d+:\d+: /;
450
+ function named(error, file, rootDir) {
451
+ if (!(error instanceof Error) || LOCATED.test(error.message))
452
+ return error;
453
+ const path = relative2(rootDir, file);
454
+ const shown = path === "" || path.startsWith("..") || isAbsolute3(path) ? file : path.split(sep2).join("/");
455
+ return Object.assign(new Error(`${shown}: ${error.message}`), { cause: error });
456
+ }
457
+ function cssPlugin(compilers, { rootDir, dev }) {
458
+ const target = (path, resolveDir) => {
459
+ try {
460
+ return Bun.resolveSync(path, resolveDir || rootDir);
461
+ } catch {
462
+ return isAbsolute3(path) ? path : resolve6(resolveDir || rootDir, path);
463
+ }
464
+ };
465
+ return {
466
+ name: "hamur-css",
467
+ setup(build) {
468
+ const server = build.config?.define?.["import.meta.server"] === "true";
469
+ if (dev && !server) {
470
+ build.onResolve({ filter: new RegExp(`\\.(?:${LANGUAGE})$`) }, ({ path, resolveDir, kind, namespace }) => {
471
+ if (namespace !== "file" || !SCRIPT_IMPORTS.has(kind))
472
+ return;
473
+ return { path: cssPath(target(path, resolveDir)), namespace: "file" };
474
+ });
475
+ }
476
+ build.onLoad({ filter: new RegExp(`\\.(?:${LANGUAGE})(?:(?:\\.module)?\\.css)?$`), namespace: "file" }, async ({ path }) => {
477
+ if (server)
478
+ return { contents: "", loader: "js" };
479
+ const file = stylePath(path);
480
+ try {
481
+ const { code } = await compile(compilers, file, await readFile2(file, "utf8"));
482
+ return { contents: code, loader: "css" };
483
+ } catch (error) {
484
+ throw file === path ? error : named(error, file, rootDir);
485
+ }
486
+ });
487
+ }
488
+ };
489
+ }
490
+ var module_default = defineModule({
491
+ meta: { name: "css", configKey: "cssCompilers" },
492
+ setup(input, hamur) {
493
+ const options = checkOptions(input);
494
+ const common = { rootDir: hamur.options.rootDir };
495
+ const compilers = {
496
+ sass: createSass({ ...common, options: options.sass ?? {} }),
497
+ less: createLess({ ...common, options: options.less ?? {} }),
498
+ stylus: createStylus({ ...common, options: options.stylus ?? {} })
499
+ };
500
+ const postcss = createPostcss({
501
+ rootDir: hamur.options.rootDir,
502
+ srcDirs: [hamur.options.srcDir, ...hamur.options.layers.map((layer) => layer.srcDir)],
503
+ options: options.postcss,
504
+ warn: (message) => useLogger("hamur").warn(message)
505
+ });
506
+ if (postcss.on) {
507
+ if (postcss.config)
508
+ addWatchFile(postcss.config);
509
+ addTransform({
510
+ name: "@hamur/css:postcss",
511
+ filter: { id: /\.(css|scss|sass|less|styl)$|^hamur-(vue|svelte)-style:/ },
512
+ target: "client",
513
+ enforce: "pre",
514
+ async transform(code, { id, loader }) {
515
+ if (loader !== "css" || !postcss.sees(id))
516
+ return;
517
+ return postcss.process(code, id);
518
+ }
519
+ });
520
+ }
521
+ addBunPlugin(cssPlugin(compilers, { ...common, dev: hamur.options.dev }), { client: true, server: true });
522
+ setStylePreprocessor(async ({ lang, code, file }) => {
523
+ if (lang === "scss" || lang === "sass")
524
+ return compilers.sass.compile(file, code, lang === "sass" ? "indented" : "scss");
525
+ if (lang === "less")
526
+ return compilers.less.compile(file, code);
527
+ if (lang === "styl" || lang === "stylus")
528
+ return compilers.stylus.compile(file, code);
529
+ throw new Error(`@hamur/css compiles scss, sass, less, styl and stylus style blocks (got lang "${lang}")`);
530
+ });
531
+ }
532
+ });
533
+ export {
534
+ module_default as default
535
+ };
@@ -0,0 +1,2 @@
1
+ export { default } from "./module.ts";
2
+ export type { CssCompilers, StyleData } from "./types.ts";
@@ -0,0 +1,9 @@
1
+ import { type Compiled, type CompilerSetup } from "./shared.ts";
2
+ export type LessSetup = CompilerSetup;
3
+ export declare const MISSING_LESS: string;
4
+ /** Less through the app's own `less`, loaded on the first compile; kept and located as Sass's are. */
5
+ export declare function createLess({ rootDir, options, load }: LessSetup): {
6
+ /** Compiles `source`, the text of `file` (a `.less` file, or the component a style block is in). */
7
+ compile(file: string, source: string): Promise<Compiled>;
8
+ };
9
+ export type LessCompiler = ReturnType<typeof createLess>;
@@ -0,0 +1,23 @@
1
+ import type { BunPlugin } from "bun";
2
+ import { type LessCompiler } from "./less.ts";
3
+ import { type SassCompiler } from "./sass.ts";
4
+ import { type StylusCompiler } from "./stylus.ts";
5
+ import type { CssCompilers } from "./types.ts";
6
+ export declare function checkOptions(options: CssCompilers): CssCompilers;
7
+ /** The dev client path of a style file: Bun's dev HTML bundler links a stylesheet only when its path ends `.css`, and a CSS module only when it ends `.module.css`. */
8
+ export declare const cssPath: (file: string) => string;
9
+ export declare const stylePath: (path: string) => string;
10
+ export interface StyleCompilers {
11
+ sass: SassCompiler;
12
+ less: LessCompiler;
13
+ stylus: StylusCompiler;
14
+ }
15
+ /** A dev-mapped load names the real file, as Bun's prefix of the real path does in a production build; a compiler error already names its own. */
16
+ export declare function named(error: unknown, file: string, rootDir: string): unknown;
17
+ /** An import of a Sass, Less or Stylus file: CSS for Bun's CSS bundler in the client builds and in dev, an empty module on the server, as `.css` is there. */
18
+ export declare function cssPlugin(compilers: StyleCompilers, { rootDir, dev }: {
19
+ rootDir: string;
20
+ dev: boolean;
21
+ }): BunPlugin;
22
+ declare const _default: import("hamur/kit").HamurModule<CssCompilers>;
23
+ export default _default;
@@ -0,0 +1,27 @@
1
+ export declare const MISSING_POSTCSS: string;
2
+ export declare const NO_PLUGINS = "cssCompilers.postcss is on and has no plugins: add postcss.config.mjs or cssCompilers.postcss.plugins";
3
+ export declare const notNeeded: (name: string) => string;
4
+ export interface PostcssSetup {
5
+ rootDir: string;
6
+ srcDirs: string[];
7
+ /** `cssCompilers.postcss`; `undefined` turns the pass on when `rootDir` has a config file. */
8
+ options: boolean | {
9
+ config?: string;
10
+ plugins?: unknown[];
11
+ } | undefined;
12
+ /** Imports a package from the app root, `undefined` when it is not installed. */
13
+ load?: (name: string) => Promise<unknown>;
14
+ warn: (message: string) => void;
15
+ }
16
+ /** The config file the pass reads: `cssCompilers.postcss.config`, else the first `postcss.config.{js,mjs,ts}` of `rootDir`. */
17
+ export declare function configFile(rootDir: string, options: PostcssSetup["options"]): string | undefined;
18
+ /** PostCSS through the app's own `postcss`, loaded on the first style. */
19
+ export declare function createPostcss({ rootDir, srcDirs, options, load, warn, }: PostcssSetup): {
20
+ on: boolean;
21
+ config: string | undefined;
22
+ /** Whether the pass runs on the module `id`: an app or layer source file, not a dependency. */
23
+ sees(id: string): boolean;
24
+ /** `undefined` when the app has no plugins to run. */
25
+ process(code: string, id: string): Promise<string | undefined>;
26
+ };
27
+ export type PostcssPass = ReturnType<typeof createPostcss>;
@@ -0,0 +1,15 @@
1
+ import { importFromRoot, type Compiled, type CompilerSetup } from "./shared.ts";
2
+ export type SassSyntax = "scss" | "indented";
3
+ export type SassSetup = CompilerSetup;
4
+ export type { Compiled };
5
+ export { importFromRoot };
6
+ export declare const MISSING_SASS = "@hamur/css needs \"sass\" or \"sass-embedded\" installed in the app";
7
+ /**
8
+ * Sass through the app's own compiler, loaded on the first compile. A result is kept per file and text with the
9
+ * hash of `additionalData` and of each loaded file, so a compile whose inputs did not change returns it without the compiler.
10
+ */
11
+ export declare function createSass({ rootDir, options, load }: SassSetup): {
12
+ /** Compiles `source`, the text of `file` (a `.scss`/`.sass` file, or the component a style block is in). */
13
+ compile(file: string, source: string, syntax: SassSyntax): Promise<Compiled>;
14
+ };
15
+ export type SassCompiler = ReturnType<typeof createSass>;