Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/bun-plugin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'zyzz': patch
---

Added `zyzz/bun` and `zyzz.bun`, a Bun plugin for `Bun.build`. It resolves imports through Bun's runtime resolver, as Bun's plugin API does not expose the bundler's.
5 changes: 5 additions & 0 deletions .changeset/skip-ignored-discovery.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'zyzz': patch
---

Discovery and the portable adapters' source scan now skip paths that `.gitignore` files ignore and the bundler's output directories, so stale bundles beside the sources are never parsed.
3 changes: 3 additions & 0 deletions .github/workflows/verify.yml
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,9 @@ jobs:
persist-credentials: false
- name: Install dependencies
uses: $/.github/actions/install-dependencies
- name: Install Bun
# The Bun adapter's integration test builds inside the Bun runtime.
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
- name: Remove Microsoft package sources
# Some runner images list an unsigned packages.microsoft.com source, which fails `apt-get update`.
# No step installs a package from it.
Expand Down
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,11 @@
"types": "./dist/base-ui/react/index.d.ts",
"default": "./dist/base-ui/react/index.js"
},
"./bun": {
"src": "./src/bun/index.ts",
"types": "./dist/bun/index.d.ts",
"default": "./dist/bun/index.js"
},
"./compiler": {
"src": "./src/compiler/index.ts",
"types": "./dist/compiler/index.d.ts",
Expand Down
27 changes: 23 additions & 4 deletions site/src/content/docs/api/unplugin.mdx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# Unplugin

Compile styles with esbuild, Rollup, or Webpack and emit CSS beside the bundle.
Compile styles with Bun, esbuild, Rollup, or Webpack and emit CSS beside the bundle.

The `zyzz` object from `zyzz/unplugin` holds one plugin factory per bundler. The esbuild, Rollup, and Webpack factories compile the source root, rewrite authoring calls, and emit a complete stylesheet into the output directory. [Getting Started](/docs/introduction/getting-started?framework=other-bundlers) covers the setup.
The `zyzz` object from `zyzz/unplugin` holds one plugin factory per bundler. The Bun, esbuild, Rollup, and Webpack factories compile the source root, rewrite authoring calls, and emit a complete stylesheet into the output directory. [Getting Started](/docs/introduction/getting-started?framework=other-bundlers) covers the setup.

```ts title="build.ts"
import { build } from 'esbuild'
Expand All @@ -22,6 +22,7 @@ await build({

```ts
// One factory per bundler
zyzz.bun(options?)
zyzz.esbuild(options?)
zyzz.rollup(options?)
zyzz.webpack(options?)
Expand Down Expand Up @@ -67,7 +68,7 @@ const plugin = zyzz.rollup({ reset: true })
- **Type:** `string{:ts}`
- **Default:** `process.cwd(){:ts}`

The source directory to compile. Every module under it contributes CSS, including unimported global styles. Hidden directories, `node_modules`, `dist`, `build`, `coverage`, tests, fixtures, and declaration, test, and benchmark modules are skipped.
The source directory to compile. Every module under it contributes CSS, including unimported global styles. Hidden directories, `node_modules`, `dist`, `build`, `coverage`, the bundler's output directory, paths that `.gitignore` files ignore, tests, fixtures, and declaration, test, and benchmark modules are skipped.

```ts title="build.ts"
import { zyzz } from 'zyzz/unplugin'
Expand All @@ -83,7 +84,7 @@ Keep other generated output outside the root. Dependencies are not compiled from

### plugin

- **Type:** `EsbuildPlugin | RollupPlugin | WebpackPluginInstance{:ts}`
- **Type:** `BunPlugin | EsbuildPlugin | RollupPlugin | WebpackPluginInstance{:ts}`

A plugin for the factory's bundler that emits these files into its output directory:

Expand All @@ -101,6 +102,24 @@ The plugins do not modify HTML, so the document loads the stylesheet and script
<link rel="stylesheet" href="/zyzz.css" />
```

## Bun

`zyzz.bun` is also exported as `zyzz` from `zyzz/bun`, and runs in `Bun.build`. The build needs `outdir`, since assets are written to the output directory. Imports resolve through Bun's runtime resolver, as Bun's plugin API does not expose the bundler's.

```ts title="build.ts"
import { zyzz } from 'zyzz/bun'

await Bun.build({
entrypoints: ['src/main.tsx'],
// [!code hl:2]
// Receives zyzz.css beside the bundle
outdir: 'dist',
plugins: [zyzz({ root: 'src' })],
})
```

Bun bundles the CSS that packed libraries import and lowers its `light-dark()` colors to variables it sets only beside the `color-scheme` declarations it compiles. `zyzz.css` from Bun therefore ends with a rule that selects the light colors elsewhere, as `light-dark()` does by default. Load it after the bundle's own stylesheet.

## esbuild

`zyzz.esbuild` is also exported as `zyzz` from `zyzz/esbuild`. The build needs `outdir` and the default `write: true`, since assets are written to the output directory.
Expand Down
3 changes: 2 additions & 1 deletion site/src/content/docs/api/vite.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -171,11 +171,12 @@ Discovery covers the first of these that applies:
2. The directories that hold a `zyzz.config.*` module, found by name below the Vite root. Place the configuration at the root of the application's source, such as `src/zyzz.config.ts`, so tool configuration and scripts beside `src/` stay out.
3. The Vite root.

The `zyzz.config.*` search and a root scan skip nested packages: directories below the Vite root that hold their own `package.json`, such as a workspace's examples. [`exclude`](#optionsexclude) removes modules in every case. Adding or moving a `zyzz.config.*` module or a nested `package.json` takes full effect when the server restarts.
The `zyzz.config.*` search and a root scan skip nested packages: directories below the Vite root that hold their own `package.json`, such as a workspace's examples. Every scan also skips each environment's `build.outDir` and the paths that `.gitignore` files ignore, read from the repository root down, or from the scanned directory outside a repository, so stale bundles beside the sources are never parsed. [`exclude`](#optionsexclude) removes modules in every case. Adding or moving a `zyzz.config.*` module or a nested `package.json` takes full effect when the server restarts.

```txt
app/
├── examples/web/ # skipped: nested package
├── dist-preview/ # skipped: listed in .gitignore
├── playwright.config.ts # skipped: outside src/
├── src/
│ ├── global.ts # discovered
Expand Down
5 changes: 5 additions & 0 deletions src/bun/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/** Exposes the Zyzz Bun build adapter. @module */
import { zyzz as unplugin } from '../unplugin/index.js'

/** Compiles project sources and emits `zyzz.css` into the Bun build's `outdir`. */
export const zyzz = unplugin.bun
256 changes: 256 additions & 0 deletions src/node/internal/Ignores.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,256 @@
/** Matches paths against `.gitignore` rules, so project discovery skips what Git ignores. @module */
import * as Fs from 'node:fs'
import * as Path from 'node:path'

/** One `.gitignore` pattern, anchored at the directory holding its file. */
export type Rule = {
/** Directory holding the `.gitignore` file, with platform separators. */
readonly base: string
/** Matches directories only, as a trailing slash requires. */
readonly directory: boolean
/** Re-includes a path that an earlier rule ignored. */
readonly negated: boolean
/** Compiled pattern over the `/`-separated path relative to `base`. */
readonly pattern: RegExp
}

/**
* Creates a reader of the `.gitignore` files that apply below source directories. Rules apply from
* the enclosing repository root down, or from the source directory outside a repository. Files are
* read synchronously once per directory, as watcher events need an immediate answer.
* @param options - The source directories discovery walks.
*/
export function create(options: create.Options) {
const directories = new Map<string, boolean>()
const repositories = new Map<string, boolean>()
const rules = new Map<string, readonly Rule[]>()

function repository(directory: string): boolean {
let value = repositories.get(directory)

if (value === undefined) {
const parent = Path.dirname(directory)

value =
Fs.existsSync(Path.join(directory, '.git')) ||
(parent !== directory && repository(parent))
repositories.set(directory, value)
}

return value
}

function read(directory: string): readonly Rule[] {
let value = rules.get(directory)

if (value === undefined) {
const parent = Path.dirname(directory)
const inherited =
parent === directory ||
Fs.existsSync(Path.join(directory, '.git')) ||
(options.roots.includes(directory) && !repository(parent))
? []
: read(parent)
const source = (() => {
try {
return Fs.readFileSync(Path.join(directory, '.gitignore'), 'utf8')
} catch (error) {
const code = (error as NodeJS.ErrnoException).code

if (code === 'ENOENT' || code === 'ENOTDIR' || code === 'EISDIR')
return ''
throw error
}
})()

value = [...inherited, ...parse({ base: directory, source })]
rules.set(directory, value)
}

return value
}

return {
/**
* Whether the rules of a path's directory ignore it. Callers check each ancestor below a
* source directory, since Git never re-includes a path below an ignored directory.
*/
ignored(path: ignored.Options): boolean {
if (!path.directory) return ignored(read(Path.dirname(path.path)), path)

let value = directories.get(path.path)

if (value === undefined) {
value = ignored(read(Path.dirname(path.path)), path)
directories.set(path.path, value)
}

return value
},
}
}

/** Ignore reader contracts. */
export declare namespace create {
/** Directories whose own `.gitignore` starts the rules outside a repository. */
type Options = {
/** Absolute source directories. */
readonly roots: readonly string[]
}
}

/**
* Whether the last rule matching a path ignores it, as Git decides within one directory. A path
* below an ignored directory is the caller's concern: Git never re-includes it.
* @param rules - Rules of every `.gitignore` file that applies, outermost first.
* @param options - Absolute path and whether it names a directory.
*/
export function ignored(
rules: readonly Rule[],
options: ignored.Options,
): boolean {
let value = false

for (const rule of rules) {
if (rule.directory && !options.directory) continue

const relative = relativePath(rule.base, options.path)

if (relative !== undefined && rule.pattern.test(relative))
value = !rule.negated
}

return value
}

/** Path matching contracts. */
export declare namespace ignored {
/** The path to test. */
type Options = {
/** Whether the path is a directory. */
readonly directory: boolean
/** Absolute path with platform separators. */
readonly path: string
}
}

/**
* Parses a `.gitignore` file into rules in file order. Blank lines, comments, and patterns Git
* treats as invalid produce no rule.
* @param options - File text and the directory holding it.
*/
export function parse(options: parse.Options): readonly Rule[] {
const rules: Rule[] = []

for (const line of options.source.split(/\r?\n/)) {
// Trailing spaces are insignificant unless escaped.
let value = line.replace(/(?<!\\)\s+$/, '')

if (!value || value.startsWith('#')) continue

const negated = value.startsWith('!')

if (negated) value = value.slice(1)
if (value.startsWith('\\#') || value.startsWith('\\!'))
value = value.slice(1)

const directory = value.endsWith('/')

if (directory) value = value.slice(0, -1)
if (!value) continue

// A slash before the end anchors the pattern at the file's directory.
const anchored = value.includes('/')

if (value.startsWith('/')) value = value.slice(1)

const source = glob(value)

if (source === undefined) continue

rules.push({
base: options.base,
directory,
negated,
pattern: new RegExp(anchored ? `^${source}$` : `^(?:.*/)?${source}$`),
})
}

return rules
}

/** Rule parsing contracts. */
export declare namespace parse {
/** One `.gitignore` file. */
type Options = {
/** Absolute directory holding the file. */
readonly base: string
/** File text. */
readonly source: string
}
}

/** Translates gitignore glob syntax to a regular expression source, or undefined when malformed. */
function glob(value: string) {
let output = ''

for (let index = 0; index < value.length; index++) {
const character = value[index]!

if (character === '*' && value[index + 1] === '*') {
const start = index === 0 || value[index - 1] === '/'
const end = index + 2 === value.length || value[index + 2] === '/'

// `**` spans directories only as a whole segment; otherwise it is two single-segment stars.
if (start && end) {
if (index + 2 === value.length) output += '.*'
else output += '(?:.*/)?'
index += index + 2 === value.length ? 1 : 2
continue
}
}

if (character === '*') output += '[^/]*'
else if (character === '?') output += '[^/]'
else if (character === '\\') {
const next = value[index + 1]

if (next === undefined) return undefined

output += escape(next)
index++
} else if (character === '[') {
const close = value.indexOf(']', index + 2)

if (close === -1) return undefined

let body = value.slice(index + 1, close)

if (body.startsWith('!')) body = `^${body.slice(1)}`

output += `[${body.replace(/[\\\]]/g, '\\$&')}]`
index = close
} else output += escape(character)
}

return output
}

function escape(character: string) {
return /[.*+?^${}()|[\]\\/]/.test(character) ? `\\${character}` : character
}

/** The `/`-separated path of `path` below `base`, or undefined outside it. */
function relativePath(base: string, path: string) {
const relative = Path.relative(base, path)

if (
!relative ||
relative === '..' ||
relative.startsWith(`..${Path.sep}`) ||
Path.isAbsolute(relative)
)
return undefined

return relative.split(Path.sep).join('/')
}
Loading