@silkui/vite 0.1.6 → 0.1.8

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
@@ -109,3 +109,21 @@ The package ships its types: `silk(options?: SilkOptions): Plugin[]`.
109
109
  including how the dev server talks to the host.
110
110
  - [Templates](https://github.com/silk-lang/examples).
111
111
  - [Source](https://github.com/silk-lang/SilkUI/tree/main/modules/js/packages/vite). MIT license.
112
+
113
+ ## Silk functions
114
+
115
+ `import { add } from "../silk/math.silk"` imports the public functions of a module the
116
+ project's `silk.toml` exports (`kind = "library"`, `exports = ["math"]`). silkui compiles the
117
+ module into the app's host program, and the import becomes calls into it: `add(1, 2)` runs
118
+ now, natively, and `add.async(1, 2)` runs on a thread and returns a promise. Numbers, `bool`,
119
+ `string` and `String` cross; `i64` and `u64` are `bigint`. Before it runs Vite, silkui runs
120
+ `silkui-natives` (this package's bin), which asks `silk doc` for the signatures and writes
121
+ `.silk/natives/`: the description the import reads, the host's dispatcher, and declarations.
122
+
123
+ For editor types, the package is a TypeScript 7.1 content mapper:
124
+
125
+ ```json
126
+ "contentMappers": [{ "package": "@silkui/vite", "extensions": [".silk"] }]
127
+ ```
128
+
129
+ Under the dev server, an edit to the project's Silk sources rebuilds the host silkui made and starts it again; JavaScript state starts over, as after a reload.
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env node
2
+ // silkui runs this before it bundles and builds an app: it describes the Silk functions the
3
+ // project exports to JavaScript and writes `.silk/natives/` under the project root:
4
+ // natives.json (what `.silk` imports become), natives.silk (the host's dispatcher) and
5
+ // types/<source>.d.silk.ts (declarations for a tsconfig `rootDirs` without the content mapper).
6
+ import { resolve } from "node:path";
7
+ import { leftOut, writeNatives } from "../src/natives.js";
8
+
9
+ try {
10
+ const description = await writeNatives(resolve(process.argv[2] ?? "."));
11
+ for (const line of leftOut(description)) console.warn(`silkui: ${line}`);
12
+ } catch (error) {
13
+ console.error(`silkui: ${error.message}`);
14
+ process.exit(1);
15
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@silkui/vite",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
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",
@@ -14,9 +14,26 @@
14
14
  "default": "./src/index.js"
15
15
  }
16
16
  },
17
+ "bin": {
18
+ "silkui-natives": "bin/silkui-natives.js"
19
+ },
17
20
  "files": [
18
- "src"
21
+ "src",
22
+ "bin"
19
23
  ],
24
+ "typescript": {
25
+ "contentMapper": {
26
+ "exec": [
27
+ "node",
28
+ "src/mapper.js"
29
+ ],
30
+ "compilerOptions": [],
31
+ "dynamicConfig": false
32
+ }
33
+ },
34
+ "dependencies": {
35
+ "ts-content-mapper": "0.1.1"
36
+ },
20
37
  "peerDependencies": {
21
38
  "vite": "^8.0.0"
22
39
  },
package/src/compiler.wasm CHANGED
Binary file
package/src/dev.js CHANGED
@@ -1,9 +1,12 @@
1
1
  // The development side of @silkui/vite: a Vite environment whose modules run in a ui-js host,
2
2
  // reached over a local TCP connection the host opens (`--dev <port>`).
3
3
  import { spawn } from "node:child_process";
4
+ import { copyFileSync, existsSync, readFileSync } from "node:fs";
4
5
  import net from "node:net";
6
+ import { basename, dirname, join, sep } from "node:path";
5
7
  import { fileURLToPath } from "node:url";
6
8
  import { build, DevEnvironment } from "vite";
9
+ import { NATIVES_DIR, leftOut, packageFields, projectRoot, writeNatives } from "./natives.js";
7
10
  import { resolveOptions } from "./resolve.js";
8
11
 
9
12
  // The longest text on one line: the host reads lines of up to one mebibyte.
@@ -98,6 +101,28 @@ async function bootstrapScript(modules) {
98
101
  return `${code}\n__ui.devStart(${JSON.stringify(modules)});`;
99
102
  }
100
103
 
104
+ /**
105
+ * The project and generated host of a host silkui built with Silk functions compiled in, or
106
+ * null: silkui builds it in `<project>/.silk/<target>/`, beside `.silk/natives/`.
107
+ */
108
+ function nativesOf(command) {
109
+ const host = projectRoot(dirname(command));
110
+ if (!host || basename(dirname(host)) !== ".silk" || !existsSync(join(host, "src", "natives.silk"))) return null;
111
+ const root = projectRoot(dirname(dirname(host)));
112
+ if (!root) return null;
113
+ const { source } = packageFields(readFileSync(join(root, "silk.toml"), "utf8"));
114
+ return { root, host, source };
115
+ }
116
+
117
+ /** `silk build` of the host package in `dir`. */
118
+ function silkBuild(dir) {
119
+ return new Promise((resolve, reject) => {
120
+ const build = spawn(process.env.SILK ?? "silk", ["build", "--progress", "never", "--manifest-path", join(dir, "silk.toml")], { stdio: "inherit" });
121
+ build.on("error", reject);
122
+ build.on("exit", (code) => (code === 0 ? resolve() : reject(new Error("the host build failed"))));
123
+ });
124
+ }
125
+
101
126
  /**
102
127
  * The plugins of `vite` (serve) for a ui-js application.
103
128
  * @param {{ entry: string, port: number, host?: { command: string, args?: readonly string[], cwd?: string } }} options
@@ -157,11 +182,65 @@ export function devPlugins(options) {
157
182
  return;
158
183
  }
159
184
  const { command, args = [], cwd } = options.host;
160
- child = spawn(command, [...args, "--dev", String(port)], { cwd, stdio: "inherit" });
161
- child.on("error", (error) => server.config.logger.error(`[silk] could not start ${command}: ${error.message}`));
162
- // Closing the window ends the dev session.
163
- child.on("exit", (code) => process.exit(code ?? 0));
185
+ const logger = server.config.logger;
186
+ let restarting = false;
187
+ const start = () => {
188
+ child = spawn(command, [...args, "--dev", String(port)], { cwd, stdio: "inherit" });
189
+ child.on("error", (error) => logger.error(`[silk] could not start ${command}: ${error.message}`));
190
+ // Closing the window ends the dev session.
191
+ child.on("exit", (code) => {
192
+ if (!restarting) process.exit(code ?? 0);
193
+ });
194
+ };
195
+ start();
164
196
  process.on("exit", () => child.kill());
197
+ const natives = nativesOf(command);
198
+ if (!natives) return;
199
+ // The host has the project's exported Silk functions compiled in: an edit to its Silk
200
+ // sources rebuilds it and starts it again. JavaScript state starts over, as after a reload.
201
+ let building = null;
202
+ let again = false;
203
+ const rebuild = async () => {
204
+ do {
205
+ again = false;
206
+ logger.info(`[silk] ${natives.source}/ changed: rebuilding the host`, { timestamp: true });
207
+ restarting = true;
208
+ // The host is linked in place, so it stops first.
209
+ const exited = new Promise((resolve) => child.once("exit", resolve));
210
+ child.kill();
211
+ await exited;
212
+ try {
213
+ const description = await writeNatives(natives.root);
214
+ for (const line of leftOut(description)) logger.warn(`[silk] ${line}`);
215
+ const glue = join(natives.root, NATIVES_DIR, "natives.silk");
216
+ if (existsSync(glue)) copyFileSync(glue, join(natives.host, "src", "natives.silk"));
217
+ await silkBuild(natives.host);
218
+ } catch (error) {
219
+ logger.error(`[silk] ${error.message}: the previous build runs until the next change`, { timestamp: true });
220
+ }
221
+ for (const environment of Object.values(server.environments)) {
222
+ for (const module of environment.moduleGraph.idToModuleMap.values()) {
223
+ if (module.file?.endsWith(".silk")) environment.moduleGraph.invalidateModule(module);
224
+ }
225
+ }
226
+ start();
227
+ restarting = false;
228
+ } while (again);
229
+ building = null;
230
+ };
231
+ const sources = join(natives.root, natives.source) + sep;
232
+ server.watcher.add(sources);
233
+ const changed = (file) => {
234
+ if (!file.endsWith(".silk") || !file.startsWith(sources)) return;
235
+ if (building) {
236
+ again = true;
237
+ return;
238
+ }
239
+ building = rebuild();
240
+ };
241
+ server.watcher.on("change", changed);
242
+ server.watcher.on("add", changed);
243
+ server.watcher.on("unlink", changed);
165
244
  },
166
245
  };
167
246
 
package/src/index.js CHANGED
@@ -11,13 +11,15 @@
11
11
  import { spawn } from "node:child_process";
12
12
  import { writeFileSync, rmSync } from "node:fs";
13
13
  import { builtinModules } from "node:module";
14
- import { resolve } from "node:path";
14
+ import { dirname, join, relative, 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
18
  import { compileStylesheet } from "./compiler.js";
19
19
  import { stylesheetDevPlugin } from "./stylesheets.js";
20
+ import { reportDropped, standardize } from "./report.js";
20
21
  import { fontAssetResolver } from "./font-assets.js";
22
+ import { NATIVES_DIR, jsModule, moduleOf, projectRoot, readDescription } from "./natives.js";
21
23
 
22
24
  /**
23
25
  * @param {object} [options]
@@ -156,14 +158,12 @@ export default function silk(options = {}) {
156
158
  if (!sheets.length) return;
157
159
  const css = sheets.map(sheet => typeof sheet.source === "string" ? sheet.source : new TextDecoder().decode(sheet.source)).join("\n");
158
160
  let compiled;
159
- try { compiled = compileStylesheet(css, { strict: options.strictStylesheets === true, resolveUrl: fontAssetResolver(stylesheetConfig, sheets, output) }); }
161
+ try { compiled = compileStylesheet(standardize(css), { strict: options.strictStylesheets === true, resolveUrl: fontAssetResolver(stylesheetConfig, sheets, output) }); }
160
162
  catch (error) {
161
163
  const dropped = error.diagnostics?.map(item => `${item.kind}: ${item.feature} (${item.count})`).join("\n");
162
164
  this.error(error.message + (dropped ? `\n${dropped}` : ""));
163
165
  }
164
- for (const diagnostic of compiled.diagnostics) {
165
- this.warn(`dropped ${diagnostic.count} ${diagnostic.kind} occurrence(s): ${diagnostic.feature}`);
166
- }
166
+ reportDropped(message => this.warn(message), compiled.diagnostics);
167
167
  for (const sheet of sheets) {
168
168
  delete output[sheet.fileName];
169
169
  delete output[sheet.fileName + ".map"];
@@ -175,11 +175,35 @@ export default function silk(options = {}) {
175
175
  if (!emittedStylesheet) rmSync(stylesheetPath, { force: true });
176
176
  },
177
177
  };
178
- const plugins = [buildPlugin, apiPlugin, cssPlugin, stylesheetDevPlugin({ strict: options.strictStylesheets === true })];
178
+ const plugins = [buildPlugin, silkImports, apiPlugin, cssPlugin, stylesheetDevPlugin({ strict: options.strictStylesheets === true })];
179
179
  if (node) plugins.push(builtinsPlugin);
180
180
  return [...plugins, ...devPlugins({ entry, port: options.port ?? 0, host: options.host })];
181
181
  }
182
182
 
183
+ // `import { add } from "../silk/math.silk"`: the module becomes calls into the host, which has
184
+ // the project's exported Silk functions compiled in. silkui describes them into .silk/natives/
185
+ // before it runs Vite (see natives.js).
186
+ const silkImports = {
187
+ name: "silk:imports",
188
+ enforce: "pre",
189
+ load(id) {
190
+ const file = id.split("?")[0];
191
+ if (!file.endsWith(".silk") || id.startsWith("\0")) return;
192
+ const root = projectRoot(dirname(file));
193
+ if (!root) this.error(`${file} is not in a Silk package: there is no silk.toml above it`);
194
+ const description = readDescription(root);
195
+ if (!description) this.error(`the Silk functions of ${root} are not described yet: build or run the app with \`silk task\`, which writes ${NATIVES_DIR}/`);
196
+ const module = moduleOf(description, file);
197
+ if (!module) this.error(`${relative(root, file)} is not exported to JavaScript: add its module to \`exports\` in silk.toml`);
198
+ this.addWatchFile(join(root, NATIVES_DIR, "natives.json"));
199
+ return { code: jsModule(module), map: null };
200
+ },
201
+ // The dev server rebuilds the host and starts it again (see dev.js): nothing to replace in place.
202
+ hotUpdate({ file }) {
203
+ if (file.endsWith(".silk") || file.includes(`${NATIVES_DIR}/`)) return [];
204
+ },
205
+ };
206
+
183
207
  /** The areas of `MISSING` the SilkJS runtime does not have either. */
184
208
  const NOT_IN_NODE = new Set(["dom", "storage", "workers"]);
185
209
 
package/src/mapper.js ADDED
@@ -0,0 +1,89 @@
1
+ // The TypeScript plugin for `.silk` imports: a TypeScript 7.1 content mapper. TypeScript sends
2
+ // each .silk file it meets; this answers with declarations for the functions the project
3
+ // exports to JavaScript, mapped back to the Silk source, so hover shows the Silk doc comment and
4
+ // go to definition lands in the .silk file. Silk errors in the file show as TypeScript errors.
5
+ // A project opts in from tsconfig.json:
6
+ // "contentMappers": [{ "package": "@silkui/vite", "extensions": [".silk"] }]
7
+ // The editor sees the saved files: `silk doc` reads the package from disk.
8
+ import { execFile } from "node:child_process";
9
+ import { join, relative } from "node:path";
10
+ import { promisify } from "node:util";
11
+ import { MappedCodeBuilder, SpanMapFeature, runContentMapper } from "ts-content-mapper";
12
+ import { describeProject, moduleOf, projectRoot, silkDoc } from "./natives.js";
13
+
14
+ const run = promisify(execFile);
15
+ const silk = process.env.SILK ?? "silk";
16
+ const navigation = SpanMapFeature.Hover | SpanMapFeature.Definition | SpanMapFeature.References |
17
+ SpanMapFeature.DocumentHighlights | SpanMapFeature.Rename | SpanMapFeature.DocumentSymbols;
18
+ const typeFeatures = SpanMapFeature.Hover | SpanMapFeature.Definition;
19
+
20
+ function comment(markdown) {
21
+ return `/**\n${markdown.split("\n").map((line) => ` * ${line.replaceAll("*/", "*\\/")}`).join("\n")}\n */\n`;
22
+ }
23
+
24
+ /** `silk check --json` errors in `file`, at byte offsets. */
25
+ async function errors(root, file) {
26
+ let output;
27
+ try {
28
+ output = await run(silk, ["check", "--json", "--quiet", "--manifest-path", join(root, "silk.toml")], { cwd: root });
29
+ } catch (error) {
30
+ output = error;
31
+ }
32
+ const found = [];
33
+ for (const line of `${output.stdout ?? ""}\n${output.stderr ?? ""}`.split("\n")) {
34
+ if (!line.startsWith("{")) continue;
35
+ const entry = JSON.parse(line);
36
+ if (entry.path === file && entry.severity === "error") found.push(entry);
37
+ }
38
+ return found;
39
+ }
40
+
41
+ runContentMapper({
42
+ diagnosticSource: "silk",
43
+ async transform(params, context) {
44
+ const content = params.content;
45
+ const bytes = Buffer.from(content, "utf8");
46
+ const toIndex = (offset) => bytes.subarray(0, offset).toString("utf8").length;
47
+ const position = context.positionEncoding === "utf-8" ? (index) => Buffer.byteLength(content.slice(0, index), "utf8") : (index) => index;
48
+ const code = new MappedCodeBuilder(content, { positionEncoding: context.positionEncoding });
49
+ code.append("// TypeScript view of a Silk module: its functions run natively in the Silk UI host\n");
50
+ const root = projectRoot(join(params.fileName, ".."));
51
+ const [doc, found] = root ? await Promise.all([silkDoc(root).catch(() => null), errors(root, params.fileName)]) : [null, []];
52
+ const module = doc && moduleOf(await describeProject(root, doc), params.fileName);
53
+ if (!root) code.append("// not in a Silk package: there is no silk.toml above this file\n");
54
+ else if (doc && !module) code.append(`// ${relative(root, params.fileName)} is not exported to JavaScript: add its module to exports in silk.toml\n`);
55
+ for (const fn of module?.functions ?? []) {
56
+ if (fn.unsupported) {
57
+ code.append(`// ${fn.name}: ${fn.unsupported}\n`);
58
+ continue;
59
+ }
60
+ const start = toIndex(fn.at);
61
+ const nameAt = content.indexOf(fn.name, content.indexOf("fn", start) + 2);
62
+ const params = fn.params.map((p) => `${p.name}: ${p.ts}`).join(", ");
63
+ if (fn.doc) code.append(comment(fn.doc));
64
+ code.append("export declare const ");
65
+ code.appendVerbatim(nameAt, nameAt + fn.name.length, navigation);
66
+ code.append(": ((");
67
+ fn.params.forEach((param, index) => {
68
+ if (index > 0) code.append(", ");
69
+ const at = toIndex(param.at);
70
+ const typeAt = content.indexOf(param.silk, at + param.name.length);
71
+ code.appendVerbatim(at, at + param.name.length, navigation);
72
+ code.append(": ");
73
+ if (typeAt >= 0) code.appendAtom(param.ts, typeAt, typeAt + param.silk.length, typeFeatures);
74
+ else code.append(param.ts);
75
+ });
76
+ code.append(`) => ${fn.returns.ts}) & {\n /** Runs on a background thread. */\n async(${params}): Promise<${fn.returns.ts}>;\n};\n`);
77
+ }
78
+ if (!module?.functions.some((fn) => !fn.unsupported)) code.append("export {};\n");
79
+ const output = code.build(".ts");
80
+ return {
81
+ ...output,
82
+ diagnostics: found.map((entry) => {
83
+ const start = toIndex(entry.start);
84
+ const end = toIndex(entry.end);
85
+ return { messageText: `${entry.code}: ${entry.message}`, start: position(start), length: Math.max(position(end) - position(start), 0), code: Number(String(entry.code).replace(/\D/g, "")) || 1 };
86
+ }),
87
+ };
88
+ },
89
+ });
package/src/natives.js ADDED
@@ -0,0 +1,370 @@
1
+ // Silk functions a Silk UI app exports to its JavaScript: `import { add } from "../silk/math.silk"`.
2
+ //
3
+ // The project's Silk package is a library; the modules in its `exports` are what JavaScript can
4
+ // import. `silk doc` gives their public functions, and one description of them feeds three
5
+ // outputs: the Silk dispatcher silkui compiles into the native host (`silkGlue`), the JavaScript
6
+ // module a `.silk` import becomes (`jsModule`), and its TypeScript declarations (`declarations`,
7
+ // also what the content mapper in mapper.js answers). The code runs natively in the host: a call
8
+ // is `__ui.native(id, ...args)`, which the bridge hands to the dispatcher.
9
+ import { execFile } from "node:child_process";
10
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
11
+ import { mkdtemp, readFile, rm } from "node:fs/promises";
12
+ import { tmpdir } from "node:os";
13
+ import { dirname, join, relative, resolve } from "node:path";
14
+ import { promisify } from "node:util";
15
+
16
+ const run = promisify(execFile);
17
+
18
+ /** Where silkui writes the description and the dispatcher, under the project root. */
19
+ export const NATIVES_DIR = ".silk/natives";
20
+
21
+ // Integers up to 32 bits (and the pointer-sized ones) are numbers; 64-bit ones are bigints, as
22
+ // in the TypeScript spike. A number that does not fit the parameter's type is a TypeError.
23
+ const NUMBERS = new Set(["i8", "i16", "i32", "u8", "u16", "u32", "isize", "usize", "f32", "f64"]);
24
+ const BIGINTS = new Set(["i64", "u64"]);
25
+
26
+ /** How one Silk type crosses into JavaScript, or undefined when it cannot yet. */
27
+ export function crossing(silkType) {
28
+ const type = silkType.trim();
29
+ if (NUMBERS.has(type)) return { silk: type, ts: "number", kind: "n" };
30
+ if (BIGINTS.has(type)) return { silk: type, ts: "bigint", kind: "s" };
31
+ if (type === "bool") return { silk: type, ts: "boolean", kind: "b" };
32
+ if (type === "string" || type === "string<'static>") return { silk: type, ts: "string", kind: "s" };
33
+ if (type === "String") return { silk: type, ts: "string", kind: "s" };
34
+ if (type === "" || type === "()") return { silk: "()", ts: "void", kind: "" };
35
+ return undefined;
36
+ }
37
+
38
+ /** The id JavaScript calls `module.name` by. The dispatcher compares the same numbers. */
39
+ export function nativeId(qualified) {
40
+ let hash = 0;
41
+ for (const byte of new TextEncoder().encode(qualified)) hash = (hash * 31 + byte) % 2147483629;
42
+ return hash;
43
+ }
44
+
45
+ /** `pub [effect] fn name(params) [-> T] [! E] [? R]`, or null for anything else. */
46
+ export function parseSignature(signature) {
47
+ const match = /^pub (effect )?fn ([A-Za-z_][A-Za-z0-9_]*)\((.*)\)\s*(?:->\s*([^!?]+?))?\s*(?:!\s*([^?]+?))?\s*(?:\?\s*(.+))?$/s.exec(signature.trim());
48
+ if (!match) return null;
49
+ const [, effect, name, params, returns = "()", fails = "", requires = ""] = match;
50
+ return { effect: effect !== undefined, name, params, returns: returns.trim(), fails: fails.trim(), requires: requires.trim() };
51
+ }
52
+
53
+ /** One public function of a module as JavaScript sees it, with `unsupported` saying why not. */
54
+ export function describeFunction(module, item, parameters) {
55
+ const parsed = parseSignature(item.signature);
56
+ const fn = { name: item.name, id: nativeId(`${module}.${item.name}`), doc: item.documentation?.markdown ?? "", signature: item.signature, at: item.source?.start ?? 0 };
57
+ if (!parsed) return { ...fn, unsupported: `\`${item.signature}\` is not a plain function (generic, or a method)` };
58
+ const params = parameters.map((parameter) => {
59
+ const at = parameter.signature.indexOf(":");
60
+ return { name: parameter.name, at: parameter.source?.start ?? 0, silk: parameter.signature.slice(at + 1).trim(), ...crossing(parameter.signature.slice(at + 1)) };
61
+ });
62
+ const returns = crossing(parsed.returns);
63
+ const bad = [...params.filter((p) => !p.ts).map((p) => p.silk), ...(returns ? [] : [parsed.returns])];
64
+ if (bad.length) return { ...fn, unsupported: `${bad.map((t) => `\`${t}\``).join(", ")} cannot cross into JavaScript yet` };
65
+ const requires = parsed.requires.split("|").map((r) => r.trim()).filter(Boolean);
66
+ const other = requires.filter((r) => r !== "&mut Allocator");
67
+ if (other.length) return { ...fn, unsupported: `it needs ${other.map((r) => `\`${r}\``).join(", ")}; the host provides only \`&mut Allocator\`` };
68
+ return {
69
+ ...fn,
70
+ effect: parsed.effect,
71
+ fails: parsed.fails,
72
+ params: params.map(({ name, at, silk, ts, kind }) => ({ name, at, silk, ts, kind })),
73
+ returns: { silk: returns.silk === "()" ? "()" : parsed.returns, ts: returns.ts },
74
+ };
75
+ }
76
+
77
+ /** `[package]` fields of a silk.toml that matter here: kind, source and exports. */
78
+ export function packageFields(toml) {
79
+ const section = /^\[package\]\s*$([\s\S]*?)(?=^\[|(?![\s\S]))/m.exec(toml)?.[1] ?? "";
80
+ const string = (key) => new RegExp(`^${key}\\s*=\\s*"([^"]*)"`, "m").exec(section)?.[1];
81
+ const list = /^exports\s*=\s*\[([^\]]*)\]/m.exec(section)?.[1] ?? "";
82
+ return { kind: string("kind") ?? "executable", source: string("source") ?? "src", exports: [...list.matchAll(/"([^"]+)"/g)].map((m) => m[1]) };
83
+ }
84
+
85
+ /** The nearest directory at or above `from` with a silk.toml, or null. */
86
+ export function projectRoot(from) {
87
+ let dir = resolve(from);
88
+ while (true) {
89
+ if (existsSync(join(dir, "silk.toml"))) return dir;
90
+ const parent = dirname(dir);
91
+ if (parent === dir) return null;
92
+ dir = parent;
93
+ }
94
+ }
95
+
96
+ /** Runs `silk doc` on the project at `root`: the parsed JSON. */
97
+ export async function silkDoc(root, silk = process.env.SILK ?? "silk") {
98
+ const scratch = await mkdtemp(join(tmpdir(), "silkui-natives-"));
99
+ try {
100
+ const output = join(scratch, "doc.json");
101
+ try {
102
+ await run(silk, ["doc", "--manifest-path", join(root, "silk.toml"), "--output", output], { cwd: root });
103
+ } catch (error) {
104
+ if (error.code === "ENOENT") throw new Error(`cannot run \`${silk}\`: put silk on PATH or set SILK to its path`);
105
+ throw new Error(`silk doc failed in ${root}:\n${error.stderr || error.stdout || error.message}`);
106
+ }
107
+ return JSON.parse(await readFile(output, "utf8"));
108
+ } finally {
109
+ await rm(scratch, { recursive: true, force: true });
110
+ }
111
+ }
112
+
113
+ /**
114
+ * The exported modules of the project at `root` and their functions. `doc` is `silk doc`'s
115
+ * JSON; without it this runs `silk doc`. A project without `exports` has none.
116
+ */
117
+ export async function describeProject(root, doc) {
118
+ const fields = packageFields(readFileSync(join(root, "silk.toml"), "utf8"));
119
+ const description = { version: 1, root, library: fields.kind === "library", modules: [] };
120
+ if (fields.exports.length === 0) return description;
121
+ doc ??= await silkDoc(root);
122
+ for (const module of doc.modules) {
123
+ if (!fields.exports.includes(module.name)) continue;
124
+ const items = module.items ?? [];
125
+ const functions = [];
126
+ items.forEach((item, index) => {
127
+ if (item.kind !== "Function" || item.visibility !== "Public" || item.parent !== undefined) return;
128
+ const parameters = items.filter((p) => p.kind === "Parameter" && p.parent === index);
129
+ functions.push(describeFunction(module.name, item, parameters));
130
+ });
131
+ description.modules.push({ module: module.name, file: module.sourcePath, functions });
132
+ }
133
+ return description;
134
+ }
135
+
136
+ /** The module of `description` whose source is `file`. */
137
+ export function moduleOf(description, file) {
138
+ const wanted = resolve(file);
139
+ return description.modules.find((m) => resolve(m.file) === wanted);
140
+ }
141
+
142
+ // --- Silk: the dispatcher in the host ---
143
+
144
+ function argument(param, at, signature) {
145
+ const value = `args, ${at}`;
146
+ switch (param.silk) {
147
+ case "f64": return { let: `let a${at} = number(${value})` };
148
+ case "f32": return { let: `let a${at} = f64.toF32(number(${value}))` };
149
+ case "bool": return { let: `let a${at} = flag(${value})` };
150
+ case "i64": return { let: `let a${at} = signed(${value})` };
151
+ case "u64": return { let: `let a${at} = unsigned(${value})` };
152
+ case "String": return { let: `let a${at} = run String.copy(text(${value}))`, pass: `move a${at}` };
153
+ case "string":
154
+ case "string<'static>": return { let: `let a${at} = text(${value})` };
155
+ default: {
156
+ const to = param.silk[0].toUpperCase() + param.silk.slice(1);
157
+ return {
158
+ let: `let a${at} = match f64.checkedTo${to}(number(${value})) {\n Option.Some { value } => value\n Option.None => {\n reply.* = run wrongArguments(${JSON.stringify(signature)})\n return ()\n }\n }`,
159
+ };
160
+ }
161
+ }
162
+ }
163
+
164
+ function replyOf(silkType) {
165
+ switch (silkType) {
166
+ case "()": return null;
167
+ case "f64": return "Reply.Number { value: value }";
168
+ case "bool": return "Reply.Flag { value: value }";
169
+ case "i64": return "run fromSigned(value)";
170
+ case "u64": return "run fromUnsigned(value)";
171
+ case "String": return "Reply.Text { value: move value }";
172
+ case "string":
173
+ case "string<'static>": return "run copied(value)";
174
+ default: return `Reply.Number { value: ${silkType}.toF64(value) }`;
175
+ }
176
+ }
177
+
178
+ /** `add(a: number, b: number)`, as a TypeError names what a function takes. */
179
+ function jsSignature(fn) {
180
+ return `${fn.name}(${fn.params.map((p) => `${p.name}: ${p.ts}`).join(", ")})`;
181
+ }
182
+
183
+ /** The host's `src/natives.silk`: an `Exports` dispatcher over every supported function. */
184
+ export function silkGlue(description) {
185
+ const modules = description.modules.filter((m) => m.functions.some((fn) => !fn.unsupported));
186
+ const nums = new Set(["f64"]);
187
+ const lines = [];
188
+ modules.forEach((module, index) => {
189
+ for (const fn of module.functions) {
190
+ if (fn.unsupported) continue;
191
+ const signature = jsSignature(fn);
192
+ const call = `m${index}.${fn.name}`;
193
+ lines.push(` if id == ${fn.id} {`);
194
+ lines.push(` if !accepts(args, ${JSON.stringify(fn.params.map((p) => p.kind).join(""))}) {`);
195
+ lines.push(` reply.* = run wrongArguments(${JSON.stringify(signature)})`);
196
+ lines.push(` return ()`);
197
+ lines.push(` }`);
198
+ const passed = fn.params.map((param, at) => {
199
+ const { let: binding, pass } = argument(param, at, signature);
200
+ if (NUMBERS.has(param.silk)) nums.add(param.silk);
201
+ lines.push(` ${binding}`);
202
+ return pass ?? `a${at}`;
203
+ });
204
+ const invoke = `${call}(${passed.join(", ")})`;
205
+ const answer = replyOf(fn.returns.silk);
206
+ if (NUMBERS.has(fn.returns.silk)) nums.add(fn.returns.silk);
207
+ const bound = answer ? "let value = " : "";
208
+ if (fn.fails) {
209
+ lines.push(` let ran = run Effect.result(${invoke})`);
210
+ lines.push(` ${answer ? "let value = " : ""}match move ran {`);
211
+ lines.push(` Result.Success { value } => ${answer ? "move value" : "{ drop value }"}`);
212
+ lines.push(` Result.Failure { error } => {`);
213
+ lines.push(` reply.* = run failed(${JSON.stringify(`${module.module}.${fn.name}`)}, ${JSON.stringify(fn.fails)}, move error)`);
214
+ lines.push(` return ()`);
215
+ lines.push(` }`);
216
+ lines.push(` }`);
217
+ } else {
218
+ lines.push(` ${bound}${fn.effect ? "run " : ""}${invoke}`);
219
+ }
220
+ if (answer) lines.push(` reply.* = ${answer}`);
221
+ lines.push(` return ()`);
222
+ lines.push(` }`);
223
+ }
224
+ });
225
+ const body = lines.join("\n");
226
+ const helpers = ["Natives", "Reply", "Exports", "Arg", "serve", "accepts", "number", "flag", "text", "signed", "unsigned", "fromSigned", "fromUnsigned", "wrongArguments", "failed", "copied"];
227
+ const always = new Set(["Natives", "Reply", "Exports", "Arg", "serve"]);
228
+ const used = (text, name) => always.has(name) || new RegExp(`(^|[^A-Za-z0-9_.])${name.replace(".", "\\.")}`).test(text);
229
+ return [
230
+ "//! Generated by silkui: do not edit. `silk task` writes it again on every build.",
231
+ "//! The Silk functions the app's JavaScript imports, for `__ui.native`.",
232
+ ...modules.map((m, index) => `import project.${m.module} as m${index}`),
233
+ `import silkui_window.natives { ${helpers.filter((name) => name.length && used(body, name)).join(", ")} }`,
234
+ "import silk.mem.allocator { Allocator, OutOfMemoryError }",
235
+ ...(used(body, "Effect") ? ["import silk.core.effect { Effect }"] : []),
236
+ ...(used(body, "Option") ? ["import silk.core.option { Option }"] : []),
237
+ ...(used(body, "Result") ? ["import silk.core.result { Result }"] : []),
238
+ "import silk.text.string { String }",
239
+ ...[...nums].sort().filter((n) => used(body, `${n}.`)).map((n) => `import silk.num.${n}`),
240
+ "",
241
+ "struct Exported {}",
242
+ "",
243
+ "impl Exports for Exported {",
244
+ " effect fn dispatch(self: &Self, id: u32, args: &[Arg], reply: &mut Reply) -> () ! OutOfMemoryError ? &mut Allocator {",
245
+ ...lines,
246
+ " reply.* = Reply.TypeError { message: run String.copy(\"this build of the app does not have that Silk function: rebuild it (restart `silk task dev`)\") }",
247
+ " }",
248
+ "}",
249
+ "",
250
+ "export \"C\" fn exported(raw: ?*mut u8) -> () as \"silkui_app_natives\" {",
251
+ " unsafe serve<Exported>(&Exported {}, raw)",
252
+ "}",
253
+ "",
254
+ "/// The dispatcher, for `Settings.natives`.",
255
+ "pub fn all() -> Natives {",
256
+ " return unsafe Natives.fromCallback(exported)",
257
+ "}",
258
+ "",
259
+ ].join("\n");
260
+ }
261
+
262
+ /** Whether `description` exports any function the host can call. */
263
+ export function hasFunctions(description) {
264
+ return description.modules.some((m) => m.functions.some((fn) => !fn.unsupported));
265
+ }
266
+
267
+ // --- JavaScript: what a `.silk` import becomes ---
268
+
269
+ function jsArgument(param) {
270
+ if (param.silk === "i64") return `BigInt.asIntN(64, BigInt(${param.name})).toString()`;
271
+ if (param.silk === "u64") return `BigInt.asUintN(64, BigInt(${param.name})).toString()`;
272
+ return param.name;
273
+ }
274
+
275
+ /** The ES module for `module`: one function per supported export, each with an `async` form. */
276
+ export function jsModule(module) {
277
+ const out = [
278
+ "// Generated by @silkui/vite from a Silk module: the functions run natively in the host.",
279
+ "const ui = globalThis.__ui;",
280
+ "function call(id, args, fails) {",
281
+ " if (!ui?.native) throw new Error(\"Silk functions run only in a Silk UI host\");",
282
+ " if (!fails) return ui.native(id, ...args);",
283
+ " try {",
284
+ " return ui.native(id, ...args);",
285
+ " } catch (error) {",
286
+ " if (error?.name === \"InternalError\") throw new Error(error.message);",
287
+ " throw error;",
288
+ " }",
289
+ "}",
290
+ "function later(id, args, fails) {",
291
+ " if (ui?.nativeStart) return ui.nativeStart(id, ...args);",
292
+ " return new Promise((resolve) => resolve(call(id, args, fails)));",
293
+ "}",
294
+ ];
295
+ for (const fn of module.functions) {
296
+ if (fn.unsupported) {
297
+ out.push(`// ${fn.name}: ${fn.unsupported}`);
298
+ continue;
299
+ }
300
+ const names = fn.params.map((p) => p.name).join(", ");
301
+ const args = `[${fn.params.map(jsArgument).join(", ")}]`;
302
+ const big = fn.returns.silk === "i64" || fn.returns.silk === "u64";
303
+ const fails = fn.fails ? "true" : "false";
304
+ if (fn.doc) out.push(jsDoc(fn.doc));
305
+ out.push(`export function ${fn.name}(${names}) {`);
306
+ out.push(` return ${big ? `BigInt(call(${fn.id}, ${args}, ${fails}))` : `call(${fn.id}, ${args}, ${fails})`};`);
307
+ out.push("}");
308
+ out.push(`${fn.name}.async = (${names}) => later(${fn.id}, ${args}, ${fails})${big ? ".then(BigInt)" : ""};`);
309
+ }
310
+ return `${out.join("\n")}\n`;
311
+ }
312
+
313
+ function jsDoc(markdown) {
314
+ return `/**\n${markdown.split("\n").map((line) => ` * ${line.replaceAll("*/", "*\\/")}`).join("\n")}\n */`;
315
+ }
316
+
317
+ /** The TypeScript declarations of `module`: `native.d.silk.ts` beside the source. */
318
+ export function declarations(module) {
319
+ const out = ["// Generated by @silkui/vite from a Silk module. TypeScript finds it with `allowArbitraryExtensions`."];
320
+ for (const fn of module.functions) {
321
+ if (fn.unsupported) {
322
+ out.push(`// ${fn.name}: ${fn.unsupported}`);
323
+ continue;
324
+ }
325
+ const params = fn.params.map((p) => `${p.name}: ${p.ts}`).join(", ");
326
+ if (fn.doc) out.push(jsDoc(fn.doc));
327
+ out.push(`export declare const ${fn.name}: ((${params}) => ${fn.returns.ts}) & {`);
328
+ out.push(` /** Runs on a background thread. */`);
329
+ out.push(` async(${params}): Promise<${fn.returns.ts}>;`);
330
+ out.push("};");
331
+ }
332
+ if (!module.functions.some((fn) => !fn.unsupported)) out.push("export {};");
333
+ return `${out.join("\n")}\n`;
334
+ }
335
+
336
+ /** The description silkui wrote for the project at `root`, or null before the first build. */
337
+ export function readDescription(root) {
338
+ const path = join(root, NATIVES_DIR, "natives.json");
339
+ return existsSync(path) ? JSON.parse(readFileSync(path, "utf8")) : null;
340
+ }
341
+
342
+ /**
343
+ * Describes the Silk functions the project at `root` exports and writes `NATIVES_DIR`:
344
+ * natives.json, natives.silk (the host's dispatcher) and types/<source>.d.silk.ts. Returns the
345
+ * description.
346
+ */
347
+ export async function writeNatives(root) {
348
+ const description = await describeProject(root);
349
+ const out = join(root, NATIVES_DIR);
350
+ rmSync(out, { recursive: true, force: true });
351
+ mkdirSync(out, { recursive: true });
352
+ writeFileSync(join(out, "natives.json"), `${JSON.stringify(description, null, 2)}\n`);
353
+ if (hasFunctions(description)) {
354
+ if (!description.library) throw new Error("silk.toml exports modules to JavaScript, so the package must be a library: set `kind = \"library\"` and give the tasks their own profile (`[profiles.tasks] main = \"tasks.silk\"`)");
355
+ writeFileSync(join(out, "natives.silk"), silkGlue(description));
356
+ }
357
+ for (const module of description.modules) {
358
+ const types = join(out, "types", `${relative(root, module.file).replace(/\.silk$/, "")}.d.silk.ts`);
359
+ mkdirSync(dirname(types), { recursive: true });
360
+ writeFileSync(types, declarations(module));
361
+ }
362
+ return description;
363
+ }
364
+
365
+ /** Why each function of `description` that JavaScript cannot call is left out. */
366
+ export function leftOut(description) {
367
+ return description.modules.flatMap((module) =>
368
+ module.functions.filter((fn) => fn.unsupported).map((fn) => `${module.module}.${fn.name} is not available to JavaScript: ${fn.unsupported}`),
369
+ );
370
+ }
package/src/report.js ADDED
@@ -0,0 +1,34 @@
1
+ // Prefixed properties whose standard form the stylesheet compiler reads; a prefixed one alone
2
+ // (no standard declaration beside it) would otherwise be dropped.
3
+ const prefixed = /(^|[;{\s])-webkit-(backdrop-filter|mask-image|text-decoration)(\s*:)/g;
4
+
5
+ /** `css` with `-webkit-backdrop-filter`, `-webkit-mask-image` and `-webkit-text-decoration` spelled the standard way. */
6
+ export function standardize(css) {
7
+ return css.replace(prefixed, "$1$2$3");
8
+ }
9
+
10
+ // Other engines' prefixed properties and selectors, as resets such as Tailwind's preflight write them.
11
+ const vendor = /^:{0,2}-(webkit|moz|ms|o)-/;
12
+ // Pseudo-elements of things Silk UI does not have: the top layer and file inputs.
13
+ const absent = new Set(["backdrop", "file-selector-button"]);
14
+
15
+ function quiet(diagnostic) {
16
+ return vendor.test(diagnostic.feature) || (diagnostic.kind === "feature" && absent.has(diagnostic.feature));
17
+ }
18
+
19
+ /**
20
+ * Reports what the stylesheet compiler dropped through `warn`: one line naming the features Silk UI
21
+ * does not draw yet, leaving out other engines' prefixes and pseudo-elements of things it has no
22
+ * equivalent of. `SILKUI_CSS_REPORT=all` writes every dropped feature on its own line instead.
23
+ */
24
+ export function reportDropped(warn, diagnostics) {
25
+ if (process.env.SILKUI_CSS_REPORT === "all") {
26
+ for (const item of diagnostics) warn(`dropped ${item.count} ${item.kind} occurrence(s): ${item.feature}`);
27
+ return;
28
+ }
29
+ const shown = diagnostics.filter(item => !quiet(item));
30
+ if (!shown.length) return;
31
+ const names = shown.map(item => item.count > 1 ? `${item.feature} (${item.count})` : item.feature).join(", ");
32
+ const what = shown.length === 1 ? "1 CSS feature" : `${shown.length} CSS features`;
33
+ warn(`skipped ${what} Silk UI does not draw yet: ${names}. SILKUI_CSS_REPORT=all lists everything dropped.`);
34
+ }
@@ -1,4 +1,5 @@
1
1
  import { compileStylesheet } from './compiler.js';
2
+ import { reportDropped, standardize } from './report.js';
2
3
 
3
4
  const CSS = /\.(?:css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
4
5
  const marker = /[?&]silk-sheet(?:&|$)/;
@@ -53,7 +54,7 @@ if (import.meta.hot) {
53
54
  }
54
55
  let result;
55
56
  try {
56
- result = compileStylesheet(expression.value, { strict, resolveUrl(url) {
57
+ result = compileStylesheet(standardize(expression.value), { strict, resolveUrl(url) {
57
58
  if (!url) return url;
58
59
  const origin = server?.config.server.origin ?? server?.resolvedUrls?.local[0] ?? server?.resolvedUrls?.network[0];
59
60
  try { return new URL(url, origin).href; }
@@ -64,9 +65,7 @@ if (import.meta.hot) {
64
65
  const dropped = error.diagnostics?.map(item => `${item.kind}: ${item.feature} (${item.count})`).join("\n");
65
66
  this.error(error.message + (dropped ? `\n${dropped}` : ""));
66
67
  }
67
- for (const diagnostic of result.diagnostics) {
68
- this.warn(`dropped ${diagnostic.count} ${diagnostic.kind} occurrence(s): ${diagnostic.feature}`);
69
- }
68
+ reportDropped(message => this.warn(message), result.diagnostics);
70
69
  return { code: `export default ${JSON.stringify(Buffer.from(result.bytes).toString('base64'))};`, map: { mappings: '' } };
71
70
  },
72
71
  }];