@adecore/shell 0.17.0-beta.1 → 0.17.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,13 +1,102 @@
1
- MIT License
1
+ # Functional Source License, Version 1.1, MIT Future License
2
2
 
3
- Copyright (c) 2026 Bas Milius
3
+ ## Abbreviation
4
4
 
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
5
+ FSL-1.1-MIT
6
+
7
+ ## Notice
8
+
9
+ Copyright 2026 - present Bas Milius
10
+
11
+ ## Terms and Conditions
12
+
13
+ ### Licensor ("We")
14
+
15
+ The party offering the Software under these Terms and Conditions.
16
+
17
+ ### The Software
18
+
19
+ The "Software" is each version of the software that we make available under
20
+ these Terms and Conditions, as indicated by our inclusion of these Terms and
21
+ Conditions with the Software.
22
+
23
+ ### License Grant
24
+
25
+ Subject to your compliance with this License Grant and the Patents,
26
+ Redistribution and Trademark clauses below, we hereby grant you the right to
27
+ use, copy, modify, create derivative works, publicly perform, publicly display
28
+ and redistribute the Software for any Permitted Purpose identified below.
29
+
30
+ ### Permitted Purpose
31
+
32
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
33
+ means making the Software available to others in a commercial product or
34
+ service that:
35
+
36
+ 1. substitutes for the Software;
37
+
38
+ 2. substitutes for any other product or service we offer using the Software
39
+ that exists as of the date we make the Software available; or
40
+
41
+ 3. offers the same or substantially similar functionality as the Software.
42
+
43
+ Permitted Purposes specifically include using the Software:
44
+
45
+ 1. for your internal use and access;
46
+
47
+ 2. for non-commercial education;
48
+
49
+ 3. for non-commercial research; and
50
+
51
+ 4. in connection with professional services that you provide to a licensee
52
+ using the Software in accordance with these Terms and Conditions.
53
+
54
+ ### Patents
55
+
56
+ To the extent your use for a Permitted Purpose would necessarily infringe our
57
+ patents, the license grant above includes a license under our patents. If you
58
+ make a claim against any party that the Software infringes or contributes to
59
+ the infringement of any patent, then your patent license to the Software ends
60
+ immediately.
61
+
62
+ ### Redistribution
63
+
64
+ The Terms and Conditions apply to all copies, modifications and derivatives of
65
+ the Software.
66
+
67
+ If you redistribute any copies, modifications or derivatives of the Software,
68
+ you must include a copy of or a link to these Terms and Conditions and not
69
+ remove any copyright notices provided in or with the Software.
70
+
71
+ ### Disclaimer
72
+
73
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
74
+ IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
75
+ PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
76
+
77
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
78
+ SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
79
+ EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
80
+
81
+ ### Trademarks
82
+
83
+ Except for displaying the License Details and identifying us as the origin of
84
+ the Software, you have no right under these Terms and Conditions to use our
85
+ trademarks, trade names, service marks or product names.
86
+
87
+ ## Grant of Future License
88
+
89
+ We hereby irrevocably grant you an additional license to use the Software under
90
+ the MIT license that is effective on the second anniversary of the date we make
91
+ the Software available. On or after that date, you may use the Software under
92
+ the MIT license, in which case the following will apply:
93
+
94
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
95
+ this software and associated documentation files (the "Software"), to deal in
96
+ the Software without restriction, including without limitation the rights to
97
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
98
+ of the Software, and to permit persons to whom the Software is furnished to do
99
+ so, subject to the following conditions:
11
100
 
12
101
  The above copyright notice and this permission notice shall be included in all
13
102
  copies or substantial portions of the Software.
package/README.md CHANGED
@@ -23,7 +23,7 @@ The package registers no IPC handler and listens to no app-wide Electron event.
23
23
 
24
24
  | Import | What it holds |
25
25
  |---|---|
26
- | `@adecore/shell` | For the main process: `createWindows`, `createWindowState`, `createUpdater`, `createTheme`, `menuTemplateOf`, `staticMenuTemplate`, `createMenuCommands`, `createPageKeys` and the web guards |
26
+ | `@adecore/shell` | For the main process: `createWindows`, `createWindowState`, `createUpdater`, `createTheme`, `menuTemplateOf`, `staticMenuTemplate`, `createMenuCommands`, `createPageKeys`, `createAppScheme` and the web guards |
27
27
  | `@adecore/shell/bridge` | The shapes that cross IPC: `MenuSpec`, `MenuNode`, `MENU_ROLES`, `UpdateState`, `ThemeState` and `compareVersions`. It imports nothing from Electron, so a preload and the page read it too. |
