sepal 0.2.0-alpha.0 → 0.3.0-alpha.0

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.
Files changed (65) hide show
  1. package/README.md +14 -5
  2. package/cli.js +127 -10
  3. package/package.json +48 -4
  4. package/src/abort.js +129 -0
  5. package/src/app.js +13 -0
  6. package/src/dom.js +173 -60
  7. package/src/fetch.js +347 -80
  8. package/src/form-data.js +141 -0
  9. package/src/host-call.js +57 -0
  10. package/src/index.js +9 -11
  11. package/src/lru.js +45 -0
  12. package/src/native.js +32 -0
  13. package/src/notifications.js +60 -0
  14. package/src/os.js +35 -0
  15. package/src/process.js +164 -0
  16. package/src/protocol.js +3 -4
  17. package/src/renderer.js +140 -10
  18. package/src/secrets.js +42 -0
  19. package/src/settings.js +52 -0
  20. package/src/shims.js +30 -8
  21. package/src/stem.js +125 -0
  22. package/src/updater.js +3 -2
  23. package/src/url.js +65 -20
  24. package/src/web.js +86 -0
  25. package/src/window.js +6 -2
  26. package/types/abort.d.ts +46 -0
  27. package/types/app.d.ts +7 -0
  28. package/types/fetch.d.ts +118 -28
  29. package/types/form-data.d.ts +19 -0
  30. package/types/host-call.d.ts +18 -0
  31. package/types/index.d.ts +5 -2
  32. package/types/lru.d.ts +18 -0
  33. package/types/native.d.ts +22 -0
  34. package/types/notifications.d.ts +53 -0
  35. package/types/os.d.ts +53 -0
  36. package/types/process.d.ts +90 -0
  37. package/types/protocol.d.ts +0 -2
  38. package/types/renderer.d.ts +16 -1
  39. package/types/secrets.d.ts +22 -0
  40. package/types/settings.d.ts +29 -0
  41. package/types/shims.d.ts +1 -0
  42. package/types/stem.d.ts +21 -0
  43. package/types/updater.d.ts +6 -4
  44. package/types/url.d.ts +1 -1
  45. package/types/vite/adapter.d.ts +22 -0
  46. package/types/vite/add.d.ts +77 -0
  47. package/types/vite/app.d.ts +52 -1
  48. package/types/vite/licenses.d.ts +11 -0
  49. package/types/vite/native.d.ts +135 -0
  50. package/types/vite/page.d.ts +20 -0
  51. package/types/vite/permissions.d.ts +56 -0
  52. package/types/vite/sveltekit.d.ts +5 -42
  53. package/types/vite/vite.d.ts +86 -29
  54. package/types/web.d.ts +17 -0
  55. package/types/window.d.ts +5 -1
  56. package/vite/adapter.js +118 -0
  57. package/vite/add.js +254 -0
  58. package/vite/app.js +195 -27
  59. package/vite/head.js +2 -2
  60. package/vite/licenses.js +115 -0
  61. package/vite/native.js +535 -0
  62. package/vite/page.js +95 -0
  63. package/vite/permissions.d.ts +56 -0
  64. package/vite/sveltekit.js +11 -263
  65. package/vite/vite.js +378 -109
package/vite/head.js CHANGED
@@ -6,8 +6,8 @@
6
6
  // <svelte:head><title>{item.name} - Shop</title></svelte:head>
7
7
  //
8
8
  // becomes an expression that sets `document.title` whenever what it reads
9
- // changes. With the DOM layer loaded that is also the window's title (given
10
- // `permissions.window`); without it the expression does nothing. Anything else
9
+ // changes. With the DOM layer loaded that is the page's <title>, which the
10
+ // window shows; without it the expression does nothing. Anything else
11
11
  // in the block (<meta>, <link>, <script>) means nothing in an app and is
12
12
  // dropped, with a warning at build time.
13
13
  //
