sepal 0.1.0-alpha.2 → 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 (81) hide show
  1. package/README.md +16 -9
  2. package/cli.js +127 -10
  3. package/package.json +48 -21
  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 +14 -12
  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 +111 -11
  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 +13 -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 -34
  53. package/types/vite/vite.d.ts +86 -53
  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 -224
  65. package/vite/vite.js +377 -147
  66. package/ambient.d.ts +0 -20
  67. package/types/vite/navigation.d.ts +0 -1
  68. package/types/vite/router-entry.d.ts +0 -1
  69. package/types/vite/router.d.ts +0 -21
  70. package/types/vite/routes.d.ts +0 -41
  71. package/types/vite/routing.svelte.d.ts +0 -131
  72. package/types/vite/state.d.ts +0 -1
  73. package/vite/Router.svelte +0 -32
  74. package/vite/RouterError.svelte +0 -11
  75. package/vite/navigation.js +0 -3
  76. package/vite/router-entry.js +0 -12
  77. package/vite/router.js +0 -17
  78. package/vite/routes.js +0 -219
  79. package/vite/routing.svelte.js +0 -378
  80. package/vite/state.js +0 -2
  81. package/vite/virtual.d.ts +0 -9
package/vite/app.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // What every way of building an app shares, whichever router it uses: reading
2
- // `sepal.config.ts`, writing the manifest the host reads (`app.json`), and
3
- // opening the app in dev and reloading it after each rebuild.
2
+ // `sepal.config.ts`, writing the manifest the host reads (`app.json`),
3
+ // compiling the modules to bytecode, and opening the app in dev and
4
+ // reloading it after each rebuild.
4
5
  //
5
6
  // Runs in Node.
6
7
 
@@ -13,6 +14,16 @@ import { find_host } from '@ethercorps/calyx';
13
14
 
14
15
  const CONFIG_FILES = ['sepal.config.ts', 'sepal.config.js', 'sepal.config.mjs'];
15
16
 
17
+ /**
18
+ * What `sepal()` tells the SvelteKit adapter (`sepal/adapter`), which runs
19
+ * inside SvelteKit's build and has no other way to reach it: the project,
20
+ * the settings from `sepal.config.ts`, and what to do once the app is
21
+ * written to a directory (open or reload the dev window). `null` until
22
+ * `sepal()` has run.
23
+ * @type {{ session: { root: string, options: import('./vite.js').Config, written: (out_dir: string) => void } | null }}
24
+ */
25
+ export const kit = { session: null };
26
+
16
27
  /**
17
28
  * Read the project's config file, if it has one.
18
29
  * @param {string} project
@@ -38,7 +49,7 @@ export const SEPAL_ICON = fileURLToPath(new URL('./icon.png', import.meta.url));
38
49
  * @param {import('./vite.js').Config} options
39
50
  * @param {string} root the project
40
51
  * @param {string} static_dir where the icon is looked for; empty when there is none
41
- * @returns {{ json: string, icon: string | null } | null}
52
+ * @returns {{ json: string, icon: string | null, warnings: string[] } | null}
42
53
  */
43
54
  export function manifest(options, root, static_dir) {
44
55
  if (!options.app && !options.permissions) return null;
@@ -65,42 +76,72 @@ export function manifest(options, root, static_dir) {
65
76
  }
66
77
  }
67
78
  const json = JSON.stringify(options.permissions ? { ...app, permissions: options.permissions } : app, null, '\t') + '\n';
68
- return { json, icon };
79
+ return { json, icon, warnings: process_warnings(options.permissions) };
80
+ }
81
+
82
+ /**
83
+ * Programs that run whatever they are given (`SHELLS` in
84
+ * crates/host/src/api/process.rs).
85
+ */
86
+ const SHELLS = ['sh', 'bash', 'zsh', 'fish', 'dash', 'ksh', 'csh', 'tcsh', 'osascript', 'powershell', 'pwsh', 'cmd', 'env', 'xargs', 'python', 'perl', 'ruby', 'node', 'bun', 'deno', 'npx'];
87
+
88
+ /**
89
+ * What to say about `permissions.process` when it allows running anything:
90
+ * `true`, or a list that names a shell or a script runner. A warning, not
91
+ * an error: some apps are for exactly that.
92
+ * @param {{ process?: unknown } | undefined} permissions
93
+ * @returns {string[]}
94
+ */
95
+ export function process_warnings(permissions) {
96
+ const allowed = permissions?.process;
97
+ if (allowed === true) return ['permissions.process is true: the app can run any program. List the programs it needs instead'];
98
+ if (!Array.isArray(allowed)) return [];
99
+ return allowed.flatMap((entry) => {
100
+ // Without its folder and version: `/usr/bin/python3.12` is `python`.
101
+ const name = String(entry).split('/').pop()?.replace(/[\d.]+$/, '') ?? '';
102
+ return SHELLS.includes(name) ? [`permissions.process lists \`${entry}\`: ${name} runs whatever it is given, so the app can run any program`] : [];
103
+ });
104
+ }
105
+
106
+ /**
107
+ * The flags for dev's throwaway bundle: `--dev`, which leaves the page out
108
+ * of it and signs it for this Mac, with the app's identity when
109
+ * `SEPAL_SIGN` names one. Its signature is then the same from one build
110
+ * of the app to the next, and so is the program the keychain and the
111
+ * notification settings know.
112
+ */
113
+ export function dev_bundle_flags() {
114
+ return process.env.SEPAL_SIGN ? ['--dev', '--sign', process.env.SEPAL_SIGN] : ['--dev'];
69
115
  }
