@silkui/vite 0.1.0 → 0.1.2

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/README.md CHANGED
@@ -1,33 +1,111 @@
1
1
  # @silkui/vite
2
2
 
3
- Vite plugin for ui-js applications: a library build with one ES module for the host to
4
- evaluate, and a reload of the native window after each rebuild. It knows no UI framework:
5
- a React application adds `react()` from `@silkui/react/vite` for JSX and Fast Refresh.
3
+ The [Vite](https://vite.dev) plugin for [Silk UI](https://github.com/silk-lang/SilkUI)
4
+ JavaScript apps. It builds the app into the one ES module a Silk UI host runs, serves its
5
+ modules to the window under the dev server with hot module replacement, and reports the web
6
+ and Node APIs the build uses that the embedded SilkJS runtime does not have. It knows no UI
7
+ framework: a React app adds `react()` from `@silkui/react/vite`.
8
+
9
+ ## Install
10
+
11
+ The templates (`silk init my-app -t ui-react`, `ui-foldkit` or `ui-js`) set it up, and
12
+ `silk task dev` and `silk task build` run Vite for you. See
13
+ [Get started](https://silk-ui-docs.juliaortiz-js.workers.dev/start/). To add it to an
14
+ existing project:
15
+
16
+ ```sh
17
+ npm install -D @silkui/vite vite
18
+ ```
19
+
20
+ ## Usage
6
21
 
7
22
  ```js
23
+ // vite.config.js
8
24
  import { defineConfig } from "vite";
9
25
  import silk from "@silkui/vite";
10
26
  import react from "@silkui/react/vite";
11
27
 
12
- export default defineConfig({ plugins: [silk(), react()] });
28
+ export default defineConfig({ plugins: [silk({ entry: "src/main.tsx" }), react()] });
13
29
  ```
14
30
 
31
+ - `vite build` writes the production bundle, `dist/app.js`, with `process.env.NODE_ENV`
32
+ from the Vite mode.
33
+ - `vite` serves the modules to the host and replaces the ones an edit touches. A module
34
+ nothing accepts restarts the app. With `@silkui/react/vite`, component files keep their
35
+ state (React Fast Refresh). A build error is printed and the running app is left alone.
36
+ `import.meta.hot` works as in Vite.
37
+ - `vite build --watch --mode development` rebuilds the bundle on every change and writes
38
+ `<bundle>.stamp` after each successful build. A host that watches it reloads the whole app.
39
+ This is the production code path, so it is the mode to check a bundle in.
40
+
41
+ The development runner supplies UTF-8 `TextEncoder` and `TextDecoder` for dependencies
42
+ that initialize them before production tree shaking, including Effect. Decoding supports
43
+ streaming, fatal errors and BOM options; other encoding labels throw. Release engine hosts
44
+ still lack these APIs, and the production API report continues to flag retained uses.
45
+
46
+ ## Stylesheets
47
+
48
+ Import CSS from the application entry or its modules. Vite runs any configured CSS processors
49
+ first, then this plugin compiles the resulting CSS with the shared Silk compiler shipped as
50
+ WebAssembly. `vite build` writes `dist/app.sheet`; the `silkui` pipeline validates and embeds
51
+ it after any explicitly configured `App.stylesheet` files. The generated host adopts all
52
+ sheets before the first frame. The application bundle contains no CSS parser or DOM style
53
+ injection. Tailwind and other processors remain optional Vite plugins.
54
+
55
+ Unsupported features produce counted build warnings. Set `strictStylesheets: true` to fail
56
+ instead. Compiler and host versions must match; stale compiled sheets fail the build.
57
+ CSS imports, including dependencies processed through `@import`, hot-replace their compiled
58
+ sheet under the Vite development server. The mounted application and its state remain in
59
+ place. Failed compilation preserves the previous sheet until a valid edit arrives.
60
+ `App.stylesheet` files hot-reload through the pipeline.
61
+
62
+ Maintainers rebuild the packaged compiler with `npm run build:compiler --workspace @silkui/vite`
63
+ from `modules/js`, using the repository's pinned Silk toolchain. Applications need no Silk
64
+ compiler to run the Vite CSS compilation step.
65
+
66
+ ## Options
67
+
15
68
  | Option | Default | Meaning |
16
69
  | --- | --- | --- |
17
70
  | `entry` | `src/main.jsx` | Entry module, relative to the Vite root |
18
71
  | `fileName` | `app.js` | Name of the bundle in `build.outDir` |
19
- | `host` | the `SILKUI_HOST` program, which `silk task dev` sets | `{ command, args, cwd }`: a host binary to start, given `--dev <port>` under the dev server and `--watch <bundle>` in watch mode |
72
+ | `host` | the `SILKUI_HOST` program, which `silk task dev` sets | `{ command, args, cwd }`: a host binary to start, given `--dev <port>` under the dev server and `--watch <bundle>` in watch mode. Without one, the plugin prints the port for a host you start yourself |
20
73
  | `port` | any free one | Port the dev server listens on for the host |
21
- | `apis` | `warn` | What to do when the build uses a web or Node API a ui-js runtime does not have: `warn`, `error` or `off` |
22
- | `allow` | none | Names of such APIs the application provides itself |
23
- | `node` | `false` | The host runs the full SilkJS runtime (ui-js-node): `node:fs` and the other Node builtins stay imports, and `apis` reports only what that runtime lacks |
74
+ | `apis` | `"warn"` | What to do when the build uses an API the runtime does not have: `"warn"`, `"error"` or `"off"` |
75
+ | `allow` | none | Names of such APIs the app provides itself, such as `provided` from `@silkui/foldkit/apis` |
76
+ | `strictStylesheets` | `false` | Fail on unsupported CSS instead of warning |
77
+ | `node` | `false` | The host runs the full SilkJS runtime: `node:fs` and the other Node builtins stay imports, and `apis` reports only what that runtime lacks |
24
78
 
25
- - `vite build` makes the production bundle.
26
- - `vite` serves the modules to the host and replaces the ones an edit touches. A module
27
- nothing accepts restarts the application; with `@silkui/react/vite`, component files keep
28
- their state (React Fast Refresh).
29
- - `vite build --watch --mode development` keeps building the bundle and writes
30
- `<bundle>.stamp` after each successful build; a host that watches it reloads the whole
31
- application.
79
+ ## The missing API report
80
+
81
+ A realm has ECMAScript, timers, `requestAnimationFrame`, `console`, `performance.now`,
82
+ `navigator.clipboard` and `@silkui/core`, but no `fetch`, `URL`, `Intl`, `document`,
83
+ `process` or Node modules. Libraries written for browsers or Node often expect them, so the
84
+ plugin reads every module of a build and says which are used, and by whom:
85
+
86
+ ```
87
+ APIs used here that a ui-js runtime does not have:
88
+ fetch (network): src/api.js, ky
89
+ Intl (intl): date-fns
90
+ node:fs (node): some-package
91
+ ```
92
+
93
+ A name counts when a module reads it as a global. A `typeof` test for it, a local of the
94
+ same name and `process.env.NAME` do not count. Under the dev server the warning comes when
95
+ the module is first served. For Node's APIs at run time, build with `node: true` and give
96
+ the app the full runtime (`App.runtime(Runtime.node())` in `src/tasks.silk`).
97
+
98
+ ## TypeScript
99
+
100
+ The package ships its types: `silk(options?: SilkOptions): Plugin[]`.
101
+
102
+ ## Requirements
103
+
104
+ `vite` 8.
105
+
106
+ ## More
32
107
 
33
- See [the ui-js README](../../README.md#silkvite).
108
+ - [The ui-js reference](https://github.com/silk-lang/SilkUI/blob/main/modules/js/README.md#silkuivite),
109
+ including how the dev server talks to the host.
110
+ - [Templates](https://github.com/silk-lang/examples).
111
+ - [Source](https://github.com/silk-lang/SilkUI/tree/main/modules/js/packages/vite). MIT license.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@silkui/vite",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Vite plugin that builds a ui-js application and reloads it in the native window",
5
5
  "repository": {
6
6
  "type": "git",
@@ -20,5 +20,12 @@
20
20
  "peerDependencies": {
21
21
  "vite": "^8.0.0"
22
22
  },
23
- "license": "MIT"
23
+ "license": "MIT",
24
+ "scripts": {
25
+ "build:compiler": "node scripts/build-compiler.mjs"
26
+ },
27
+ "devDependencies": {
28
+ "@tailwindcss/vite": "4.3.5",
29
+ "tailwindcss": "4.3.5"
30
+ }
24
31
  }
@@ -0,0 +1,63 @@
1
+ import { readFileSync } from 'node:fs';
2
+
3
+ const encoder = new TextEncoder();
4
+ const decoder = new TextDecoder();
5
+ const kinds = ['at-rule', 'selector', 'property', 'value', 'feature'];
6
+ let compiler;
7
+
8
+ export function compileStylesheet(css, { strict = false, resolveUrl } = {}) {
9
+ if (resolveUrl !== undefined && typeof resolveUrl !== 'function') throw new TypeError('resolveUrl must be a function');
10
+ compiler ??= createCompiler();
11
+ return compiler(css, strict, resolveUrl);
12
+ }
13
+
14
+ function createCompiler() {
15
+ let input, result, diagnostics, instance, resolver, replacement, resolutionError;
16
+ let busy = false;
17
+ const module = new WebAssembly.Module(readFileSync(new URL('./compiler.wasm', import.meta.url)));
18
+ instance = new WebAssembly.Instance(module, {
19
+ stylesheet: {
20
+ input_length: () => input.length,
21
+ input_read: (pointer, length) => new Uint8Array(instance.exports.memory.buffer, pointer, length).set(input),
22
+ font_url_length: (pointer, length) => {
23
+ if (!resolver || resolutionError) return 0;
24
+ const original = decoder.decode(new Uint8Array(instance.exports.memory.buffer, pointer, length));
25
+ try {
26
+ const resolved = resolver(original);
27
+ if (typeof resolved !== 'string') throw new TypeError('resolveUrl must return a string');
28
+ if (resolved === original) return 0;
29
+ replacement = encoder.encode(resolved);
30
+ return replacement.length + 1;
31
+ } catch (error) { resolutionError = { error }; return 0; }
32
+ },
33
+ font_url_read: (pointer, length) => new Uint8Array(instance.exports.memory.buffer, pointer, length).set(replacement),
34
+ output: (pointer, length) => { result = new Uint8Array(instance.exports.memory.buffer, pointer, length).slice(); },
35
+ diagnostic: (kind, pointer, length, count) => {
36
+ diagnostics.push({ kind: kinds[kind], feature: decoder.decode(new Uint8Array(instance.exports.memory.buffer, pointer, length)), count });
37
+ },
38
+ },
39
+ });
40
+ return (css, strict, resolveUrl) => {
41
+ if (busy) throw new Error('Stylesheet compilation cannot run inside resolveUrl');
42
+ input = encoder.encode(css);
43
+ if (input.length > 64 * 1024 * 1024) throw new RangeError('Stylesheet exceeds the 64 MiB compiler input limit');
44
+ result = null;
45
+ diagnostics = [];
46
+ resolver = resolveUrl;
47
+ resolutionError = null;
48
+ busy = true;
49
+ try {
50
+ const status = instance.exports.compile_stylesheet(strict ? 1 : 0);
51
+ if (resolutionError) throw resolutionError.error;
52
+ if (status !== 0 || !result) {
53
+ const error = new Error(status === 1 ? 'Stylesheet contains unsupported CSS in strict mode' : 'Stylesheet compilation failed');
54
+ error.diagnostics = diagnostics;
55
+ throw error;
56
+ }
57
+ return { bytes: result, diagnostics };
58
+ } finally {
59
+ busy = false;
60
+ input = resolver = replacement = resolutionError = null;
61
+ }
62
+ };
63
+ }
Binary file
package/src/dev-client.js CHANGED
@@ -38,6 +38,6 @@ native.devStart = async (modules) => {
38
38
  try {
39
39
  for (const module of modules) await runner.import(module);
40
40
  } catch (error) {
41
- console.error(`Uncaught ${error?.stack ?? error}`);
41
+ console.error(`Uncaught ${error?.name ?? "Error"}: ${error?.message ?? error}\n${error?.stack ?? ""}`);
42
42
  }
43
43
  };
@@ -0,0 +1,111 @@
1
+ // UTF-8 for the development module runner and dependencies evaluated before tree shaking.
2
+ // Release hosts still report encoding APIs as unsupported. Other encodings fail explicitly.
3
+ export class TextEncoder {
4
+ get encoding() { return "utf-8"; }
5
+ encode(input = "") {
6
+ const text = String(input);
7
+ const buffer = new Uint8Array(text.length * 3);
8
+ const { written } = this.encodeInto(text, buffer);
9
+ return buffer.slice(0, written);
10
+ }
11
+ encodeInto(input, destination) {
12
+ const text = String(input);
13
+ if (!(destination instanceof Uint8Array)) throw new TypeError("Expected a Uint8Array");
14
+ let read = 0, written = 0;
15
+ for (const character of text) {
16
+ let code = character.codePointAt(0);
17
+ if (code >= 0xd800 && code <= 0xdfff) code = 0xfffd;
18
+ const size = code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4;
19
+ if (written + size > destination.length) break;
20
+ if (size === 1) destination[written++] = code;
21
+ else {
22
+ destination[written++] = (size === 2 ? 0xc0 : size === 3 ? 0xe0 : 0xf0) | (code >> (6 * (size - 1)));
23
+ for (let shift = 6 * (size - 2); shift >= 0; shift -= 6) destination[written++] = 0x80 | ((code >> shift) & 0x3f);
24
+ }
25
+ read += character.length;
26
+ }
27
+ return { read, written };
28
+ }
29
+ }
30
+
31
+ export class TextDecoder {
32
+ #fatal;
33
+ #ignoreBOM;
34
+ #streaming = false;
35
+ #bomSeen = false;
36
+ #needed = 0;
37
+ #seen = 0;
38
+ #code = 0;
39
+ #lower = 0x80;
40
+ #upper = 0xbf;
41
+ constructor(label = "utf-8", options = {}) {
42
+ const encoding = String(label).replace(/^[\t\n\f\r ]+|[\t\n\f\r ]+$/g, "").toLowerCase();
43
+ if (!["utf-8", "utf8", "unicode-1-1-utf-8", "unicode11utf8", "unicode20utf8", "x-unicode20utf8"].includes(encoding)) throw new RangeError("The native dev runner supports only UTF-8");
44
+ this.#fatal = Boolean(options?.fatal);
45
+ this.#ignoreBOM = Boolean(options?.ignoreBOM);
46
+ }
47
+ get encoding() { return "utf-8"; }
48
+ get fatal() { return this.#fatal; }
49
+ get ignoreBOM() { return this.#ignoreBOM; }
50
+ #reset() {
51
+ this.#needed = this.#seen = this.#code = 0;
52
+ this.#lower = 0x80;
53
+ this.#upper = 0xbf;
54
+ }
55
+ decode(input, options = {}) {
56
+ let bytes;
57
+ if (input === undefined) bytes = new Uint8Array();
58
+ else if (ArrayBuffer.isView(input)) bytes = new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
59
+ else if (input instanceof ArrayBuffer || (typeof SharedArrayBuffer !== "undefined" && input instanceof SharedArrayBuffer)) bytes = new Uint8Array(input);
60
+ else throw new TypeError("Expected an ArrayBuffer or view");
61
+ if (!this.#streaming) {
62
+ this.#reset();
63
+ this.#bomSeen = false;
64
+ }
65
+ this.#streaming = Boolean(options?.stream);
66
+ let text = "";
67
+ const emit = (code) => {
68
+ if (!this.#bomSeen) {
69
+ this.#bomSeen = true;
70
+ if (code === 0xfeff && !this.#ignoreBOM) return;
71
+ }
72
+ text += String.fromCodePoint(code);
73
+ };
74
+ const error = () => {
75
+ if (this.#fatal) throw new TypeError("The encoded data was not valid UTF-8");
76
+ emit(0xfffd);
77
+ };
78
+ for (let index = 0; index < bytes.length; index++) {
79
+ const byte = bytes[index];
80
+ if (this.#needed === 0) {
81
+ if (byte <= 0x7f) emit(byte);
82
+ else if (byte >= 0xc2 && byte <= 0xdf) { this.#needed = 1; this.#code = byte & 0x1f; }
83
+ else if (byte >= 0xe0 && byte <= 0xef) {
84
+ this.#needed = 2; this.#code = byte & 0x0f;
85
+ if (byte === 0xe0) this.#lower = 0xa0;
86
+ if (byte === 0xed) this.#upper = 0x9f;
87
+ } else if (byte >= 0xf0 && byte <= 0xf4) {
88
+ this.#needed = 3; this.#code = byte & 0x07;
89
+ if (byte === 0xf0) this.#lower = 0x90;
90
+ if (byte === 0xf4) this.#upper = 0x8f;
91
+ } else error();
92
+ } else if (byte < this.#lower || byte > this.#upper) {
93
+ this.#reset();
94
+ error();
95
+ index--; // The invalid continuation can start the next character.
96
+ } else {
97
+ this.#lower = 0x80; this.#upper = 0xbf;
98
+ this.#code = (this.#code << 6) | (byte & 0x3f);
99
+ if (++this.#seen === this.#needed) {
100
+ emit(this.#code);
101
+ this.#reset();
102
+ }
103
+ }
104
+ }
105
+ if (!this.#streaming && this.#needed !== 0) {
106
+ this.#reset();
107
+ error();
108
+ }
109
+ return text;
110
+ }
111
+ }
package/src/dev-shims.js CHANGED
@@ -1,10 +1,8 @@
1
- // What Vite's module runner touches that a ui-js realm does not have. Source map
2
- // interception is off, so the decoder is never asked for text.
3
- globalThis.TextDecoder ??= class TextDecoder {
4
- decode() {
5
- return "";
6
- }
7
- };
1
+ // Development dependencies (including Effect's barrel exports) instantiate encoders
2
+ // before production tree shaking can remove them. Never substitute a no-op decoder.
3
+ import { TextEncoder, TextDecoder } from "./dev-encoding.js";
4
+ globalThis.TextEncoder ??= TextEncoder;
5
+ globalThis.TextDecoder ??= TextDecoder;
8
6
 
9
7
  // The runner builds file URLs for import.meta: this covers `new URL("file://…").href`.
10
8
  globalThis.URL ??= class URL {
package/src/dev.js CHANGED
@@ -100,7 +100,7 @@ async function bootstrapScript(modules) {
100
100
 
101
101
  /**
102
102
  * The plugins of `vite` (serve) for a ui-js application.
103
- * @param {{ entry: string, port: number, host?: { command: string, args?: string[], cwd?: string } }} options
103
+ * @param {{ entry: string, port: number, host?: { command: string, args?: readonly string[], cwd?: string } }} options
104
104
  */
105
105
  export function devPlugins(options) {
106
106
  const { channel, accept } = createChannel();
@@ -0,0 +1,27 @@
1
+ import { readFileSync, statSync } from 'node:fs';
2
+ import { resolve, sep } from 'node:path';
3
+
4
+ export function fontAssetResolver(config, sheets, output) {
5
+ const base = new URL(config.base, 'https://silk.invalid/').pathname;
6
+ return url => {
7
+ if (!url || url.startsWith('//') || /^[a-z][a-z0-9+.-]*:/i.test(url)) return url;
8
+ const candidates = new Map();
9
+ for (const sheet of sheets) {
10
+ const path = decodeURIComponent(new URL(url, 'https://silk.invalid/' + sheet.fileName).pathname);
11
+ const name = path.startsWith(base) ? path.slice(base.length) : path.slice(1);
12
+ const asset = output[name];
13
+ if (asset?.type === 'asset' && !asset.fileName.endsWith('.css')) {
14
+ candidates.set('asset:' + name, Buffer.from(asset.source));
15
+ } else if (config.publicDir) {
16
+ const file = resolve(config.publicDir, name);
17
+ if (file.startsWith(resolve(config.publicDir) + sep) && statSync(file, { throwIfNoEntry: false })?.isFile()) {
18
+ candidates.set(file, readFileSync(file));
19
+ }
20
+ }
21
+ }
22
+ if (!candidates.size) throw new Error(`Font URL does not resolve to a bundled asset: ${url}`);
23
+ const values = [...candidates.values()];
24
+ if (values.some(value => !value.equals(values[0]))) throw new Error(`Font URL is ambiguous across CSS chunks: ${url}`);
25
+ return 'data:application/octet-stream;base64,' + values[0].toString('base64');
26
+ };
27
+ }
package/src/index.d.ts CHANGED
@@ -6,18 +6,20 @@ export interface SilkOptions {
6
6
  /** Name of the bundle in `build.outDir`. Default `app.js`. */
7
7
  fileName?: string;
8
8
  /** Host binary to start: given `--watch <bundle>` in watch mode, `--dev <port>` under the dev server. */
9
- host?: { command: string; args?: string[]; cwd?: string };
9
+ host?: { command: string; args?: readonly string[]; cwd?: string };
10
10
  /** Port the dev server listens on for the host. Default: any free one. */
11
11
  port?: number;
12
12
  /** What to do when the build uses a web or Node API the runtime does not have. Default `warn`. */
13
13
  apis?: "warn" | "error" | "off";
14
14
  /** Such APIs the application provides itself. */
15
- allow?: string[];
15
+ allow?: readonly string[];
16
16
  /**
17
17
  * The host runs the full SilkJS runtime (ui-js-node): Node builtins stay `node:` imports,
18
18
  * and `apis` reports only what that runtime lacks.
19
19
  */
20
20
  node?: boolean;
21
+ /** Fail the stylesheet build when the CSS compiler drops an unsupported feature. */
22
+ strictStylesheets?: boolean;
21
23
  }
22
24
 
23
25
  export default function silk(options?: SilkOptions): Plugin[];
package/src/index.js CHANGED
@@ -9,18 +9,21 @@
9
9
  // them, and an edit replaces only the modules it touches: see dev.js. The plugin knows no
10
10
  // UI framework: `@silkui/react/vite` adds React's JSX, its reconciler fix and Fast Refresh.
11
11
  import { spawn } from "node:child_process";
12
- import { writeFileSync } from "node:fs";
12
+ import { writeFileSync, rmSync } from "node:fs";
13
13
  import { builtinModules } from "node:module";
14
14
  import { resolve } from "node:path";
15
15
  import { missingApis, ownerOf, report } from "./apis.js";
16
16
  import { devPlugins } from "./dev.js";
17
17
  import { resolveOptions } from "./resolve.js";
18
+ import { compileStylesheet } from "./compiler.js";
19
+ import { stylesheetDevPlugin } from "./stylesheets.js";
20
+ import { fontAssetResolver } from "./font-assets.js";
18
21
 
19
22
  /**
20
23
  * @param {object} [options]
21
24
  * @param {string} [options.entry] Entry module, relative to the Vite root. Default `src/main.jsx`.
22
25
  * @param {string} [options.fileName] Name of the bundle in `build.outDir`. Default `app.js`.
23
- * @param {{ command: string, args?: string[], cwd?: string }} [options.host] Host binary to
26
+ * @param {{ command: string, args?: readonly string[], cwd?: string }} [options.host] Host binary to
24
27
  * start. In watch mode it is given `--watch <bundle>` after `args`, under the dev
25
28
  * server `--dev <port>`.
26
29
  * @param {number} [options.port] Port the dev server listens on for the host. Default: any
@@ -41,6 +44,9 @@ export default function silk(options = {}) {
41
44
  let bundle = "";
42
45
  let watching = false;
43
46
  let child = null;
47
+ let stylesheetPath = "";
48
+ let emittedStylesheet = false;
49
+ let stylesheetConfig;
44
50
 
45
51
  function startHost() {
46
52
  const { command, args = [], cwd } = options.host;
@@ -65,7 +71,8 @@ export default function silk(options = {}) {
65
71
  build: {
66
72
  target: "es2022",
67
73
  minify: mode !== "development",
68
- lib: { entry, formats: ["es"], fileName: () => fileName },
74
+ cssCodeSplit: false,
75
+ lib: { entry, formats: ["es"], fileName: () => fileName, cssFileName: "app" },
69
76
  rolldownOptions: { output: { codeSplitting: false } },
70
77
  },
71
78
  };
@@ -115,6 +122,7 @@ export default function silk(options = {}) {
115
122
  }
116
123
  const owner = ownerOf(id, root);
117
124
  for (const { name, area } of missingApis(ast)) {
125
+ if (serving && (name === "TextEncoder" || name === "TextDecoder")) continue;
118
126
  if (allow.has(name) || (node && !NOT_IN_NODE.has(area))) continue;
119
127
  let use = uses.get(name);
120
128
  if (!use) uses.set(name, (use = { area, owners: new Set() }));
@@ -132,7 +140,42 @@ export default function silk(options = {}) {
132
140
  },
133
141
  };
134
142
 
135
- const plugins = [buildPlugin, apiPlugin];
143
+ const cssPlugin = {
144
+ name: "silk:stylesheets",
145
+ apply: "build",
146
+ enforce: "post",
147
+ configResolved(config) {
148
+ stylesheetPath = resolve(config.root, config.build.outDir, "app.sheet");
149
+ stylesheetConfig = config;
150
+ },
151
+ generateBundle: {
152
+ order: "post",
153
+ handler(_options, output) {
154
+ const sheets = Object.values(output).filter(item => item.type === "asset" && item.fileName.endsWith(".css"));
155
+ emittedStylesheet = sheets.length !== 0;
156
+ if (!sheets.length) return;
157
+ const css = sheets.map(sheet => typeof sheet.source === "string" ? sheet.source : new TextDecoder().decode(sheet.source)).join("\n");
158
+ let compiled;
159
+ try { compiled = compileStylesheet(css, { strict: options.strictStylesheets === true, resolveUrl: fontAssetResolver(stylesheetConfig, sheets, output) }); }
160
+ catch (error) {
161
+ const dropped = error.diagnostics?.map(item => `${item.kind}: ${item.feature} (${item.count})`).join("\n");
162
+ this.error(error.message + (dropped ? `\n${dropped}` : ""));
163
+ }
164
+ for (const diagnostic of compiled.diagnostics) {
165
+ this.warn(`dropped ${diagnostic.count} ${diagnostic.kind} occurrence(s): ${diagnostic.feature}`);
166
+ }
167
+ for (const sheet of sheets) {
168
+ delete output[sheet.fileName];
169
+ delete output[sheet.fileName + ".map"];
170
+ }
171
+ this.emitFile({ type: "asset", fileName: "app.sheet", source: compiled.bytes });
172
+ },
173
+ },
174
+ writeBundle() {
175
+ if (!emittedStylesheet) rmSync(stylesheetPath, { force: true });
176
+ },
177
+ };
178
+ const plugins = [buildPlugin, apiPlugin, cssPlugin, stylesheetDevPlugin({ strict: options.strictStylesheets === true })];
136
179
  if (node) plugins.push(builtinsPlugin);
137
180
  return [...plugins, ...devPlugins({ entry, port: options.port ?? 0, host: options.host })];
138
181
  }
@@ -0,0 +1,73 @@
1
+ import { compileStylesheet } from './compiler.js';
2
+
3
+ const CSS = /\.(?:css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
4
+ const marker = /[?&]silk-sheet(?:&|$)/;
5
+ const passthrough = /[?&](?:inline|raw|url|direct|silk-css-module)(?:&|$)/;
6
+ const virtualPrefix = '\0silk:stylesheet:';
7
+
8
+ export function stylesheetDevPlugin({ strict = false } = {}) {
9
+ const sources = new Map();
10
+ let server;
11
+ return [{
12
+ name: 'silk:stylesheet-dev',
13
+ apply: 'serve',
14
+ enforce: 'pre',
15
+ async resolveId(source, importer) {
16
+ if (this.environment.name !== 'silk' || !CSS.test(source) || passthrough.test(source) || marker.test(source)) return;
17
+ const resolved = await this.resolve(source, importer, { skipSelf: true });
18
+ if (!resolved || resolved.external) return;
19
+ const id = virtualPrefix + Buffer.from(resolved.id).toString('base64url') + '.js';
20
+ sources.set(id, resolved.id);
21
+ return id;
22
+ },
23
+ load(id) {
24
+ const source = sources.get(id);
25
+ if (!source) return;
26
+ const join = source.includes('?') ? '&' : '?';
27
+ const inline = source + join + 'inline&silk-sheet';
28
+ const key = JSON.stringify(source);
29
+ const dependency = JSON.stringify(inline);
30
+ const modules = /\.module\./.test(source)
31
+ ? `export { default } from ${JSON.stringify(source + join + 'silk-css-module')};\nexport * from ${JSON.stringify(source + join + 'silk-css-module')};`
32
+ : 'export default {};';
33
+ return `import compiled from ${dependency};
34
+ import { updateStyleSheet } from '@silkui/core';
35
+ updateStyleSheet(${key}, compiled);
36
+ ${modules}
37
+ if (import.meta.hot) {
38
+ import.meta.hot.accept(${dependency}, updated => { if (updated) updateStyleSheet(${key}, updated.default); });
39
+ import.meta.hot.prune(() => updateStyleSheet(${key}, null));
40
+ }`;
41
+ },
42
+ }, {
43
+ name: 'silk:stylesheet-compile',
44
+ configureServer(value) { server = value; },
45
+ apply: 'serve',
46
+ enforce: 'post',
47
+ transform(code, id) {
48
+ if (this.environment.name !== 'silk' || !marker.test(id)) return;
49
+ const ast = this.parse(code);
50
+ const expression = ast.body.find(node => node.type === 'ExportDefaultDeclaration')?.declaration;
51
+ if (expression?.type !== 'Literal' || typeof expression.value !== 'string') {
52
+ this.error('The CSS processor did not produce an inline stylesheet');
53
+ }
54
+ let result;
55
+ try {
56
+ result = compileStylesheet(expression.value, { strict, resolveUrl(url) {
57
+ if (!url) return url;
58
+ const origin = server?.config.server.origin ?? server?.resolvedUrls?.local[0] ?? server?.resolvedUrls?.network[0];
59
+ try { return new URL(url, origin).href; }
60
+ catch { throw new Error('Font URLs need a Vite server origin; set server.origin when using middleware mode'); }
61
+ } });
62
+ }
63
+ catch (error) {
64
+ const dropped = error.diagnostics?.map(item => `${item.kind}: ${item.feature} (${item.count})`).join("\n");
65
+ this.error(error.message + (dropped ? `\n${dropped}` : ""));
66
+ }
67
+ for (const diagnostic of result.diagnostics) {
68
+ this.warn(`dropped ${diagnostic.count} ${diagnostic.kind} occurrence(s): ${diagnostic.feature}`);
69
+ }
70
+ return { code: `export default ${JSON.stringify(Buffer.from(result.bytes).toString('base64'))};`, map: { mappings: '' } };
71
+ },
72
+ }];
73
+ }