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/src/secrets.js ADDED
@@ -0,0 +1,42 @@
1
+ // The OS's keychain, under `permissions.secrets`: the login keychain on
2
+ // macOS; on Linux the Secret Service (GNOME Keyring, KWallet), or inside
3
+ // Flatpak the Secret portal. Kept under the app's id, which no call can
4
+ // name: through this API an app reads its own secrets only. What keeps
5
+ // other programs out is the OS's keychain: macOS asks the user before
6
+ // another program reads an item; on Linux, outside Flatpak, any program
7
+ // running as the user can read the items of an unlocked keyring. Dev keeps
8
+ // its secrets apart from the shipped app's (`<id>.dev`). For tokens and
9
+ // passwords; anything else belongs in `sepal/settings` or a file.
10
+
11
+ import { host_call } from './host-call.js';
12
+
13
+ /**
14
+ * A secret, or null when there is none under `key`. The OS may ask the user
15
+ * first: to unlock the keychain, or, on macOS, to let this build of the app
16
+ * read what another build of it stored.
17
+ * @param {string} key
18
+ * @returns {Promise<string | null>} rejects when there is no keychain, or the user refuses
19
+ */
20
+ export function getSecret(key) {
21
+ return host_call('secrets.get', { key });
22
+ }
23
+
24
+ /**
25
+ * Keep a secret under `key`, in place of what was there. A string, up to
26
+ * 64 KB.
27
+ * @param {string} key
28
+ * @param {string} value
29
+ * @returns {Promise<void>}
30
+ */
31
+ export function setSecret(key, value) {
32
+ return host_call('secrets.set', { key, value });
33
+ }
34
+
35
+ /**
36
+ * Forget a secret. Nothing under `key` is not an error.
37
+ * @param {string} key
38
+ * @returns {Promise<void>}
39
+ */
40
+ export function deleteSecret(key) {
41
+ return host_call('secrets.delete', { key });
42
+ }
@@ -0,0 +1,52 @@
1
+ // The app's settings: a store of JSON values by key, kept by the host in
2
+ // `settings.json` in the app's data directory. The page, the server code and
3
+ // the app's Rust share it, and each hears the others' changes. Needs
4
+ // `permissions.settings`. Two running instances of one app overwrite each
5
+ // other's settings.
6
+
7
+ import { host_call, listen } from './host-call.js';
8
+
9
+ /**
10
+ * A setting's value, or undefined when it is not set.
11
+ * @param {string} key
12
+ * @returns {Promise<any>}
13
+ */
14
+ export async function get(key) {
15
+ return (await host_call('settings.get', { key })).value;
16
+ }
17
+
18
+ /**
19
+ * Set a setting to anything JSON can carry, on disk before the promise
20
+ * settles. Undefined removes it, as JSON drops it.
21
+ * Every call is a flush to the disk (milliseconds): set on a choice made,
22
+ * not on every key press.
23
+ * @param {string} key
24
+ * @param {unknown} value
25
+ * @returns {Promise<void>} rejects past 1 MB of settings
26
+ */
27
+ export function set(key, value) {
28
+ if (value === undefined) return remove(key);
29
+ return host_call('settings.set', { key, value });
30
+ }
31
+
32
+ /** @param {string} key @returns {Promise<void>} */
33
+ export function remove(key) {
34
+ return host_call('settings.remove', { key });
35
+ }
36
+
37
+ /** Every setting. @returns {Promise<Record<string, any>>} */
38
+ export function all() {
39
+ return host_call('settings.all');
40
+ }
41
+
42
+ /**
43
+ * Hear the changes the rest of the app makes (the other runtime, or Rust),
44
+ * not this runtime's own, as the web's `storage` event. `value` is
45
+ * undefined for a removal. When changes came faster than the app took
46
+ * them and some were dropped, `key` is null: read them again with `all()`.
47
+ * @param {(key: string | null, value: any) => void} listener
48
+ * @returns {() => void} stops listening
49
+ */
50
+ export function onChange(listener) {
51
+ return listen('settings.change', (/** @type {any} */ change) => (change ? listener(change.key, change.value) : listener(null, undefined)));
52
+ }
package/src/shims.js CHANGED
@@ -8,6 +8,28 @@
8
8
  const g = /** @type {any} */ (globalThis);