70
116
 
71
117
  /**
72
118
  * The app's window in dev. The first call opens it; every later one reloads
73
119
  * it in place. Returns a function to call after each successful build.
120
+ *
121
+ * An app with `native/` runs its own host: built first (the window opens
122
+ * when it is), built again on every change to it or to a crate it has by
123
+ * path, and restarted when that changes the binary. A build that fails keeps
124
+ * the last good host running; one that never succeeded opens nothing. Both
125
+ * keep dev going until the next change.
74
126
  * @param {() => { root: string, out_dir: string, name: string | undefined }} project read at the first call
75
127
  */
76
128
  export function dev_window(project) {
77
129
  /** @type {import('node:child_process').ChildProcess | null} */
78
130
  let host = null;
79
131
  let gave_up = false;
132
+ /** The app's own host, once there is one; `undefined` until the first call looks. @type {Promise<void> | null | undefined} */
133
+ let native;
134
+ /** The binary to start once the running host has quit, for a restart. @type {string | null} */
135
+ let next = null;
80
136
 
81
- return () => {
82
- if (gave_up) return;
83
- if (host !== null) {
84
- // The host reloads on every line it reads.
85
- host.stdin?.write('reload\n');
86
- return;
87
- }
88
-
89
- let bin;
90
- try {
91
- bin = find_host().path;
92
- } catch (error) {
93
- console.warn(`sepal: the app will not open: ${/** @type {Error} */ (error).message}`);
94
- gave_up = true;
95
- return;
96
- }
137
+ /** Start the host on `bin`, out of a throwaway bundle on macOS. @param {string} bin */
138
+ const open = (bin) => {
97
139
  const { root, out_dir, name } = project();
98
-
99
140
  // macOS takes an app's name and Dock icon from the bundle it runs
100
141
  // from, so in dev the host runs out of a throwaway one. It still
101
142
  // loads the app from the build directory, not from the copy inside the bundle.
102
143
  if (process.platform === 'darwin' && name) {
103
- const made = spawnSync(bin, ['--bundle', out_dir, resolve(root, 'node_modules/.sepal')], {
144
+ const made = spawnSync(bin, ['--bundle', out_dir, resolve(root, 'node_modules/.sepal'), ...dev_bundle_flags()], {
104
145
  encoding: 'utf8'
105
146
  });
106
147
  if (made.status === 0) {
@@ -112,13 +153,140 @@ export function dev_window(project) {
112
153
  }
113
154
 
114
155
  const started = bin;
115
- host = spawn(started, ['--watch', out_dir], { stdio: ['pipe', 'inherit', 'inherit'] });
116
- host.on('error', (error) => {
156
+ const child = spawn(started, ['--watch', out_dir], { stdio: ['pipe', 'inherit', 'inherit'] });
157
+ host = child;
158
+ child.on('error', (error) => {
117
159
  console.error(`sepal: cannot start ${started}: ${error.message}`);
118
160
  process.exit(1);
119
161
  });
120
- // Closing the window ends the session. The other direction needs no
121
- // code: when the build tool exits, the host's stdin closes and it quits.
122
- host.on('exit', (code) => process.exit(code ?? 0));
162
+ // Closing the window ends the session, unless it closed for a new
163
+ // host. The other direction needs no code: when the build tool exits,
164
+ // the host's stdin closes and it quits.
165
+ child.on('exit', (code) => {
166
+ if (next === null) process.exit(code ?? 0);
167
+ const binary = next;
168
+ next = null;
169
+ open(binary);
170
+ });
123
171
  };
172
+
173
+ /** Build native/ and keep it built, opening and restarting the window. @param {string} manifest */
174
+ const own_host = async (manifest) => {
175
+ const { announce, build, path_crates, tag_problem, toolchain_problem, watch_crates, written, VERSION } =
176
+ await import('./native.js');
177
+ const problem = tag_problem(manifest, VERSION) ?? toolchain_problem();
178
+ if (problem) {
179
+ console.error(problem);
180
+ process.exit(1);
181
+ }
182
+ let built_at = 0;
183
+ const run = async () => {
184
+ announce(manifest, 'dev');
185
+ const started = Date.now();
186
+ const built = await build(manifest, 'dev');
187
+ if ('error' in built) {
188
+ console.error(
189
+ `sepal: native/ did not build (${built.error}); ${host ? 'the window stays on the last host that did' : 'the app opens once it does'}. Save again to retry.`
190
+ );
191
+ return;
192
+ }
193
+ console.error(`sepal: native/ built in ${((Date.now() - started) / 1000).toFixed(1)} s`);
194
+ process.env.SEPAL_HOST = built.binary;
195
+ const at = written(built.binary);
196
+ if (host === null) open(built.binary);
197
+ else if (at !== built_at) {
198
+ // A new binary: the page starts over on it.
199
+ next = built.binary;
200
+ host.stdin?.end();
201
+ }
202
+ built_at = at;
203
+ };
204
+ // One build at a time; a change during one builds again after it.
205
+ let building = Promise.resolve();
206
+ let again = false;
207
+ const rebuild = () => {
208
+ if (again) return;
209
+ again = true;
210
+ building = building
211
+ .then(() => {
212
+ again = false;
213
+ return run();
214
+ })
215
+ .catch((error) => console.error(`sepal: building native/ failed: ${error.message ?? error}`));
216
+ };
217
+ let stop = () => {};
218
+ const watch_all = async () => {
219
+ stop();
220
+ stop = watch_crates(await path_crates(manifest), (file) => {
221
+ // The crates by path may have changed with a manifest.
222
+ if (file.endsWith('Cargo.toml')) void watch_all();
223
+ rebuild();
224
+ });
225
+ };
226
+ await watch_all();
227
+ rebuild();
228
+ await building;
229
+ };
230
+
231
+ return () => {
232
+ if (gave_up) return;
233
+ if (host !== null) {
234
+ // The host reloads on every line it reads.
235
+ host.stdin?.write('reload\n');
236
+ return;
237
+ }
238
+ if (native === undefined) {
239
+ // SEPAL_HOST, when set, is the host to run, whatever native/ has.
240
+ const { root } = project();
241
+ const manifest = process.env.SEPAL_HOST ? null : join(root, 'native', 'Cargo.toml');
242
+ native = manifest && existsSync(manifest) ? own_host(manifest) : null;
243
+ }
244
+ // The window opens once the app's own host is built, on the build
245
+ // that is newest then.
246
+ if (native !== null) return;
247
+
248
+ let bin;
249
+ try {
250
+ bin = find_host().path;
251
+ } catch (error) {
252
+ console.warn(`sepal: the app will not open: ${/** @type {Error} */ (error).message}`);
253
+ gave_up = true;
254
+ return;
255
+ }
256
+ open(bin);
257
+ };
258
+ }
259
+
260
+ /**
261
+ * Compile the app's modules to bytecode with this machine's calyx (`calyx
262
+ * --compile`), which writes `x.js.qbc` next to each `x.js`: the host then
263
+ * loads them without parsing them. The app folder is a new build, so every
264
+ * module is compiled. Without a calyx that can, the app loads its
265
+ * JavaScript, as it always could: the build says so, and goes on.
266
+ * @param {string} dir the app folder
267
+ * @param {(message: string) => void} warn
268
+ * @returns {string | null} calyx's summary, or null when nothing was compiled
269
+ */
270
+ export function compile_bytecode(dir, warn) {
271
+ let bin;
272
+ try {
273
+ bin = find_host().path;
274
+ } catch (error) {
275
+ warn(`sepal: the app's modules were not compiled to bytecode, so it loads their JavaScript: ${/** @type {Error} */ (error).message}`);
276
+ return null;
277
+ }
278
+ const done = spawnSync(bin, ['--compile', dir], { encoding: 'utf8' });
279
+ if (done.error || done.status !== 0) {
280
+ // A calyx from before --compile takes it for the app folder.
281
+ if (done.stderr?.includes('--compile is not an app folder')) {
282
+ warn(`sepal: ${bin} is a calyx from before \`--compile\`, so the app's modules were not compiled to bytecode and it loads their JavaScript. A current calyx compiles them.`);
283
+ return null;
284
+ }
285
+ const why = done.error?.message ?? done.stderr.trim();
286
+ warn(`sepal: compiling the app's modules to bytecode failed, so it loads their JavaScript: ${why}`);
287
+ return null;
288
+ }
289
+ // Modules that stayed JavaScript, one line each.
290
+ for (const line of done.stderr.split('\n').filter(Boolean)) warn(`sepal: ${line}`);
291
+ return done.stdout.trim() || null;
124
292
  }
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
+ }