@@ -0,0 +1,115 @@
1
+ // The third-party notices of a host binary: the licences of everything
2
+ // compiled into it, for THIRD-PARTY-LICENSES.txt. calyx's ships next to its
3
+ // binary in its platform package (scripts/third-party-licenses.js), and
4
+ // `calyx --bundle` puts it in every .app, in Contents/SharedSupport. An app
5
+ // that builds its own host (native/) gets the notices of that binary,
6
+ // plugins included.
7
+ //
8
+ // The binary is our code plus several hundred Rust crates (and QuickJS, which
9
+ // comes inside one). Their licences ask for their notices to travel with the
10
+ // binary; Stylo's (MPL-2.0) also asks that people can find its source, so each
11
+ // crate is listed with where it comes from.
12
+ //
13
+ // The texts are the crates' own licence files, read from where Cargo keeps
14
+ // their source, so the copyright lines are theirs. Crates whose files are
15
+ // identical are listed together above one copy of the text. Runs in Node,
16
+ // and needs cargo, which has already built the binary.
17
+
18
+ import { execFileSync } from 'node:child_process';
19
+ import { createHash } from 'node:crypto';
20
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
21
+ import { dirname, join } from 'node:path';
22
+
23
+ /**
24
+ * The notices for the binary `manifest` builds.
25
+ * @param {string} manifest the Cargo.toml the binary is built from
26
+ * @param {string[]} [features] the features it is built with; a superset is fine for a list of notices
27
+ * @returns {{ text: string, crates: number, texts: number }}
28
+ */
29
+ export function third_party_licenses(manifest, features = []) {
30
+ const features_args = features.length > 0 ? ['--features', features.join(',')] : [];
31
+ const metadata = JSON.parse(
32
+ execFileSync('cargo', ['metadata', '--format-version', '1', ...features_args, '--manifest-path', manifest], {
33
+ encoding: 'utf8',
34
+ maxBuffer: 256 * 1024 * 1024
35
+ })
36
+ );
37
+
38
+ /** @type {Map<string, any>} */
39
+ const packages = new Map(metadata.packages.map((/** @type {any} */ pkg) => [pkg.id, pkg]));
40
+ /** @type {Map<string, any>} */
41
+ const nodes = new Map(metadata.resolve.nodes.map((/** @type {any} */ node) => [node.id, node]));
42
+
43
+ // What ends up in the binary: reachable from the host through ordinary
44
+ // dependencies. Build scripts and tests are not linked in.
45
+ const linked = new Set();
46
+ const queue = [metadata.resolve.root];
47
+ while (queue.length > 0) {
48
+ const id = /** @type {string} */ (queue.pop());
49
+ if (linked.has(id)) continue;
50
+ linked.add(id);
51
+ for (const dep of nodes.get(id).deps) {
52
+ if (dep.dep_kinds.some((/** @type {any} */ kind) => kind.kind === null)) queue.push(dep.pkg);
53
+ }
54
+ }
55
+ linked.delete(metadata.resolve.root);
56
+
57
+ const notice = /^(licen[sc]e|copying|notice|unlicense)/i;
58
+
59
+ /** @type {Map<string, { text: string, crates: string[] }>} licence text by its hash */
60
+ const texts = new Map();
61
+ /** @type {string[]} */
62
+ const index = [];
63
+ /** @type {string[]} */
64
+ const without_text = [];
65
+
66
+ for (const id of [...linked].sort((a, b) => packages.get(a).name.localeCompare(packages.get(b).name))) {
67
+ const pkg = packages.get(id);
68
+ const label = `${pkg.name} ${pkg.version}`;
69
+ // Our own patched copies are listed too: they are still their authors' work.
70
+ const source = pkg.repository ?? pkg.homepage ?? `https://crates.io/crates/${pkg.name}`;
71
+ index.push(`${label} (${pkg.license ?? 'see its licence file'}) ${source}`);
72
+
73
+ const directory = dirname(pkg.manifest_path);
74
+ // One level down as well: a crate that wraps a C library keeps the
75
+ // library, and its licence, in a subdirectory (QuickJS in rquickjs-sys),
76
+ // and some crates keep theirs in a `LICENSES` directory.
77
+ const files = existsSync(directory)
78
+ ? readdirSync(directory, { withFileTypes: true })
79
+ .flatMap((entry) =>
80
+ entry.isDirectory() && entry.name !== 'target'
81
+ ? readdirSync(join(directory, entry.name), { withFileTypes: true })
82
+ .filter((inner) => inner.isFile() && (notice.test(inner.name) || notice.test(entry.name)))
83
+ .map((inner) => join(entry.name, inner.name))
84
+ : entry.isFile() && notice.test(entry.name)
85
+ ? [entry.name]
86
+ : []
87
+ )
88
+ .sort()
89
+ : [];
90
+ if (files.length === 0) without_text.push(label);
91
+ for (const file of files) {
92
+ // Line endings and trailing space differ between otherwise identical copies.
93
+ const text = readFileSync(join(directory, file), 'utf8').replace(/\r\n/g, '\n').replace(/[ \t]+$/gm, '').trim();
94
+ const key = createHash('sha256').update(text).digest('hex');
95
+ if (!texts.has(key)) texts.set(key, { text, crates: [] });
96
+ /** @type {{ crates: string[] }} */ (texts.get(key)).crates.push(label);
97
+ }
98
+ }
99
+
100
+ const rule = '='.repeat(78);
101
+ const sections = [...texts.values()]
102
+ .sort((a, b) => b.crates.length - a.crates.length)
103
+ .map(({ text, crates }) => `${rule}\n${[...new Set(crates)].join(', ')}\n${rule}\n\n${text}\n`);
104
+
105
+ const text = `Third-party software in the Sepal host binary
106
+
107
+ The host is built from the crates listed below. Each is the work of its
108
+ authors and is used under the licence named beside it; the source of each is
109
+ at the address given. The licence texts follow the list.
110
+
111
+ ${index.join('\n')}
112
+ ${without_text.length > 0 ? `\nPublished without a licence file of their own. The licence named above applies;\nthe texts of those licences (MIT, Apache-2.0, MPL-2.0) are among those below:\n${without_text.join(', ')}\n` : ''}
113
+ ${sections.join('\n')}`;
114
+ return { text, crates: linked.size, texts: texts.size };
115
+ }
package/vite/native.js ADDED
@@ -0,0 +1,535 @@
1
+ // An app's own host: the Rust crate in `native/`, which builds calyx with the
2
+ // app's commands and plugins (`sepal::App`). When `native/Cargo.toml` exists,
3
+ // dev (`vite build --watch`) and `sepal run`, `screenshot` and `bundle` build
4
+ // it with cargo and run that binary, through `SEPAL_HOST`, instead of the
5
+ // prebuilt calyx. Everything here runs in Node.
6
+ //
7
+ // Every app on a machine shares one Cargo build directory (`cargo_dir()`),
8
+ // so Blitz, Stylo and wgpu compile once per profile; each app's own binary
9
+ // goes to its own target directory, `node_modules/.sepal/native`. Cargo
10
+ // keys what it builds by the compiler, so each compiler gets a subdirectory
11
+ // of its own (`rustc-<release>-<commit>`, about 5 GB with both profiles):
12
+ // a Rust update starts a new one, and one no build has used for 30 days is
13
+ // removed by the next build. `sepal native clean` removes them all.
14
+
15
+ import { execFile, spawn, spawnSync } from 'node:child_process';
16
+ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, watch, writeFileSync } from 'node:fs';
17
+ import { homedir } from 'node:os';
18
+ import { basename, dirname, join, relative, resolve, sep } from 'node:path';
19
+
20
+ export const REPOSITORY = 'https://github.com/etherCorps/sepal';
21
+
22
+ /** Sepal's patched crates, in the order `[patch.crates-io]` lists them. */
23
+ export const PATCHED = ['blitz-dom', 'anyrender_vello_hybrid', 'vello_gpu', 'wgpu-hal', 'rquickjs-sys'];
24
+
25
+ /**
26
+ * The newest release a dependency of the host asks for: oo7, the keychain on
27
+ * Linux. (Cargo's split of build-dir from target-dir, which the shared build
28
+ * directory needs, is stable from 1.91.) The crate's `rust-version` is the
29
+ * same number; crates/host/tests/package.rs compares them.
30
+ */
31
+ const RUST = /** @type {const} */ ([1, 95]);
32
+
33
+ /** The system libraries a Linux build links against, as `.github/actions/setup` installs them. */
34
+ const LINUX_LIBRARIES = ['fontconfig', 'wayland-client', 'xkbcommon', 'x11', 'xcursor', 'xi', 'xrandr'];
35
+
36
+ /** The version of this sepal, which `native/` has to build its host from. */
37
+ export const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
38
+
39
+ /** @typedef {{ numbers: number[], pre: string[] | undefined }} Version */
40
+
41
+ /** @param {string} version @returns {Version | null} */
42
+ function parsed(version) {
43
+ const parts = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(version);
44
+ return parts && { numbers: [Number(parts[1]), Number(parts[2]), Number(parts[3])], pre: parts[4]?.split('.') };
45
+ }
46
+
47
+ /** Semver's order: negative when `a` is before `b`. @param {Version} a @param {Version} b */
48
+ function order(a, b) {
49
+ for (let at = 0; at < 3; at++) if (a.numbers[at] !== b.numbers[at]) return a.numbers[at] - b.numbers[at];
50
+ // A release is after its pre-releases.
51
+ if (!a.pre || !b.pre) return Number(!a.pre) - Number(!b.pre);
52
+ for (let at = 0; at < Math.max(a.pre.length, b.pre.length); at++) {
53
+ const [x, y] = [a.pre[at], b.pre[at]];
54
+ if (x === y) continue;
55
+ // `alpha` is before `alpha.0`.
56
+ if (x === undefined || y === undefined) return x === undefined ? -1 : 1;
57
+ const [number_x, number_y] = [/^\d+$/.test(x), /^\d+$/.test(y)];
58
+ if (number_x && number_y) return Number(x) - Number(y);
59
+ // A number is before a word.
60
+ if (number_x !== number_y) return number_x ? -1 : 1;
61
+ return x < y ? -1 : 1;
62
+ }
63
+ return 0;
64
+ }
65
+
66
+ /**
67
+ * Whether `version` is in the caret range `^base`, as Cargo and npm both
68
+ * read one: at `base` or after it, in its 0.x line (its major from 1.0 on),
69
+ * and a pre-release only of `base`'s own major.minor.patch. This is how a
70
+ * plugin names sepal, in its crate and in its package's peer range.
71
+ * @param {string} base @param {string} version
72
+ */
73
+ export function caret_accepts(base, version) {
74
+ const [from, to] = [parsed(base), parsed(version)];
75
+ if (!from || !to) return false;
76
+ const same = (/** @type {number} */ count) => from.numbers.slice(0, count).every((number, at) => number === to.numbers[at]);
77
+ // What a caret holds still: up to the first number that is not zero.
78
+ if (!same(from.numbers[0] > 0 ? 1 : from.numbers[1] > 0 ? 2 : 3)) return false;
79
+ if (to.pre && !(from.pre && same(3))) return false;
80
+ return order(from, to) <= 0;
81
+ }
82
+
83
+ /** @param {string} root the project @returns {string | null} `native/Cargo.toml`, if the app has one */
84
+ export function native_manifest(root) {
85
+ const manifest = join(root, 'native', 'Cargo.toml');
86
+ return existsSync(manifest) ? manifest : null;
87
+ }
88
+
89
+ /** How long another compiler's build directory is kept unused. */
90
+ const KEEP_DAYS = 30;
91
+
92
+ /** Touched by every build in a compiler's build directory: when it was last used. */
93
+ const STAMP = '.sepal-used';
94
+
95
+ /** The build directory every app on this machine shares: one subdirectory per compiler. */
96
+ export function cargo_dir(env = process.env) {
97
+ if (env.SEPAL_CARGO_DIR) return resolve(env.SEPAL_CARGO_DIR);
98
+ if (process.platform === 'darwin') return join(homedir(), 'Library/Caches/sepal/cargo');
99
+ return join(env.XDG_CACHE_HOME || join(homedir(), '.cache'), 'sepal/cargo');
100
+ }
101
+
102
+ /**
103
+ * The crate's name, from the app's id (`app.sepal.tracker` is
104
+ * `app-sepal-tracker`) or else its package name.
105
+ * @param {string | undefined} id @param {string | undefined} package_name
106
+ */
107
+ export function crate_name(id, package_name) {
108
+ const base = (id || package_name?.replace(/^@[^/]+\//, '') || 'app').toLowerCase();
109
+ const name = base.replace(/[^a-z0-9_-]+/g, '-').replace(/^[^a-z]+/, '').replace(/-+$/, '');
110
+ return name || 'app';
111
+ }
112
+
113
+ /**
114
+ * Where `native/Cargo.toml` takes sepal and the patched crates from: this
115
+ * release's tag in the repository, or, with `SEPAL_CRATES` (this repository's
116
+ * own examples and tests), the crates by path.
117
+ * @param {string} native the native/ directory
118
+ * @param {string} version
119
+ * @param {string | undefined} crates `SEPAL_CRATES`
120
+ * @returns {(name: string) => string} the source of the crate in `crates/<dir>`, as TOML
121
+ */
122
+ function source(native, version, crates) {
123
+ if (crates) {
124
+ // Real paths at both ends: Cargo resolves a path from the real one
125
+ // (/tmp is /private/tmp on macOS).
126
+ const real = (/** @type {string} */ path) => (existsSync(path) ? realpathSync(path) : resolve(path));
127
+ const from = existsSync(native) ? real(native) : join(real(dirname(native)), 'native');
128
+ return (dir) => `path = "${relative(from, join(real(crates), dir)).split(sep).join('/')}"`;
129
+ }
130
+ return () => `git = "${REPOSITORY}", tag = "v${version}"`;
131
+ }
132
+
133
+ /**
134
+ * What `sepal native init` writes, by path under the project.
135
+ * @param {{ name: string, version: string, native: string, crates?: string }} options
136
+ * @returns {Record<string, string>}
137
+ */
138
+ export function init_files({ name, version, native, crates }) {
139
+ const from = source(native, version, crates);
140
+ const patches = PATCHED.map((crate) => `${crate} = { ${from(crate)} }`).join('\n');
141
+ return {
142
+ 'native/Cargo.toml': `# This app's own host: everything calyx does, plus the commands and plugins in
143
+ # src/. \`vite build --watch\` (dev) and \`sepal bundle\` build it, and so does
144
+ # \`sepal native build\` on its own.
145
+ [package]
146
+ name = "${name}"
147
+ version = "0.1.0"
148
+ edition = "2024"
149
+ publish = false
150
+
151
+ [dependencies]
152
+ sepal = { ${from('host')}, features = ["screenshot"] }
153
+
154
+ # Sepal's patched crates, from the same release (each one's PATCH.md says
155
+ # what it changes). Keep them: without them sepal stops the build and names
156
+ # what is missing. \`sepal native update\` moves all of these to a new release.
157
+ [patch.crates-io]
158
+ ${patches}
159
+
160
+ # Cargo reads profiles from this file only: these are calyx's own, so a dev
161
+ # build is fast enough to use and a bundle is the size calyx is.
162
+ [profile.dev]
163
+ opt-level = 1
164
+
165
+ [profile.dev.package."*"]
166
+ opt-level = 2
167
+
168
+ [profile.release]
169
+ lto = "thin"
170
+ strip = true
171
+
172
+ [profile.dist]
173
+ inherits = "release"
174
+ lto = "fat"
175
+ codegen-units = 1
176
+ `,
177
+ 'native/src/main.rs': `//! This app's own host. JavaScript calls a command with \`invoke('hello',
178
+ //! 'world')\` from \`sepal/native\`; see ${REPOSITORY}.
179
+ mod plugins;
180
+
181
+ fn main() -> std::process::ExitCode {
182
+ plugins::add(sepal::App::new())
183
+ .command("hello", |_call: &sepal::Call, name: String| {
184
+ Ok(format!("Hello, {name}!"))
185
+ })
186
+ .run()
187
+ }
188
+ `,
189
+ 'native/src/plugins.rs': `// Written by \`sepal add\`: it lists the app's plugins, and is written again
190
+ // when one is added or removed. Edits here are lost.
191
+ pub fn add(app: sepal::App) -> sepal::App {
192
+ app
193
+ }
194
+ `
195
+ };
196
+ }
197
+
198
+ /** The lines `native init` wrote that name a release of the repository. */
199
+ const TAGGED = /(git\s*=\s*"https:\/\/github\.com\/etherCorps\/sepal(?:\.git)?"\s*,\s*tag\s*=\s*")([^"]*)(")/g;
200
+
201
+ /**
202
+ * Why `native/` cannot be built with this sepal, or null: its lines name
203
+ * another release's tag. The host and the JavaScript are released together.
204
+ * @param {string} manifest @param {string} version
205
+ */
206
+ export function tag_problem(manifest, version) {
207
+ const tags = [...readFileSync(manifest, 'utf8').matchAll(TAGGED)].map((match) => match[2]);
208
+ const other = [...new Set(tags.filter((tag) => tag !== `v${version}`))];
209
+ if (other.length === 0) return null;
210
+ return (
211
+ `sepal: native/Cargo.toml builds this app's host from sepal ${other.join(', ')}, and this is sepal ${version}.\n` +
212
+ 'The host and the JavaScript are released together, and that pair is not. To build it from this release:\n\n' +
213
+ ' sepal native update\n'
214
+ );
215
+ }
216
+
217
+ /** Point the lines that name a release at this one. @param {string} manifest @param {string} version @returns {number} the lines changed */
218
+ export function update_tag(manifest, version) {
219
+ let changed = 0;
220
+ const text = readFileSync(manifest, 'utf8').replace(TAGGED, (_, before, tag, after) => {
221
+ if (tag !== `v${version}`) changed++;
222
+ return `${before}v${version}${after}`;
223
+ });
224
+ writeFileSync(manifest, text);
225
+ return changed;
226
+ }
227
+
228
+ /** @param {string} command @param {string[]} args @param {NodeJS.ProcessEnv} env @param {string} [cwd] */
229
+ function works(command, args, env, cwd) {
230
+ const done = spawnSync(command, args, { encoding: 'utf8', env, cwd });
231
+ return done.error || done.status !== 0 ? null : done.stdout;
232
+ }
233
+
234
+ /**
235
+ * The subdirectory for a compiler, from `rustc -vV`: `rustc-1.95.0-59807616e`.
236
+ * The commit tells nightlies of one release apart.
237
+ * @param {string} verbose
238
+ */
239
+ export function compiler_dir(verbose) {
240
+ const field = (/** @type {string} */ name) => verbose.match(new RegExp(`^${name}: (.+)$`, 'm'))?.[1].trim();
241
+ return `rustc-${field('release') ?? 'unknown'}-${(field('commit-hash') ?? 'unknown').slice(0, 9)}`;
242
+ }
243
+
244
+ /**
245
+ * The build directory for `native/`: the shared one's subdirectory for the
246
+ * compiler cargo uses there (rustup picks it from the directory, with its
247
+ * rust-toolchain file).
248
+ * @param {string} manifest @param {NodeJS.ProcessEnv} [env]
249
+ */
250
+ export function build_dir(manifest, env = process.env) {
251
+ return join(cargo_dir(env), compiler_dir(works('rustc', ['-vV'], env, dirname(manifest)) ?? ''));
252
+ }
253
+
254
+ /**
255
+ * Remove the other compilers' build directories that no build has used for
256
+ * 30 days. Only `rustc-*` directories: nothing else in `base` is ours.
257
+ * @param {string} base @param {string} keep the one in use @param {number} [now]
258
+ * @returns {string[]} what was removed
259
+ */
260
+ export function prune(base, keep, now = Date.now()) {
261
+ /** @type {string[]} */
262
+ const removed = [];
263
+ let entries;
264
+ try {
265
+ entries = readdirSync(base, { withFileTypes: true });
266
+ } catch {
267
+ return removed;
268
+ }
269
+ for (const entry of entries) {
270
+ if (!entry.isDirectory() || !entry.name.startsWith('rustc-') || entry.name === keep) continue;
271
+ const dir = join(base, entry.name);
272
+ const used = existsSync(join(dir, STAMP)) ? statSync(join(dir, STAMP)).mtimeMs : statSync(dir).mtimeMs;
273
+ if (now - used > KEEP_DAYS * 24 * 60 * 60 * 1000) {
274
+ rmSync(dir, { recursive: true, force: true });
275
+ removed.push(entry.name);
276
+ }
277
+ }
278
+ return removed;
279
+ }
280
+
281
+ /** `sepal native clean`: the whole shared directory, every compiler's. @returns {string} what was removed */
282
+ export function clean(env = process.env) {
283
+ const base = cargo_dir(env);
284
+ const size = works('du', ['-sh', base], env)?.split('\t')[0];
285
+ rmSync(base, { recursive: true, force: true });
286
+ return size ? `${base} (${size})` : base;
287
+ }
288
+
289
+ /**
290
+ * What this machine is missing to build `native/`, as the message to print,
291
+ * or null.
292
+ * @param {NodeJS.ProcessEnv} [env]
293
+ */
294
+ export function toolchain_problem(env = process.env) {
295
+ const cargo = works('cargo', ['--version'], env);
296
+ const version = cargo?.match(/(\d+)\.(\d+)/)?.slice(1).map(Number);
297
+ const old = version !== undefined && (version[0] < RUST[0] || (version[0] === RUST[0] && version[1] < RUST[1]));
298
+ /** @type {string[]} */
299
+ const missing = [];
300
+ /** @type {string[]} */
301
+ const steps = [];
302
+ if (cargo === null) {
303
+ missing.push(`Rust ${RUST.join('.')} or later`);
304
+ steps.push(` curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh (https://rustup.rs)`);
305
+ } else if (old) {
306
+ missing.push(`Rust ${RUST.join('.')} or later (this machine has ${cargo.trim()})`);
307
+ steps.push(' rustup update');
308
+ }
309
+ if (process.platform === 'darwin' && works('xcode-select', ['-p'], env) === null) {
310
+ missing.push("Xcode's command line tools (the linker)");
311
+ steps.push(' xcode-select --install');
312
+ }
313
+ if (
314
+ process.platform === 'linux' &&
315
+ (works('cc', ['--version'], env) === null || works('pkg-config', ['--exists', ...LINUX_LIBRARIES], env) === null)
316
+ ) {
317
+ missing.push('a C compiler, pkg-config and the system libraries the window links against');
318
+ steps.push(
319
+ ' sudo apt install build-essential pkg-config libfontconfig1-dev libwayland-dev libxkbcommon-dev \\',
320
+ ' libx11-dev libxcursor-dev libxi-dev libxrandr-dev (Debian, Ubuntu)',
321
+ ' sudo dnf install gcc pkgconf-pkg-config fontconfig-devel wayland-devel libxkbcommon-devel \\',
322
+ ' libX11-devel libXcursor-devel libXi-devel libXrandr-devel (Fedora)'
323
+ );
324
+ }
325
+ if (steps.length === 0) return null;
326
+ return (
327
+ 'sepal: this app has native/ (its own host, in Rust), and building it needs what this machine is missing:\n' +
328
+ `${missing.map((what) => ` - ${what}`).join('\n')}\n\nTo install it:\n\n${steps.join('\n')}\n\n` +
329
+ 'Then run this again. An app without native/ runs on the prebuilt calyx and needs none of this.'
330
+ );
331
+ }
332
+
333
+ /** Whether this compiler has built a host here before: the first build compiles everything. @param {string} dir */
334
+ function first_build(dir) {
335
+ return !existsSync(join(dir, 'debug')) && !existsSync(join(dir, 'dist'));
336
+ }
337
+
338
+ /**
339
+ * Build `native/` with cargo, its progress on this terminal. Resolves to the
340
+ * binary, or to the error when cargo fails.
341
+ * @param {string} manifest `native/Cargo.toml`
342
+ * @param {'dev' | 'dist'} profile
343
+ * @returns {Promise<{ binary: string } | { error: string }>}
344
+ */
345
+ export function build(manifest, profile) {
346
+ const project = dirname(dirname(manifest));
347
+ const args = [
348
+ 'build',
349
+ '--manifest-path',
350
+ manifest,
351
+ '--profile',
352
+ profile,
353
+ '--target-dir',
354
+ join(project, 'node_modules/.sepal/native'),
355
+ // Diagnostics as cargo prints them, on stderr; on stdout, the binary's path.
356
+ '--message-format=json-render-diagnostics'
357
+ ];
358
+ const env = { ...process.env, CARGO_BUILD_BUILD_DIR: process.env.CARGO_BUILD_BUILD_DIR ?? shared(manifest) };
359
+ return new Promise((done) => {
360
+ const cargo = spawn('cargo', args, { stdio: ['ignore', 'pipe', 'inherit'], env });
361
+ /** @type {string | null} */
362
+ let binary = null;
363
+ let rest = '';
364
+ cargo.stdout.setEncoding('utf8');
365
+ cargo.stdout.on('data', (chunk) => {
366
+ const lines = (rest + chunk).split('\n');
367
+ rest = lines.pop() ?? '';
368
+ for (const line of lines) {
369
+ if (!line.startsWith('{')) continue;
370
+ const message = JSON.parse(line);
371
+ if (message.reason === 'compiler-artifact' && message.executable && resolve(message.manifest_path) === resolve(manifest)) {
372
+ binary = message.executable;
373
+ }
374
+ }
375
+ });
376
+ cargo.on('error', (error) => done({ error: `cannot start cargo: ${error.message}` }));
377
+ cargo.on('close', (code) => {
378
+ if (code === 0 && binary) {
379
+ if (profile === 'dev') sign_dev_host(binary, process.env.SEPAL_SIGN);
380
+ done({ binary });
381
+ } else done({ error: code === 0 ? 'cargo built no binary' : `cargo stopped (exit ${code})` });
382
+ });
383
+ });
384
+ }
385
+
386
+ /**
387
+ * Sign dev's host with the app's signing identity (`SEPAL_SIGN`), on macOS.
388
+ *
389
+ * The keychain knows a program by its code signature, and the linker signs
390
+ * each build ad hoc, as a hash of the binary: to the keychain every rebuild
391
+ * is another program, asked before it reads a secret the last one stored.
392
+ * Signed with one identity under one identifier, the builds are one
393
+ * program. Only a binary cargo just linked is signed (its signature is the
394
+ * linker's again), so an unchanged host is not touched and dev does not
395
+ * restart it.
396
+ * @param {string} binary @param {string | undefined} identity
397
+ * @param {typeof spawnSync} [run]
398
+ * @returns {boolean} whether it signed it
399
+ */
400
+ export function sign_dev_host(binary, identity, run = spawnSync) {
401
+ if (process.platform !== 'darwin' || !identity) return false;
402
+ const signature = run('codesign', ['--display', '--verbose', binary], { encoding: 'utf8' });
403
+ if (!String(signature.stderr).includes('Signature=adhoc')) return false;
404
+ const signed = run('codesign', ['--force', '--sign', identity, '--identifier', basename(binary), binary], { encoding: 'utf8' });
405
+ if (signed.status !== 0) {
406
+ console.error(`sepal: could not sign dev's host with SEPAL_SIGN (${identity}); macOS will ask before it reads secrets an earlier build stored.\n${String(signed.stderr).trim()}`);
407
+ return false;
408
+ }
409
+ return true;
410
+ }
411
+
412
+ /**
413
+ * The directories of every crate `native/` has by path, itself included:
414
+ * what a rebuild in dev watches.
415
+ * @param {string} manifest
416
+ * @returns {Promise<string[]>}
417
+ */
418
+ export function path_crates(manifest) {
419
+ return new Promise((done) => {
420
+ execFile(
421
+ 'cargo',
422
+ ['metadata', '--format-version', '1', '--manifest-path', manifest],
423
+ { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 },
424
+ (error, stdout) => {
425
+ if (error) return done([dirname(manifest)]);
426
+ const metadata = JSON.parse(stdout);
427
+ done(
428
+ metadata.packages
429
+ .filter((/** @type {any} */ pkg) => pkg.source === null)
430
+ .map((/** @type {any} */ pkg) => dirname(pkg.manifest_path))
431
+ );
432
+ }
433
+ );
434
+ });
435
+ }
436
+
437
+ /**
438
+ * Watch `dirs` (told by the OS: FSEvents, inotify; nothing polls) and call
439
+ * `changed` once for every burst of changes, a burst being changes less than
440
+ * 100 ms apart. What is under a `target/` directory does not count.
441
+ * @param {string[]} dirs @param {(file: string) => void} changed
442
+ * @returns {() => void} stops watching
443
+ */
444
+ export function watch_crates(dirs, changed) {
445
+ /** @type {ReturnType<typeof setTimeout> | undefined} */
446
+ let timer;
447
+ const watchers = dirs.map((dir) =>
448
+ watch(dir, { recursive: true }, (_, file) => {
449
+ if (!file || String(file).split(/[\\/]/).includes('target')) return;
450
+ clearTimeout(timer);
451
+ timer = setTimeout(() => changed(join(dir, String(file))), 100);
452
+ })
453
+ );
454
+ return () => {
455
+ clearTimeout(timer);
456
+ for (const watcher of watchers) watcher.close();
457
+ };
458
+ }
459
+
460
+ /** When the binary was last written, to tell a rebuild that changed it from one that did not. @param {string} binary */
461
+ export function written(binary) {
462
+ try {
463
+ return statSync(binary).mtimeMs;
464
+ } catch {
465
+ return 0;
466
+ }
467
+ }
468
+
469
+ /**
470
+ * Check, build and hand over: everything `sepal run`, `screenshot` and
471
+ * `bundle` need before they start the host. Exits with the message when the
472
+ * app cannot be built. Sets `SEPAL_HOST` to the binary.
473
+ * @param {string} manifest @param {'dev' | 'dist'} profile
474
+ * @returns {Promise<string>} the binary
475
+ */
476
+ export async function build_or_exit(manifest, profile) {
477
+ const problem = tag_problem(manifest, VERSION) ?? toolchain_problem();
478
+ if (problem) {
479
+ console.error(problem);
480
+ process.exit(1);
481
+ }
482
+ announce(manifest, profile);
483
+ const started = Date.now();
484
+ const built = await build(manifest, profile);
485
+ if ('error' in built) {
486
+ console.error(`sepal: native/ did not build: ${built.error}`);
487
+ process.exit(1);
488
+ }
489
+ console.error(`sepal: native/ built in ${((Date.now() - started) / 1000).toFixed(1)} s`);
490
+ process.env.SEPAL_HOST = built.binary;
491
+ return built.binary;
492
+ }
493
+
494
+ /**
495
+ * The shared build directory for `native/`, made ready: its compiler's
496
+ * subdirectory, stamped as used now, with other compilers' unused ones
497
+ * removed. A `CARGO_BUILD_BUILD_DIR` the user set is theirs to manage.
498
+ * @param {string} manifest
499
+ */
500
+ function shared(manifest) {
501
+ const dir = build_dir(manifest);
502
+ mkdirSync(dir, { recursive: true });
503
+ writeFileSync(join(dir, STAMP), `${new Date().toISOString()}\n`);
504
+ const removed = prune(dirname(dir), basename(dir));
505
+ if (removed.length > 0) console.error(`sepal: removed builds no compiler here has used for ${KEEP_DAYS} days: ${removed.join(', ')}`);
506
+ return dir;
507
+ }
508
+
509
+ /** The line before a build, and what a first one costs. @param {string} manifest @param {'dev' | 'dist'} profile */
510
+ export function announce(manifest, profile) {
511
+ console.error(`sepal: building native/ (${profile} profile)`);
512
+ const dir = process.env.CARGO_BUILD_BUILD_DIR ?? build_dir(manifest);
513
+ if (first_build(dir)) {
514
+ console.error(
515
+ `sepal: the first build with this Rust compiler compiles Blitz, Stylo and wgpu, once per profile, and takes\n` +
516
+ `several minutes; later builds, of this app or another, take seconds. They share ${dir}.`
517
+ );
518
+ }
519
+ }
520
+
521
+ /**
522
+ * Write `native/` for the project at `root`. Refuses if it exists.
523
+ * @param {string} root @param {string} name the crate's name
524
+ * @returns {string[]} the files written
525
+ */
526
+ export function init(root, name) {
527
+ const native = join(root, 'native');
528
+ if (existsSync(native)) throw new Error('native/ exists already; init writes a new one only');
529
+ const files = init_files({ name, version: VERSION, native, crates: process.env.SEPAL_CRATES });
530
+ for (const [file, text] of Object.entries(files)) {
531
+ mkdirSync(dirname(join(root, file)), { recursive: true });
532
+ writeFileSync(join(root, file), text);
533
+ }
534
+ return Object.keys(files);
535
+ }