28
28
 
29
29
  ## Documentation
@@ -36,8 +36,9 @@ The package registers no IPC handler and listens to no app-wide Electron event.
36
36
  | [Window state](https://adecore.dev/shell/window-state) | Each window opens where it was left |
37
37
  | [Theme](https://adecore.dev/shell/theme) | The page's theme on the window, its controls and Chromium |
38
38
  | [Web guards](https://adecore.dev/shell/web-guards) | Where the app's page may go, and who may speak for it |
39
+ | [App scheme](https://adecore.dev/shell/app-scheme) | The app's page served from a scheme of its own, with the guards bound to it |
39
40
  | [Bridge](https://adecore.dev/shell/bridge) | The shapes that cross IPC |
40
41
 
41
42
  ## License
42
43
 
43
- MIT
44
+ FSL-1.1-MIT, see [LICENSE](./LICENSE).
@@ -0,0 +1,34 @@
1
+ import type { CustomScheme } from 'electron';
2
+ import { type NavigationVerdict, type SenderFrame } from './web-guards.ts';
3
+ export declare const APP_SCHEME_PRIVILEGES: NonNullable<CustomScheme['privileges']>;
4
+ export interface SchemeFolder {
5
+ readonly root: string;
6
+ readonly routes?: boolean;
7
+ readonly headers?: Record<string, string> | ((file: string) => Record<string, string>);
8
+ }
9
+ export type SchemeResolver = (request: Request, url: URL) => Response | Promise<Response>;
10
+ export interface AppSchemeOptions {
11
+ readonly scheme: string;
12
+ readonly host?: string;
13
+ readonly root: string;
14
+ readonly routes?: boolean;
15
+ readonly headers?: SchemeFolder['headers'];
16
+ readonly hosts?: Readonly<Record<string, SchemeFolder | SchemeResolver>>;
17
+ readonly pageUrl?: string;
18
+ readonly privileges?: CustomScheme['privileges'];
19
+ readonly read?: (file: string, request: Request) => Promise<Response>;
20
+ }
21
+ export interface AppScheme {
22
+ readonly scheme: string;
23
+ readonly url: string;
24
+ readonly origin: string;
25
+ readonly privileged: CustomScheme;
26
+ handle(request: Request): Promise<Response>;
27
+ serveFile(root: string, file: string, request: Request, headers?: Record<string, string>): Promise<Response>;
28
+ originOf(url: string): string | null;
29
+ isAppUrl(url: string): boolean;
30
+ navigation(url: string): NavigationVerdict;
31
+ isAppSender(isAppWindow: boolean, frame: SenderFrame | null): boolean;
32
+ }
33
+ export declare const segmentsOf: (pathname: string) => string[] | null;
34
+ export declare function createAppScheme(options: AppSchemeOptions): AppScheme;
@@ -0,0 +1,149 @@
1
+ import { realpath, readFile, stat } from 'node:fs/promises';
2
+ import { extname, isAbsolute, join, relative, resolve } from 'node:path';
3
+ import { appWindowNavigation, isAppSender, originOf } from './web-guards.js';
4
+ /*
5
+ * Standard and secure give the page a real origin and a secure context (WebCrypto), fetch and CORS let it
6
+ * load from the scheme and talk to a backend, streaming serves big files, the code cache keeps compiled
7
+ * scripts between starts, and a service worker needs its own privilege.
8
+ */
9
+ export const APP_SCHEME_PRIVILEGES = {
10
+ standard: true,
11
+ secure: true,
12
+ supportFetchAPI: true,
13
+ corsEnabled: true,
14
+ stream: true,
15
+ codeCache: true,
16
+ allowServiceWorkers: true
17
+ };
18
+ const CONTENT_TYPES = {
19
+ '.html': 'text/html; charset=utf-8',
20
+ '.js': 'text/javascript; charset=utf-8',
21
+ '.mjs': 'text/javascript; charset=utf-8',
22
+ '.css': 'text/css; charset=utf-8',
23
+ '.json': 'application/json',
24
+ '.map': 'application/json',
25
+ '.webmanifest': 'application/manifest+json',
26
+ // A WebAssembly module compiles while it streams only under its own type.
27
+ '.wasm': 'application/wasm',
28
+ '.svg': 'image/svg+xml',
29
+ '.png': 'image/png',
30
+ '.jpg': 'image/jpeg',
31
+ '.jpeg': 'image/jpeg',
32
+ '.gif': 'image/gif',
33
+ '.webp': 'image/webp',
34
+ '.avif': 'image/avif',
35
+ '.ico': 'image/x-icon',
36
+ '.woff2': 'font/woff2',
37
+ '.woff': 'font/woff',
38
+ '.ttf': 'font/ttf',
39
+ '.otf': 'font/otf',
40
+ '.mp3': 'audio/mpeg',
41
+ '.wav': 'audio/wav',
42
+ '.ogg': 'audio/ogg',
43
+ '.mp4': 'video/mp4',
44
+ '.webm': 'video/webm',
45
+ '.txt': 'text/plain; charset=utf-8'
46
+ };
47
+ const notFound = () => new Response('Not found', { status: 404 });
48
+ const readWhole = async (file) => new Response(new Uint8Array(await readFile(file)));
49
+ /* The segments of a path as the URL carries them, decoded, or null when one could climb out or means nothing on its own. */
50
+ export const segmentsOf = (pathname) => {
51
+ const path = pathname.replace(/^\/+/, '');
52
+ if (path === '') {
53
+ return [];
54
+ }
55
+ const segments = [];
56
+ for (const raw of path.split('/')) {
57
+ let segment;
58
+ try {
59
+ segment = decodeURIComponent(raw);
60
+ }
61
+ catch {
62
+ return null;
63
+ }
64
+ if (segment === '' || segment === '.' || segment === '..' || /[/\\\0]/.test(segment)) {
65
+ return null;
66
+ }
67
+ segments.push(segment);
68
+ }
69
+ return segments;
70
+ };
71
+ const isInside = (root, path) => {
72
+ const between = relative(root, path);
73
+ return between !== '' && !between.startsWith('..') && !isAbsolute(between);
74
+ };
75
+ /*
76
+ * Registers nothing by itself: the app hands `privileged` to `protocol.registerSchemesAsPrivileged`
77
+ * before it is ready and `handle` to `protocol.handle`, on the sessions it picks. Every file it serves
78
+ * lies inside the folder of its host, also after following a symlink.
79
+ */
80
+ export function createAppScheme(options) {
81
+ const scheme = options.scheme;
82
+ const pageHost = (options.host ?? 'app').toLowerCase();
83
+ const schemes = [scheme];
84
+ const own = `${scheme}://${pageHost}`;
85
+ const url = options.pageUrl ?? `${own}/`;
86
+ const origin = originOf(url, schemes) ?? own;
87
+ const read = options.read ?? readWhole;
88
+ const hosts = new Map(Object.entries(options.hosts ?? {}).map(([name, host]) => [name.toLowerCase(), host]));
89
+ hosts.set(pageHost, { root: options.root, routes: options.routes ?? true, headers: options.headers });
90
+ const serveFile = async (root, file, request, headers = {}) => {
91
+ let found;
92
+ try {
93
+ const [realRoot, realFile] = await Promise.all([realpath(resolve(root)), realpath(resolve(file))]);
94
+ if (!isInside(realRoot, realFile) || !(await stat(realFile)).isFile()) {
95
+ return notFound();
96
+ }
97
+ found = realFile;
98
+ }
99
+ catch {
100
+ return notFound();
101
+ }
102
+ const response = await read(found, request);
103
+ const merged = new Headers(response.headers);
104
+ const type = CONTENT_TYPES[extname(found).toLowerCase()];
105
+ if (type !== undefined) {
106
+ merged.set('content-type', type);
107
+ }
108
+ for (const [name, value] of Object.entries(headers)) {
109
+ merged.set(name, value);
110
+ }
111
+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers: merged });
112
+ };
113
+ const serveFolder = (folder, request, address) => {
114
+ const segments = segmentsOf(address.pathname);
115
+ if (segments === null) {
116
+ return notFound();
117
+ }
118
+ // A missing chunk with an extension stays a 404, so a stale one fails as a load error rather than as the page.
119
+ const page = segments.length === 0 || (folder.routes === true && extname(segments.at(-1)) === '');
120
+ const file = page ? join(folder.root, 'index.html') : join(folder.root, ...segments);
121
+ const headers = typeof folder.headers === 'function' ? folder.headers(file) : folder.headers;
122
+ return serveFile(folder.root, file, request, headers);
123
+ };
124
+ return {
125
+ scheme,
126
+ url,
127
+ origin,
128
+ privileged: { scheme, privileges: options.privileges ?? APP_SCHEME_PRIVILEGES },
129
+ handle: async (request) => {
130
+ let address;
131
+ try {
132
+ address = new URL(request.url);
133
+ }
134
+ catch {
135
+ return notFound();
136
+ }
137
+ const host = address.protocol === `${scheme}:` ? hosts.get(address.host.toLowerCase()) : undefined;
138
+ if (host === undefined) {
139
+ return notFound();
140
+ }
141
+ return typeof host === 'function' ? host(request, address) : serveFolder(host, request, address);
142
+ },
143
+ serveFile,
144
+ originOf: (address) => originOf(address, schemes),
145
+ isAppUrl: (address) => originOf(address, schemes) === origin,
146
+ navigation: (address) => appWindowNavigation(address, origin, schemes),
147
+ isAppSender: (isAppWindow, frame) => isAppSender(isAppWindow, frame, origin, schemes)
148
+ };
149
+ }
package/dist/index.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ export { APP_SCHEME_PRIVILEGES, createAppScheme, segmentsOf } from './app-scheme.ts';
2
+ export type { AppScheme, AppSchemeOptions, SchemeFolder, SchemeResolver } from './app-scheme.ts';
1
3
  export { createMenuCommands, devToolsAccelerator, menuTemplateOf, staticMenuTemplate } from './menu.ts';
2
4
  export type { MenuCommandOptions, MenuTemplateOptions, MenuWindow, StaticMenuOptions } from './menu.ts';
3
5
  export { createPageKeys, PAGE_KEY_MS } from './page-keys.ts';
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ export { APP_SCHEME_PRIVILEGES, createAppScheme, segmentsOf } from './app-scheme.js';
1
2
  export { createMenuCommands, devToolsAccelerator, menuTemplateOf, staticMenuTemplate } from './menu.js';
2
3
  export { createPageKeys, PAGE_KEY_MS } from './page-keys.js';
3
4
  export { createUpdater, describeUpdateError, UPDATE_INTERVAL_MS } from './updater.js';
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@adecore/shell",
3
- "version": "0.17.0-beta.1",
3
+ "version": "0.17.0-beta.2",
4
4
  "description": "The main process of an Electron app: its menu, its updater and the guards around its page.",
5
- "license": "MIT",
5
+ "license": "FSL-1.1-MIT",
6
6
  "author": "Bas Milius",
7
7
  "repository": {
8
8
  "type": "git",
@@ -0,0 +1,204 @@
1
+ import { realpath, readFile, stat } from 'node:fs/promises';
2
+ import { extname, isAbsolute, join, relative, resolve } from 'node:path';
3
+ import type { CustomScheme } from 'electron';
4
+ import { appWindowNavigation, isAppSender, originOf, type NavigationVerdict, type SenderFrame } from './web-guards.ts';
5
+
6
+ /*
7
+ * Standard and secure give the page a real origin and a secure context (WebCrypto), fetch and CORS let it
8
+ * load from the scheme and talk to a backend, streaming serves big files, the code cache keeps compiled
9
+ * scripts between starts, and a service worker needs its own privilege.
10
+ */
11
+ export const APP_SCHEME_PRIVILEGES: NonNullable<CustomScheme['privileges']> = {
12
+ standard: true,
13
+ secure: true,
14
+ supportFetchAPI: true,
15
+ corsEnabled: true,
16
+ stream: true,
17
+ codeCache: true,
18
+ allowServiceWorkers: true
19
+ };
20
+
21
+ const CONTENT_TYPES: Readonly<Record<string, string>> = {
22
+ '.html': 'text/html; charset=utf-8',
23
+ '.js': 'text/javascript; charset=utf-8',
24
+ '.mjs': 'text/javascript; charset=utf-8',
25
+ '.css': 'text/css; charset=utf-8',
26
+ '.json': 'application/json',
27
+ '.map': 'application/json',
28
+ '.webmanifest': 'application/manifest+json',
29
+ // A WebAssembly module compiles while it streams only under its own type.
30
+ '.wasm': 'application/wasm',
31
+ '.svg': 'image/svg+xml',
32
+ '.png': 'image/png',
33
+ '.jpg': 'image/jpeg',
34
+ '.jpeg': 'image/jpeg',
35
+ '.gif': 'image/gif',
36
+ '.webp': 'image/webp',
37
+ '.avif': 'image/avif',
38
+ '.ico': 'image/x-icon',
39
+ '.woff2': 'font/woff2',
40
+ '.woff': 'font/woff',
41
+ '.ttf': 'font/ttf',
42
+ '.otf': 'font/otf',
43
+ '.mp3': 'audio/mpeg',
44
+ '.wav': 'audio/wav',
45
+ '.ogg': 'audio/ogg',
46
+ '.mp4': 'video/mp4',
47
+ '.webm': 'video/webm',
48
+ '.txt': 'text/plain; charset=utf-8'
49
+ };
50
+
51
+ export interface SchemeFolder {
52
+ readonly root: string;
53
+ /* A page that routes itself: an address without an extension gets its `index.html`. Otherwise only `/` does. */
54
+ readonly routes?: boolean;
55
+ /* On every response of the folder, such as a `Content-Security-Policy`, or per file. */
56
+ readonly headers?: Record<string, string> | ((file: string) => Record<string, string>);
57
+ }
58
+
59
+ /* A host that answers a request itself, such as files it finds by an id; `serveFile` serves what it found. */
60
+ export type SchemeResolver = (request: Request, url: URL) => Response | Promise<Response>;
61
+
62
+ export interface AppSchemeOptions {
63
+ /* Without the colon, such as `app`. */
64
+ readonly scheme: string;
65
+ /* The host of the page; `app` without one. */
66
+ readonly host?: string;
67
+ /* The built page. It routes itself unless `routes` is false. */
68
+ readonly root: string;
69
+ readonly routes?: boolean;
70
+ readonly headers?: SchemeFolder['headers'];
71
+ /* Other hosts on the same scheme, by name: a folder of their own or a resolver. */
72
+ readonly hosts?: Readonly<Record<string, SchemeFolder | SchemeResolver>>;
73
+ /* The URL the window loads instead, such as a dev server; the guards then take its origin for the app's. */
74
+ readonly pageUrl?: string;
75
+ readonly privileges?: CustomScheme['privileges'];
76
+ /* Answers with a file the scheme found. Reads it whole without one; `net.fetch` of its `file:` URL streams it. */
77
+ readonly read?: (file: string, request: Request) => Promise<Response>;
78
+ }
79
+
80
+ export interface AppScheme {
81
+ readonly scheme: string;
82
+ /* What the window loads: `pageUrl`, or the root of the page's host. */
83
+ readonly url: string;
84
+ /* The origin the guards take for the app's. */
85
+ readonly origin: string;
86
+ /* For `protocol.registerSchemesAsPrivileged`, before the app is ready. */
87
+ readonly privileged: CustomScheme;
88
+ /* For `protocol.handle`: the file a request names, or a 404. */
89
+ handle(request: Request): Promise<Response>;
90
+ /* Serves `file` when it lies inside `root`, for a resolver of a host. */
91
+ serveFile(root: string, file: string, request: Request, headers?: Record<string, string>): Promise<Response>;
92
+ originOf(url: string): string | null;
93
+ isAppUrl(url: string): boolean;
94
+ navigation(url: string): NavigationVerdict;
95
+ isAppSender(isAppWindow: boolean, frame: SenderFrame | null): boolean;
96
+ }
97
+
98
+ const notFound = (): Response => new Response('Not found', { status: 404 });
99
+
100
+ const readWhole = async (file: string): Promise<Response> => new Response(new Uint8Array(await readFile(file)));
101
+
102
+ /* The segments of a path as the URL carries them, decoded, or null when one could climb out or means nothing on its own. */
103
+ export const segmentsOf = (pathname: string): string[] | null => {
104
+ const path = pathname.replace(/^\/+/, '');
105
+ if (path === '') {
106
+ return [];
107
+ }
108
+ const segments: string[] = [];
109
+ for (const raw of path.split('/')) {
110
+ let segment: string;
111
+ try {
112
+ segment = decodeURIComponent(raw);
113
+ } catch {
114
+ return null;
115
+ }
116
+ if (segment === '' || segment === '.' || segment === '..' || /[/\\\0]/.test(segment)) {
117
+ return null;
118
+ }
119
+ segments.push(segment);
120
+ }
121
+ return segments;
122
+ };
123
+
124
+ const isInside = (root: string, path: string): boolean => {
125
+ const between = relative(root, path);
126
+ return between !== '' && !between.startsWith('..') && !isAbsolute(between);
127
+ };
128
+
129
+ /*
130
+ * Registers nothing by itself: the app hands `privileged` to `protocol.registerSchemesAsPrivileged`
131
+ * before it is ready and `handle` to `protocol.handle`, on the sessions it picks. Every file it serves
132
+ * lies inside the folder of its host, also after following a symlink.
133
+ */
134
+ export function createAppScheme(options: AppSchemeOptions): AppScheme {
135
+ const scheme = options.scheme;
136
+ const pageHost = (options.host ?? 'app').toLowerCase();
137
+ const schemes = [scheme];
138
+ const own = `${scheme}://${pageHost}`;
139
+ const url = options.pageUrl ?? `${own}/`;
140
+ const origin = originOf(url, schemes) ?? own;
141
+ const read = options.read ?? readWhole;
142
+ const hosts = new Map<string, SchemeFolder | SchemeResolver>(Object.entries(options.hosts ?? {}).map(([name, host]) => [name.toLowerCase(), host]));
143
+ hosts.set(pageHost, { root: options.root, routes: options.routes ?? true, headers: options.headers });
144
+
145
+ const serveFile = async (root: string, file: string, request: Request, headers: Record<string, string> = {}): Promise<Response> => {
146
+ let found: string;
147
+ try {
148
+ const [realRoot, realFile] = await Promise.all([realpath(resolve(root)), realpath(resolve(file))]);
149
+ if (!isInside(realRoot, realFile) || !(await stat(realFile)).isFile()) {
150
+ return notFound();
151
+ }
152
+ found = realFile;
153
+ } catch {
154
+ return notFound();
155
+ }
156
+ const response = await read(found, request);
157
+ const merged = new Headers(response.headers);
158
+ const type = CONTENT_TYPES[extname(found).toLowerCase()];
159
+ if (type !== undefined) {
160
+ merged.set('content-type', type);
161
+ }
162
+ for (const [name, value] of Object.entries(headers)) {
163
+ merged.set(name, value);
164
+ }
165
+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers: merged });
166
+ };
167
+
168
+ const serveFolder = (folder: SchemeFolder, request: Request, address: URL): Promise<Response> | Response => {
169
+ const segments = segmentsOf(address.pathname);
170
+ if (segments === null) {
171
+ return notFound();
172
+ }
173
+ // A missing chunk with an extension stays a 404, so a stale one fails as a load error rather than as the page.
174
+ const page = segments.length === 0 || (folder.routes === true && extname(segments.at(-1)!) === '');
175
+ const file = page ? join(folder.root, 'index.html') : join(folder.root, ...segments);
176
+ const headers = typeof folder.headers === 'function' ? folder.headers(file) : folder.headers;
177
+ return serveFile(folder.root, file, request, headers);
178
+ };
179
+
180
+ return {
181
+ scheme,
182
+ url,
183
+ origin,
184
+ privileged: { scheme, privileges: options.privileges ?? APP_SCHEME_PRIVILEGES },
185
+ handle: async (request) => {
186
+ let address: URL;
187
+ try {
188
+ address = new URL(request.url);
189
+ } catch {
190
+ return notFound();
191
+ }
192
+ const host = address.protocol === `${scheme}:` ? hosts.get(address.host.toLowerCase()) : undefined;
193
+ if (host === undefined) {
194
+ return notFound();
195
+ }
196
+ return typeof host === 'function' ? host(request, address) : serveFolder(host, request, address);
197
+ },
198
+ serveFile,
199
+ originOf: (address) => originOf(address, schemes),
200
+ isAppUrl: (address) => originOf(address, schemes) === origin,
201
+ navigation: (address) => appWindowNavigation(address, origin, schemes),
202
+ isAppSender: (isAppWindow, frame) => isAppSender(isAppWindow, frame, origin, schemes)
203
+ };
204
+ }
package/src/index.ts CHANGED
@@ -1,3 +1,5 @@
1
+ export { APP_SCHEME_PRIVILEGES, createAppScheme, segmentsOf } from './app-scheme.ts';
2
+ export type { AppScheme, AppSchemeOptions, SchemeFolder, SchemeResolver } from './app-scheme.ts';
1
3
  export { createMenuCommands, devToolsAccelerator, menuTemplateOf, staticMenuTemplate } from './menu.ts';
2
4
  export type { MenuCommandOptions, MenuTemplateOptions, MenuWindow, StaticMenuOptions } from './menu.ts';
3
5
  export { createPageKeys, PAGE_KEY_MS } from './page-keys.ts';