9
9
  const host = g.__sb_host ?? {};
10
10
 
11
+ // The value that follows the code through promise jobs (`async-context.js`).
12
+ // Timers and frame callbacks come from the host, which does not track them:
13
+ // each takes the value of the code that scheduled it.
14
+ /** @type {() => unknown} */
15
+ const continuation = typeof host.continuation === 'function' ? () => host.continuation() : () => undefined;
16
+ /** @type {(value: unknown) => void} */
17
+ const set_continuation = typeof host.set_continuation === 'function' ? (value) => host.set_continuation(value) : () => {};
18
+
19
+ /**
20
+ * Call `fn` with the continuation value `value`, and restore the one before.
21
+ * @param {unknown} value @param {Function} fn @param {any[]} args
22
+ */
23
+ function run_with(value, fn, args) {
24
+ const before = continuation();
25
+ set_continuation(value);
26
+ try {
27
+ return fn(...args);
28
+ } finally {
29
+ set_continuation(before);
30
+ }
31
+ }
32
+
11
33
  const clock = () => (host.now ? host.now() : Date.now());
12
34
 
13
35
  /** @param {unknown} value */
@@ -89,8 +111,13 @@ if (typeof g.queueMicrotask !== 'function') {
89
111
  };
90
112
  }
91
113
 
