@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/src/sass.ts ADDED
@@ -0,0 +1,114 @@
1
+ import { resolve } from "node:path"
2
+ import { fileURLToPath, pathToFileURL } from "node:url"
3
+ import {
4
+ fromImports,
5
+ createMemo,
6
+ dataOf,
7
+ importFromRoot,
8
+ located,
9
+ withData,
10
+ type Compiled,
11
+ type CompilerSetup,
12
+ } from "./shared.ts"
13
+ import { DiagnosticError } from "hamur/kit"
14
+
15
+ export type SassSyntax = "scss" | "indented"
16
+ export type SassSetup = CompilerSetup
17
+ export type { Compiled }
18
+ export { importFromRoot }
19
+
20
+ /** The part of the modern API of `sass` and `sass-embedded` that the module calls. */
21
+ interface SassApi {
22
+ compileStringAsync(
23
+ source: string,
24
+ options: { url: URL; syntax: SassSyntax; style: "expanded"; loadPaths: string[]; importers: object[] },
25
+ ): Promise<{ css: string; loadedUrls: URL[] }>
26
+ NodePackageImporter?: new (entryPointDirectory?: string) => object
27
+ }
28
+
29
+ interface SassException {
30
+ sassMessage: string
31
+ span: { start: { line: number; column: number }; url?: URL }
32
+ }
33
+
34
+ export const MISSING_SASS = '@hamur/css needs "sass" or "sass-embedded" installed in the app'
35
+
36
+ const COMPILERS = ["sass-embedded", "sass"]
37
+
38
+ const apiOf = (loaded: unknown): SassApi => {
39
+ const module = loaded as SassApi & { default?: SassApi }
40
+ return typeof module.compileStringAsync === "function" ? module : module.default!
41
+ }
42
+
43
+ /** Sass names a module after its URL's last path segment, and `#app/styles/vars` has none (it is all fragment), so the compiled text carries `%23` for a leading `#`. */
44
+ const SPECIFIER_HASH = /(@(?:use|forward|import)\s+["'])#/g
45
+
46
+ const isSassException = (error: unknown): error is SassException =>
47
+ typeof (error as SassException | undefined)?.sassMessage === "string" &&
48
+ typeof (error as SassException).span?.start?.line === "number"
49
+
50
+ /**
51
+ * Sass through the app's own compiler, loaded on the first compile. A result is kept per file and text with the
52
+ * hash of `additionalData` and of each loaded file, so a compile whose inputs did not change returns it without the compiler.
53
+ */
54
+ export function createSass({ rootDir, options, load = (name) => importFromRoot(name, rootDir) }: SassSetup) {
55
+ let api: Promise<SassApi> | undefined
56
+ const compiler = () =>
57
+ (api ??= (async () => {
58
+ for (const name of COMPILERS) {
59
+ const loaded = await load(name)
60
+ if (loaded) return apiOf(loaded)
61
+ }
62
+ throw new DiagnosticError("HAMUR_E5409", MISSING_SASS)
63
+ })())
64
+ const loadPaths = (options.loadPaths ?? []).map((path) => resolve(rootDir, path))
65
+ const importsImporter = {
66
+ findFileUrl(url: string): URL | null {
67
+ const found = fromImports(rootDir, url.startsWith("%23") ? `#${url.slice(3)}` : url)
68
+ return found ? pathToFileURL(found) : null
69
+ },
70
+ }
71
+ const memo = createMemo()
72
+
73
+ return {
74
+ /** Compiles `source`, the text of `file` (a `.scss`/`.sass` file, or the component a style block is in). */
75
+ async compile(file: string, source: string, syntax: SassSyntax): Promise<Compiled> {
76
+ const data = await dataOf(options.additionalData, source, file)
77
+ const kept = await memo.get(file, source, data)
78
+ if (kept) return kept
79
+ const sass = await compiler()
80
+ let output: { css: string; loadedUrls: URL[] }
81
+ try {
82
+ output = await sass.compileStringAsync(withData(data, source).replace(SPECIFIER_HASH, "$1%23"), {
83
+ url: pathToFileURL(file),
84
+ syntax,
85
+ style: "expanded",
86
+ loadPaths,
87
+ importers: [importsImporter, ...(sass.NodePackageImporter ? [new sass.NodePackageImporter(rootDir)] : [])],
88
+ })
89
+ } catch (error) {
90
+ if (!isSassException(error)) throw error
91
+ const { span, sassMessage } = error
92
+ const at = span.url?.protocol === "file:" ? fileURLToPath(span.url) : file
93
+ throw await located(
94
+ rootDir,
95
+ "sass",
96
+ file,
97
+ source,
98
+ data,
99
+ { message: sassMessage, line: span.start.line + 1, column: span.start.column + 1, at },
100
+ error,
101
+ )
102
+ }
103
+ return memo.set(
104
+ file,
105
+ source,
106
+ data,
107
+ output.css,
108
+ output.loadedUrls.filter((url) => url.protocol === "file:").map((url) => fileURLToPath(url)),
109
+ )
110
+ },
111
+ }
112
+ }
113
+
114
+ export type SassCompiler = ReturnType<typeof createSass>
package/src/shared.ts ADDED
@@ -0,0 +1,149 @@
1
+ import { readFileSync } from "node:fs"
2
+ import { readFile } from "node:fs/promises"
3
+ import { isAbsolute, join, relative, resolve } from "node:path"
4
+ import { pathToFileURL } from "node:url"
5
+ import type { StyleData } from "./types.ts"
6
+
7
+ export interface Compiled {
8
+ code: string
9
+ /** The files the compiler read besides the one compiled. */
10
+ dependencies: string[]
11
+ }
12
+
13
+ export interface CompilerSetup {
14
+ rootDir: string
15
+ options: { additionalData?: StyleData; loadPaths?: string[] }
16
+ /** Imports a package from the app root, `undefined` when it is not installed. */
17
+ load?: (name: string) => Promise<unknown>
18
+ }
19
+
20
+ export async function importFromRoot(name: string, rootDir: string): Promise<unknown> {
21
+ let file: string
22
+ try {
23
+ file = Bun.resolveSync(name, rootDir)
24
+ } catch {
25
+ return undefined
26
+ }
27
+ return import(pathToFileURL(file).href)
28
+ }
29
+
30
+ export const missingCompiler = (name: string): string => `@hamur/css needs "${name}" installed in the app`
31
+
32
+ export function shownPath(rootDir: string, file: string): string {
33
+ const path = relative(rootDir, file)
34
+ return path === "" || path.startsWith("..") || isAbsolute(path) ? file : path.split("\\").join("/")
35
+ }
36
+
37
+ export const lines = (text: string) => text.split(/\r?\n/)
38
+
39
+ /** `file:line:column: message`, then the source line and a caret under the column. */
40
+ export function frame(place: string, line: number, column: number, message: string, text: string | undefined): string {
41
+ const head = `${place}:${line}:${column}: ${message}`
42
+ if (text === undefined) return head
43
+ const gutter = String(line)
44
+ const pad = [...text.slice(0, Math.max(0, column - 1))].map((char) => (char === "\t" ? "\t" : " ")).join("")
45
+ return [head, ` ${gutter} | ${text}`, ` ${" ".repeat(gutter.length)} | ${pad}^`].join("\n")
46
+ }
47
+
48
+ /** Where a compiler said its error is: 1-based line and column, in the text it was given, in `at` when it is another file. */
49
+ export interface Position {
50
+ message: string
51
+ line: number
52
+ column: number
53
+ at?: string
54
+ }
55
+
56
+ /** The error of `position`: in an imported file at its own line, in `additionalData` named as such, else at the file's line with the data's lines subtracted. */
57
+ export async function located(
58
+ rootDir: string,
59
+ language: string,
60
+ file: string,
61
+ source: string,
62
+ data: string,
63
+ position: Position,
64
+ cause: unknown,
65
+ ): Promise<Error> {
66
+ const { message, column } = position
67
+ let { line } = position
68
+ const at = position.at ?? file
69
+ if (at !== file) {
70
+ const text = await readFile(at, "utf8").catch(() => undefined)
71
+ return new Error(
72
+ frame(shownPath(rootDir, at), line, column, message, text === undefined ? undefined : lines(text)[line - 1]),
73
+ { cause },
74
+ )
75
+ }
76
+ const dataLines = data ? lines(data).length : 0
77
+ if (line <= dataLines)
78
+ return new Error(frame(`cssCompilers.${language}.additionalData`, line, column, message, lines(data)[line - 1]), {
79
+ cause,
80
+ })
81
+ line -= dataLines
82
+ return new Error(frame(shownPath(rootDir, file), line, column, message, lines(source)[line - 1]), { cause })
83
+ }
84
+
85
+ export const dataOf = async (additionalData: StyleData | undefined, source: string, file: string): Promise<string> =>
86
+ typeof additionalData === "function" ? additionalData(source, file) : (additionalData ?? "")
87
+
88
+ export const withData = (data: string, source: string): string => (data ? `${data}\n${source}` : source)
89
+
90
+ /** A `#…` specifier through the `imports` of the app's `package.json`: the exact key, else the `*` key with the longest prefix, to a `./` target. */
91
+ export function fromImports(rootDir: string, spec: string): string | undefined {
92
+ if (!spec.startsWith("#")) return undefined
93
+ let imports: Record<string, unknown>
94
+ try {
95
+ imports =
96
+ (JSON.parse(readFileSync(join(rootDir, "package.json"), "utf8")) as { imports?: Record<string, unknown> })
97
+ .imports ?? {}
98
+ } catch {
99
+ return undefined
100
+ }
101
+ const key = Object.hasOwn(imports, spec)
102
+ ? spec
103
+ : Object.keys(imports)
104
+ .filter((name) => {
105
+ const [prefix, suffix, ...more] = name.split("*")
106
+ return (
107
+ suffix !== undefined &&
108
+ !more.length &&
109
+ spec.length >= name.length &&
110
+ spec.startsWith(prefix!) &&
111
+ spec.endsWith(suffix)
112
+ )
113
+ })
114
+ .sort((a, b) => b.indexOf("*") - a.indexOf("*"))[0]
115
+ const target = key === undefined ? undefined : imports[key]
116
+ if (key === undefined || typeof target !== "string" || !target.startsWith("./")) return undefined
117
+ const star = key.indexOf("*")
118
+ return resolve(
119
+ rootDir,
120
+ star === -1 ? target : target.replaceAll("*", spec.slice(star, spec.length - (key.length - star - 1))),
121
+ )
122
+ }
123
+
124
+ /** A result kept per file and text with the hash of `additionalData` and of each file the compile read, so a compile whose inputs did not change returns it without the compiler. */
125
+ export function createMemo() {
126
+ const memo = new Map<string, { data: number | bigint; loaded: Array<[string, number | bigint]>; result: Compiled }>()
127
+ const key = (file: string, source: string) => `${file}\0${Bun.hash(source)}`
128
+ const unchanged = async (loaded: Array<[string, number | bigint]>) => {
129
+ for (const [file, hash] of loaded) {
130
+ const text = await readFile(file, "utf8").catch(() => undefined)
131
+ if (text === undefined || Bun.hash(text) !== hash) return false
132
+ }
133
+ return true
134
+ }
135
+ return {
136
+ async get(file: string, source: string, data: string): Promise<Compiled | undefined> {
137
+ const kept = memo.get(key(file, source))
138
+ return kept && kept.data === Bun.hash(data) && (await unchanged(kept.loaded)) ? kept.result : undefined
139
+ },
140
+ async set(file: string, source: string, data: string, code: string, read: string[]): Promise<Compiled> {
141
+ const dependencies = [...new Set(read)].filter((path) => path !== file)
142
+ const loaded: Array<[string, number | bigint]> = []
143
+ for (const path of dependencies) loaded.push([path, Bun.hash(await readFile(path, "utf8"))])
144
+ const result = { code, dependencies }
145
+ memo.set(key(file, source), { data: Bun.hash(data), loaded, result })
146
+ return result
147
+ },
148
+ }
149
+ }
package/src/stylus.ts ADDED
@@ -0,0 +1,111 @@
1
+ import { resolve } from "node:path"
2
+ import {
3
+ fromImports,
4
+ createMemo,
5
+ dataOf,
6
+ importFromRoot,
7
+ located,
8
+ missingCompiler,
9
+ withData,
10
+ type Compiled,
11
+ type CompilerSetup,
12
+ } from "./shared.ts"
13
+ import { DiagnosticError } from "hamur/kit"
14
+
15
+ export type StylusSetup = CompilerSetup
16
+
17
+ interface StylusNode {
18
+ string?: string
19
+ val?: unknown
20
+ first?: StylusNode
21
+ }
22
+
23
+ interface Evaluator {
24
+ visitImport(imported: { path: StylusNode }): unknown
25
+ }
26
+
27
+ interface Renderer {
28
+ set(name: string, value: unknown): Renderer
29
+ options: { imports: string[]; _imports: Array<{ path: string }> }
30
+ render(callback: (error: Error | null, css: string) => void): void
31
+ }
32
+
33
+ /** The part of the API of `stylus` that the module calls. */
34
+ interface StylusApi {
35
+ (source: string): Renderer
36
+ Evaluator: new (...args: never[]) => Evaluator
37
+ }
38
+
39
+ export const MISSING_STYLUS = missingCompiler("stylus")
40
+
41
+ const apiOf = (loaded: unknown): StylusApi => {
42
+ const module = loaded as { default?: StylusApi }
43
+ return typeof module.default === "function" ? module.default : (loaded as StylusApi)
44
+ }
45
+
46
+ const POSITION = /^(.+):(\d+):(\d+)\n[\s\S]*?\n\n([^\n]*)/
47
+
48
+ /** Stylus has no structured position: `Renderer.render` rewrites the message to `file:line:column`, the context, a blank line and the text. */
49
+ function positionOf(error: unknown) {
50
+ const match =
51
+ typeof (error as Error | undefined)?.message === "string" ? POSITION.exec((error as Error).message) : null
52
+ return match ? { message: match[4]!, line: Number(match[2]), column: Number(match[3]), at: match[1]! } : undefined
53
+ }
54
+
55
+ /** Stylus through the app's own `stylus`, loaded on the first compile; kept and located as Sass's are. */
56
+ export function createStylus({ rootDir, options, load = (name) => importFromRoot(name, rootDir) }: StylusSetup) {
57
+ let api: Promise<StylusApi> | undefined
58
+ const compiler = () =>
59
+ (api ??= (async () => {
60
+ const loaded = await load("stylus")
61
+ if (!loaded) throw new DiagnosticError("HAMUR_E5409", MISSING_STYLUS)
62
+ return apiOf(loaded)
63
+ })())
64
+ const paths = (options.loadPaths ?? []).map((path) => resolve(rootDir, path))
65
+ const memo = createMemo()
66
+
67
+ return {
68
+ /** Compiles `source`, the text of `file` (a `.styl` file, or the component a style block is in). */
69
+ async compile(file: string, source: string): Promise<Compiled> {
70
+ const data = await dataOf(options.additionalData, source, file)
71
+ const kept = await memo.get(file, source, data)
72
+ if (kept) return kept
73
+ const stylus = await compiler()
74
+ class ImportsEvaluator extends stylus.Evaluator {
75
+ override visitImport(imported: { path: StylusNode }) {
76
+ const spec = imported.path.first
77
+ const found = typeof spec?.string === "string" ? fromImports(rootDir, spec.string) : undefined
78
+ if (spec && found) {
79
+ spec.string = found
80
+ spec.val = found
81
+ }
82
+ return super.visitImport(imported)
83
+ }
84
+ }
85
+ const renderer = stylus(withData(data, source))
86
+ .set("filename", file)
87
+ .set("paths", [...paths])
88
+ .set("Evaluator", ImportsEvaluator)
89
+ .set("_imports", [])
90
+ const builtin = renderer.options.imports[0]
91
+ let css: string
92
+ try {
93
+ css = await new Promise<string>((done, fail) =>
94
+ renderer.render((error, output) => (error ? fail(error) : done(output))),
95
+ )
96
+ } catch (error) {
97
+ const position = positionOf(error)
98
+ throw position ? await located(rootDir, "stylus", file, source, data, position, error) : error
99
+ }
100
+ return memo.set(
101
+ file,
102
+ source,
103
+ data,
104
+ css,
105
+ renderer.options._imports.map((node) => node.path).filter((path) => path !== builtin),
106
+ )
107
+ },
108
+ }
109
+ }
110
+
111
+ export type StylusCompiler = ReturnType<typeof createStylus>
package/src/types.ts ADDED
@@ -0,0 +1,16 @@
1
+ /** Prepended to each file of the language; a function gets the file's text and absolute path. */
2
+ export type StyleData = string | ((source: string, file: string) => string | Promise<string>)
3
+
4
+ /** The `cssCompilers` config key. */
5
+ export interface CssCompilers {
6
+ sass?: { additionalData?: StyleData; loadPaths?: string[] }
7
+ less?: { additionalData?: StyleData; loadPaths?: string[] }
8
+ stylus?: { additionalData?: StyleData; loadPaths?: string[] }
9
+ postcss?: boolean | { config?: string; plugins?: unknown[] }
10
+ }
11
+
12
+ declare module "hamur" {
13
+ interface HamurModuleOptions {
14
+ cssCompilers?: CssCompilers
15
+ }
16
+ }