92
- if (typeof g.performance === 'undefined') {
93
- g.performance = { now: clock };
114
+ // One clock for scripts, timers and frame timestamps: the host's, which
115
+ // stands still headless until a test moves it. QuickJS-ng has a `performance`
116
+ // of its own, on real time, whose `now` cannot be replaced; animation code
117
+ // compares a frame's timestamp with `performance.now()`, so the whole object
118
+ // is. Its `timeOrigin` stays.
119
+ if (typeof g.performance === 'undefined' || host.now) {
120
+ g.performance = { ...g.performance, now: clock };
94
121
  }
95
122
 
96
123
  // ---------------------------------------------------------------------------
@@ -101,11 +128,24 @@ if (typeof g.performance === 'undefined') {
101
128
  // timer is pending.
102
129
  // ---------------------------------------------------------------------------
103
130
 
104
- /** @typedef {{ fn: Function, args: any[], at: number, every: number }} Timer */
131
+ /** @typedef {{ fn: Function, args: any[], at: number, every: number, level: number, context: unknown }} Timer */
105
132
 
106
133
  /** @type {Map<number, Timer>} */
107
134
  const timers = new Map();
108
135
  let next_timer_id = 1;
136
+ /**
137
+ * HTML's timer nesting level: that of the timer whose callback, or whose
138
+ * microtasks, run now; 0 outside a timer.
139
+ */
140
+ let timer_level = 0;
141
+
142
+ /**
143
+ * As in HTML: from the sixth nested timer on, a timer waits at least 4 ms.
144
+ * A chain of `setTimeout(fn, 0)` then wakes the host about 250 times a
145
+ * second, not once per turn as fast as it can go.
146
+ * @param {number} delay
147
+ */
148
+ const clamped = (delay) => (timer_level > 5 ? Math.max(4, delay) : delay);
109
149
 
110
150
  /**
111
151
  * @param {unknown} fn
@@ -116,8 +156,8 @@ let next_timer_id = 1;
116
156
  function add_timer(fn, delay, every, args) {
117
157
  if (typeof fn !== 'function') return 0;
118
158
  const id = next_timer_id++;
119
- const at = clock() + Math.max(0, Number(delay) || 0);
120
- timers.set(id, { fn, args, at, every });
159
+ const at = clock() + clamped(Math.max(0, Number(delay) || 0));
160
+ timers.set(id, { fn, args, at, every, level: timer_level + 1, context: continuation() });
121
161
  return id;
122
162
  }
123
163
 
@@ -172,6 +212,7 @@ let round = null;
172
212
  * @returns {boolean}
173
213
  */
174
214
  export function run_timers() {
215
+ timer_level = 0;
175
216
  if (round === null) {
176
217
  if (timers.size === 0) return false;
177
218
  const now = clock();
@@ -190,10 +231,15 @@ export function run_timers() {
190
231
  }
191
232
  const [id, timer] = next;
192
233
  if (!timers.has(id)) continue; // cleared by an earlier callback
193
- if (timer.every > 0) timer.at = clock() + timer.every;
194
- else timers.delete(id);
234
+ // Until the next call: the microtasks the host runs in between belong to this timer.
235
+ timer_level = timer.level;
236
+ if (timer.every > 0) {
237
+ // Each run of an interval is nested in the one before.
238
+ timer.at = clock() + clamped(timer.every);
239
+ timer.level++;
240
+ } else timers.delete(id);
195
241
  try {
196
- timer.fn(...timer.args);
242
+ run_with(timer.context, timer.fn, timer.args);
197
243
  } catch (error) {
198
244
  g.console.error('Error in timer callback:', error);
199
245
  }
@@ -222,8 +268,62 @@ if (typeof g.setTimeout !== 'function') {
222
268
  g.clearInterval = g.clearTimeout;
223
269
  }
224
270
 
271
+ // ---------------------------------------------------------------------------
272
+ // Animation frames
273
+ //
274
+ // A `requestAnimationFrame` callback runs when the host draws its next frame,
275
+ // before it lays the page out and paints. The host asks `frame_pending()` at
276
+ // the end of every turn and draws a frame only when the answer is yes, so
277
+ // with no callback queued nothing is drawn and nothing wakes it.
278
+ // ---------------------------------------------------------------------------
279
+
280
+ /** Queued callbacks, in the order they were queued, with the continuation value of where. @type {Map<number, { fn: (time: number) => void, context: unknown }>} */
281
+ const frame_callbacks = new Map();
282
+ let next_frame_id = 1;
283
+ /** The callbacks that were queued when the host started this frame. @type {number[] | null} */
284
+ let frame = null;
285
+
286
+ /**
287
+ * Run one callback of this frame, and say whether there was one. As with
288
+ * timers, the host calls this until the answer is no, and runs microtasks
289
+ * after every call. Every callback of a frame gets the same `time`; one
290
+ * queued during the frame runs in the next.
291
+ *
292
+ * @param {number} time the frame's timestamp, on the host clock
293
+ * @returns {boolean}
294
+ */
295
+ export function run_frame(time) {
296
+ if (frame === null) {
297
+ if (frame_callbacks.size === 0) return false;
298
+ frame = [...frame_callbacks.keys()];
299
+ }
300
+ for (;;) {
301
+ const id = frame.shift();
302
+ if (id === undefined) {
303
+ frame = null;
304
+ return false;
305
+ }
306
+ const callback = frame_callbacks.get(id);
307
+ if (callback === undefined) continue; // cancelled by an earlier callback
308
+ frame_callbacks.delete(id);
309
+ try {
310
+ run_with(callback.context, callback.fn, [time]);
311
+ } catch (error) {
312
+ g.console.error('Error in requestAnimationFrame callback:', error);
313
+ }
314
+ return true;
315
+ }
316
+ }
317
+
318
+ /** Whether the app waits for a frame. The host asks at the end of every turn. */
319
+ export const frame_pending = () => frame_callbacks.size > 0;
320
+
225
321
  if (typeof g.requestAnimationFrame !== 'function') {
226
- // TODO: tie this to the host's redraw instead of a 16ms timer.
227
- g.requestAnimationFrame = (/** @type {(time: number) => void} */ fn) => g.setTimeout(() => fn(clock()), 16);
228
- g.cancelAnimationFrame = g.clearTimeout;
322
+ g.requestAnimationFrame = (/** @type {unknown} */ fn) => {
323
+ if (typeof fn !== 'function') throw new TypeError('requestAnimationFrame: the callback is not a function');
324
+ const id = next_frame_id++;
325
+ frame_callbacks.set(id, { fn: /** @type {(time: number) => void} */ (fn), context: continuation() });
326
+ return id;
327
+ };
328
+ g.cancelAnimationFrame = (/** @type {number} */ id) => void frame_callbacks.delete(id);
229
329
  }
package/src/stem.js ADDED
@@ -0,0 +1,125 @@
1
+ // The stem's runtime: what an app's server code runs on, on a thread and a
2
+ // JavaScript engine of its own (`crates/host/src/stem.rs`). The server code
3
+ // is a module, `_server/index.js`, that hands `serve()` its handler. Every
4
+ // request the page makes to the app's own origin that is not for a file
5
+ // reaches the handler as a `Request`; the `Response` it returns streams
6
+ // back to the page. `serve()` is experimental: what puts an app's code
7
+ // there is still open (HANDOVER.md, "The stem's API: open").
8
+ //
9
+ // The server code has what every app has (`web.js`: `fetch`, streams,
10
+ // `URL`, `FormData`, …), `console`, timers on the host's clock, and
11
+ // `node:async_hooks`, which the host provides (`async-context.js`). Not the
12
+ // DOM, and no other Node builtin. What it may do outside the app is what the
13
+ // app's manifest allows the page.
14
+
15
+ import { run_timers, next_timer, track_rejection, report_rejections } from './shims.js';
16
+ import { host_call, settle_call, deliver_event } from './host-call.js';
17
+ import { encode, decode, to_bytes } from './base64.js';
18
+ import { Request, Response } from './web.js';
19
+
20
+ /**
21
+ * What `serve()` takes: a function from a `Request` to its `Response` (or a
22
+ * promise of one), or an object with one as `fetch`, as servers on the web
23
+ * platform take them. Typed loosely: the app's code knows these classes by
24
+ * its own (DOM) types, and this package has none to name.
25
+ * @typedef {((request: any) => unknown) | { fetch(request: any): unknown }} Handler
26
+ */
27
+
28
+ /** @type {{ fetch(request: Request): unknown } | null} */
29
+ let handler = null;
30
+
31
+ /** The readers of the bodies being sent, by request id: the page can cancel one. */
32
+ const sending = new Map();
33
+
34
+ /**
35
+ * The stores the page shares with the stem, as of the last change the host
36
+ * passed on, for reading without asking. None is shared yet
37
+ * (`sessionStorage` is the page's alone); the order is what is in place:
38
+ * a request sees every change the page made before it.
39
+ * @type {Map<string, string>}
40
+ */
41
+ const stores = new Map();
42
+
43
+ // The host's entry points into the stem. It calls these and nothing else.
44
+ /** @type {any} */ (globalThis).__sb = {
45
+ timers: run_timers,
46
+ next_timer,
47
+ resolve: settle_call,
48
+ event: deliver_event,
49
+ rejection: track_rejection,
50
+ rejections: report_rejections,
51
+ /** A request, as JSON: `{ id, method, url, headers, body }`, the body in base64 or null. @param {string} json */
52
+ request: (json) => void respond(JSON.parse(json)),
53
+ /** The page stopped reading this response. @param {string} id */
54
+ cancel: (id) => void sending.get(Number(id))?.cancel().catch(() => {}),
55
+ /** The page changed a shared store: `[[key, value or null], …]`. @param {string} json */
56
+ storage: (json) => {
57
+ for (const [key, value] of JSON.parse(json)) {
58
+ if (value === null) stores.delete(key);
59
+ else stores.set(key, value);
60
+ }
61
+ },
62
+ stores
63
+ };
64
+
65
+ /**
66
+ * Answer the page's requests to the app's origin with `next`. Call it once,
67
+ * from the server code's entry module; a later call replaces the handler.
68
+ * A request that arrives before it is answered with a 500.
69
+ *
70
+ * Experimental: what puts an app's code on the stem is not decided yet
71
+ * (SvelteKit's own server, or functions of Sepal's own), and this may
72
+ * change shape with it.
73
+ * @experimental
74
+ * @param {Handler} next
75
+ */
76
+ export function serve(next) {
77
+ handler = typeof next === 'function' ? { fetch: next } : next;
78
+ }
79
+
80
+ /**
81
+ * @param {{ id: number, method: string, url: string, headers: [string, string][], body: string | null }} request
82
+ */
83
+ async function respond({ id, method, url, headers, body }) {
84
+ /** @type {Response} */
85
+ let response;
86
+ try {
87
+ if (handler === null) throw new Error('the server code has not called serve()');
88
+ const request = new Request(url, { method, headers, body: body === null ? null : decode(body) });
89
+ const answer = await handler.fetch(request);
90
+ if (!(answer instanceof Response)) throw new TypeError(`the handler answered with ${answer}, not a Response`);
91
+ response = answer;
92
+ } catch (error) {
93
+ // As a server would: the page gets a 500, the details go to the log.
94
+ /** @type {any} */ (globalThis).console.error(`[stem] ${method} ${url}:`, error);
95
+ response = new Response('Internal Error', { status: 500 });
96
+ }
97
+ const head = { id, status: response.status, status_text: response.statusText, headers: [...response.headers] };
98
+ try {
99
+ await host_call('stem.head', head);
100
+ } catch {
101
+ // The page is no longer waiting.
102
+ await response.body?.cancel().catch(() => {});
103
+ return;
104
+ }
105
+ if (method === 'HEAD' || response.body === null) {
106
+ await host_call('stem.end', { id });
107
+ return;
108
+ }
109
+ const reader = response.body.getReader();
110
+ sending.set(id, reader);
111
+ try {
112
+ for (;;) {
113
+ const { value, done } = await reader.read();
114
+ if (done) break;
115
+ // One answer at a time: the next chunk is read once the host has this one.
116
+ if (value.byteLength > 0) await host_call('stem.chunk', { id, chunk: encode(to_bytes(value)) });
117
+ }
118
+ await host_call('stem.end', { id });
119
+ } catch (error) {
120
+ await reader.cancel(error).catch(() => {});
121
+ await host_call('stem.fail', { id, message: String(/** @type {any} */ (error)?.message ?? error) }).catch(() => {});
122
+ } finally {
123
+ sending.delete(id);
124
+ }
125
+ }
package/src/updater.js CHANGED
@@ -27,8 +27,9 @@ import { host_call } from './host-call.js';
27
27
  *
28
28
  * `download()` fetches the update and verifies its signature; nothing on disk
29
29
  * changes. `install()` downloads if that has not happened yet, replaces the
30
- * app and relaunches it, so on success its promise never settles. It rejects
31
- * when the app is not running from a bundle (in dev, for instance).
30
+ * app and ends it; the new version starts once it has ended. Code after a
31
+ * successful `install()` may not run. It rejects when the app is not running
32
+ * from a bundle (in dev, for instance).
32
33
  */
33
34
 
34
35
  /**
package/src/url.js CHANGED
@@ -7,6 +7,8 @@
7
7
  // of what was already there. A URL without `//` (`mailto:a@b`, `a:`) keeps what
8
8
  // follows the scheme as its path, untouched. `test/url.test.js` compares it with Node's own.
9
9
 
10
+ import { lru } from './lru.js';
11
+
10
12
  const ABSOLUTE = /^([a-zA-Z][a-zA-Z0-9+.-]*):\/\/([^/?#]*)([^?#]*)(\?[^#]*)?(#.*)?$/;
11
13
  /** Schemes whose URLs always have a host and a path, and an origin to speak of. */
12
14
  const SPECIAL = /^(https?|wss?|ftp):$/;
@@ -87,10 +89,10 @@ function parse(input, base) {
87
89
  return { protocol, username: '', password: '', hostname: '', port: '', pathname: opaque[2], search: clean(opaque[3], QUERY_UNSAFE), hash: clean(opaque[4], HASH_UNSAFE), opaque: true };
88
90
  }
89
91
  if (base === undefined) return null;
90
- if (no_authority.has(base)) {
92
+ if (no_authority(base)) {
91
93
  // Nothing resolves against such a URL except a hash.
92
94
  if (!input.startsWith('#')) return null;
93
- return { protocol: base.protocol, username: '', password: '', hostname: '', port: '', pathname: base.pathname, search: raw.get(base)?.search ?? '', hash: clean(input, HASH_UNSAFE), opaque: true };
95
+ return { protocol: base.protocol, username: '', password: '', hostname: '', port: '', pathname: base.pathname, search: raw_search(base), hash: clean(input, HASH_UNSAFE), opaque: true };
94
96
  }
95
97
  // Relative to the base: `//host/path`, `/path`, `path`, `?query`, `#hash`, or nothing.
96
98
  if (input.startsWith('//')) return parse(base.protocol + input, undefined);
@@ -102,7 +104,7 @@ function parse(input, base) {
102
104
  return {
103
105
  ...parts,
104
106
  pathname: base.pathname,
105
- search: search === undefined ? raw.get(base)?.search ?? base.search : clean(search, QUERY_UNSAFE),
107
+ search: search === undefined ? raw_search(base) : clean(search, QUERY_UNSAFE),
106
108
  hash: clean(hash, HASH_UNSAFE)
107
109
  };
108
110
  }
@@ -125,11 +127,41 @@ function clean(part, unsafe) {
125
127
  return part === undefined ? '' : encode(part, unsafe);
126
128
  }
127
129
 
130
+ /**
131
+ * What `parse` made of an input and a base, by both. Routers and Vite's
132
+ * preload helper parse the same few URLs on every navigation; each `new URL`
133
+ * still gets its own object, copied from the cached parts, which nothing
134
+ * writes to. A base `URL` is keyed by its `href` (and whether it has an
135
+ * authority), which is everything `parse` reads from it. SvelteKit's look
136
+ * at a page's links after a navigation parses two per link (the Tracker's
137
+ * Board has 316): the limit leaves room for a few such pages.
138
+ * @type {ReturnType<typeof lru<string, ReturnType<typeof parse>>>}
139
+ */
140
+ const parsed = lru('urls', 2048);
141
+
142
+ /** @param {string} input @param {string | URL | undefined} base */
143
+ function parse_cached(input, base) {
144
+ const base_key = base === undefined ? '' : base instanceof URL ? (no_authority(base) ? 'o' : 'u') + base.href : 's' + String(base);
145
+ // The base's length first, so that no input can make two pairs one key.
146
+ const key = `${base_key.length}:${base_key}${input}`;
147
+ let parts = parsed.get(key);
148
+ if (parts === undefined) {
149
+ const against = base === undefined ? undefined : base instanceof URL ? base : new URL(String(base));
150
+ parts = parse(input, against);
151
+ parsed.set(key, parts);
152
+ }
153
+ return parts;
154
+ }
155
+
156
+ /** The query of a URL as written, lone `?` included, for resolving against it. Set by the class. @type {(url: URL) => string} */
157
+ let raw_search;
158
+ /** Whether a URL is of the `scheme:path` kind. Set by the class. @type {(url: URL) => boolean} */
159
+ let no_authority;
160
+
128
161
  export class URL {
129
162
  /** @param {string | URL} input @param {string | URL} [base] */
130
163
  constructor(input, base) {
131
- const against = base === undefined ? undefined : base instanceof URL ? base : new URL(String(base));
132
- const parts = parse(String(input), against);
164
+ const parts = parse_cached(String(input), base);
133
165
  if (parts === null) throw new TypeError(`Invalid URL: ${String(input)}`);
134
166
  this.protocol = parts.protocol;
135
167
  this.username = parts.username;
@@ -139,20 +171,39 @@ export class URL {
139
171
  this.pathname = parts.pathname;
140
172
  this.#search = parts.search;
141
173
  this.#hash = parts.hash;
142
- raw.set(this, { search: parts.search });
143
- if (parts.opaque) no_authority.add(this);
144
- this.searchParams = new URLSearchParams(this.#search);
145
- link.set(this.searchParams, (/** @type {string} */ query) => this.#set_search(query === '' ? '' : '?' + query));
174
+ this.#opaque = parts.opaque === true;
146
175
  }
147
176
 
148
- // With their `?` and `#`, which may be all there is.
177
+ // With their `?` and `#`, which may be all there is: what a URL resolved
178
+ // against this one keeps, lone `?` included.
149
179
  #search = '';
150
180
  #hash = '';
181
+ /** A `scheme:path` URL, with no host to print or to resolve against. */
182
+ #opaque = false;
183
+ /**
184
+ * Made when it is first asked for. Routers and Vite's preload helper
185
+ * make URLs for their parts, many a navigation (SvelteKit: one per link
186
+ * on the page), and a `URLSearchParams` each was a third of that.
187
+ * @type {URLSearchParams | null}
188
+ */
189
+ #params = null;
190
+
191
+ static {
192
+ raw_search = (url) => url.#search;
193
+ no_authority = (url) => url.#opaque;
194
+ }
195
+
196
+ get searchParams() {
197
+ if (this.#params === null) {
198
+ this.#params = new URLSearchParams(this.#search);
199
+ link.set(this.#params, (/** @type {string} */ query) => this.#set_search(query === '' ? '' : '?' + query));
200
+ }
201
+ return this.#params;
202
+ }
151
203
 
152
204
  /** @param {string} search */
153
205
  #set_search(search) {
154
206
  this.#search = search;
155
- raw.set(this, { search });
156
207
  }
157
208
 
158
209
  get search() {
@@ -161,7 +212,7 @@ export class URL {
161
212
  set search(value) {
162
213
  value = String(value);
163
214
  this.#set_search(value === '' ? '' : clean(value.startsWith('?') ? value : '?' + value, QUERY_UNSAFE));
164
- reset.get(this.searchParams)?.(this.#search);
215
+ if (this.#params !== null) reset.get(this.#params)?.(this.#search);
165
216
  }
166
217
  get hash() {
167
218
  return this.#hash === '#' ? '' : this.#hash;
@@ -180,7 +231,7 @@ export class URL {
180
231
  return SPECIAL.test(this.protocol) ? `${this.protocol}//${this.host}` : 'null';
181
232
  }
182
233
  get href() {
183
- if (no_authority.has(this)) return `${this.protocol}${this.pathname}${this.#search}${this.#hash}`;
234
+ if (this.#opaque) return `${this.protocol}${this.pathname}${this.#search}${this.#hash}`;
184
235
  const user = this.username === '' ? '' : this.username + (this.password === '' ? '' : ':' + this.password) + '@';
185
236
  return `${this.protocol}//${user}${this.host}${this.pathname}${this.#search}${this.#hash}`;
186
237
  }
@@ -188,8 +239,7 @@ export class URL {
188
239
  const parts = parse(String(value), undefined);
189
240
  if (parts === null) throw new TypeError(`Invalid URL: ${String(value)}`);
190
241
  const { search, hash, opaque, ...rest } = parts;
191
- if (opaque) no_authority.add(this);
192
- else no_authority.delete(this);
242
+ this.#opaque = opaque === true;
193
243
  Object.assign(this, rest);
194
244
  this.search = search;
195
245
  this.#hash = hash;
@@ -220,11 +270,6 @@ export class URL {
220
270
  }
221
271
  }
222
272
 
223
- /** URLs of the `scheme:path` kind, which have no host to print or to resolve against. @type {WeakSet<URL>} */
224
- const no_authority = new WeakSet();
225
-
226
- /** The query of a URL as written, lone `?` included, for resolving against it. @type {WeakMap<URL, { search: string }>} */
227
- const raw = new WeakMap();
228
273
 
229
274
  /** How a `searchParams` tells its URL that it changed, and the other way round. */
230
275
  /** @type {WeakMap<URLSearchParams, (query: string) => void>} */
package/src/web.js ADDED
@@ -0,0 +1,86 @@
1
+ // The web platform's classes that are not ECMAScript, for both runtimes (the
2
+ // UI's, with or without the DOM layer, and the backend's): installed as
3
+ // globals when the engine has none.
4
+ //
5
+ // URL, URLSearchParams url.js
6
+ // TextEncoder, TextDecoder text.js
7
+ // AbortController, AbortSignal abort.js
8
+ // fetch, Headers, Request, Response fetch.js
9
+ // ReadableStream, WritableStream, web-streams-polyfill (MIT)
10
+ // TransformStream and the
11
+ // queuing strategies
12
+ // Blob, File, FormData formdata-node (MIT)
13
+ // btoa, atob base64.js (V8 has neither; QuickJS-ng both)
14
+ //
15
+ // `Event` and `EventTarget` are not here: the DOM layer has its own, which
16
+ // know about the renderer's events.
17
+
18
+ import { Blob, File, FormData } from 'formdata-node';
19
+ import { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableStream, TransformStream, WritableStream } from 'web-streams-polyfill';
20
+ import { AbortController, AbortSignal, abort_error } from './abort.js';
21
+ import { decode, encode } from './base64.js';
22
+ import { fetch, Headers, Request, Response } from './fetch.js';
23
+ import { TextDecoder, TextEncoder } from './text.js';
24
+ import { URL, URLSearchParams } from './url.js';
25
+
26
+ const classes = {
27
+ URL,
28
+ URLSearchParams,
29
+ TextEncoder,
30
+ TextDecoder,
31
+ AbortController,
32
+ AbortSignal,
33
+ fetch,
34
+ Headers,
35
+ Request,
36
+ Response,
37
+ ReadableStream,
38
+ WritableStream,
39
+ TransformStream,
40
+ ByteLengthQueuingStrategy,
41
+ CountQueuingStrategy,
42
+ Blob,
43
+ File,
44
+ FormData
45
+ };
46
+ for (const [name, value] of Object.entries(classes)) {
47
+ if (typeof (/** @type {any} */ (globalThis)[name]) !== 'function') /** @type {any} */ (globalThis)[name] = value;
48
+ }
49
+
50
+ // QuickJS-ng has `btoa` and `atob`; a bare V8 isolate has neither, and
51
+ // libraries take them for granted (SvelteKit encodes remote functions'
52
+ // arguments with them).
53
+ if (typeof (/** @type {any} */ (globalThis).btoa) !== 'function') {
54
+ /** @type {any} */ (globalThis).btoa = (/** @type {string} */ text) => {
55
+ text = String(text);
56
+ const bytes = new Uint8Array(text.length);
57
+ for (let i = 0; i < text.length; i++) {
58
+ const code = text.charCodeAt(i);
59
+ if (code > 255) throw abort_error('btoa: the string has characters outside Latin-1', 'InvalidCharacterError');
60
+ bytes[i] = code;
61
+ }
62
+ return encode(bytes);
63
+ };
64
+ }
65
+ if (typeof (/** @type {any} */ (globalThis).atob) !== 'function') {
66
+ /** @type {any} */ (globalThis).atob = (/** @type {string} */ text) => {
67
+ const bytes = decode(String(text).replace(/[\t\n\f\r ]/g, ''));
68
+ let out = '';
69
+ for (let i = 0; i < bytes.length; i += 8192) out += String.fromCharCode(...bytes.subarray(i, i + 8192));
70
+ return out;
71
+ };
72
+ }
73
+
74
+ // `navigator`, as a web worker's (and Node's) has it: every app's, page and
75
+ // stem alike, with the user's locales and the system's `platform`
76
+ // (`MacIntel`, `Linux x86_64`, `Win32`: libraries choose between Cmd and
77
+ // Ctrl by it), which the host hands each runtime before its first script.
78
+ if (/** @type {any} */ (globalThis).navigator === undefined) {
79
+ const host = /** @type {any} */ (globalThis).__sb_host;
80
+ /** @type {string[]} */
81
+ const locales = host?.locales ?? [];
82
+ const languages = Object.freeze(locales.length > 0 ? [...locales] : ['en-US']);
83
+ /** @type {any} */ (globalThis).navigator = { userAgent: 'sepal', platform: host?.platform ?? '', language: languages[0], languages, maxTouchPoints: 0, onLine: true };
84
+ }
85
+
86
+ export { URL, URLSearchParams, TextEncoder, TextDecoder, AbortController, AbortSignal, fetch, Headers, Request, Response, ReadableStream, WritableStream, TransformStream, Blob, File, FormData };
package/src/window.js CHANGED
@@ -1,11 +1,15 @@
1
- // The app's window. Needs `permissions.window`.
1
+ // The app's window. Everything but the title needs `permissions.window`.
2
2
  //
3
3
  // Title, size and icon at startup come from the app config; these change the
4
4
  // window while the app runs.
5
5
 
6
6
  import { host_call } from './host-call.js';
7
7
 
8
- /** @param {string} title @returns {Promise<void>} */
8
+ /**
9
+ * Set the window's title. Needs no permission: the title is the app's own,
10
+ * as a page's is on the web (`document.title` does the same).
11
+ * @param {string} title @returns {Promise<void>}
12
+ */
9
13
  export function setTitle(title) {
10
14
  return host_call('window.set_title', { title });
11
15
  }