@pexis/core 0.1.1 → 0.1.3
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/AGENTS.md +65 -15
- package/API.md +11 -8
- package/README.md +1 -1
- package/api.json +5951 -0
- package/dist/app.d.ts +77 -3
- package/dist/app.js +284 -38
- package/dist/app.js.map +1 -1
- package/dist/components.d.ts +100 -6
- package/dist/components.js +87 -19
- package/dist/components.js.map +1 -1
- package/dist/context.d.ts +27 -2
- package/dist/context.js +18 -2
- package/dist/context.js.map +1 -1
- package/dist/cors.d.ts +14 -0
- package/dist/cors.js +8 -0
- package/dist/cors.js.map +1 -1
- package/dist/csrf.d.ts +9 -0
- package/dist/csrf.js +9 -0
- package/dist/csrf.js.map +1 -1
- package/dist/form.d.ts +21 -3
- package/dist/form.js +38 -4
- package/dist/form.js.map +1 -1
- package/dist/host.d.ts +6 -1
- package/dist/host.js +6 -1
- package/dist/host.js.map +1 -1
- package/dist/html.d.ts +46 -5
- package/dist/html.js +112 -5
- package/dist/html.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/jsx-runtime.d.ts +32 -0
- package/dist/jsx-runtime.js +16 -0
- package/dist/jsx-runtime.js.map +1 -1
- package/dist/page.d.ts +74 -1
- package/dist/page.js +48 -5
- package/dist/page.js.map +1 -1
- package/dist/rate-limit.d.ts +46 -0
- package/dist/rate-limit.js +19 -0
- package/dist/rate-limit.js.map +1 -1
- package/dist/registry.d.ts +126 -3
- package/dist/registry.js +53 -1
- package/dist/registry.js.map +1 -1
- package/dist/schema.d.ts +129 -3
- package/dist/schema.js +80 -7
- package/dist/schema.js.map +1 -1
- package/dist/security.d.ts +38 -2
- package/dist/security.js +44 -9
- package/dist/security.js.map +1 -1
- package/dist/styles.d.ts +37 -2
- package/dist/styles.js +32 -2
- package/dist/styles.js.map +1 -1
- package/dist/types.d.ts +163 -19
- package/dist/urls.d.ts +8 -1
- package/dist/urls.js +8 -1
- package/dist/urls.js.map +1 -1
- package/package.json +2 -1
package/dist/app.d.ts
CHANGED
|
@@ -7,15 +7,23 @@ export declare function memoryStateWarning(items: readonly string[], env: {
|
|
|
7
7
|
production: boolean;
|
|
8
8
|
singleInstance: boolean;
|
|
9
9
|
}): string | null;
|
|
10
|
+
/** What createApp() takes. Only `origin` is required. */
|
|
10
11
|
export interface AppOptions {
|
|
11
12
|
/** Public origin, for example https://example.com. */
|
|
12
13
|
origin: string;
|
|
13
|
-
/**
|
|
14
|
+
/**
|
|
15
|
+
* Default <html lang>.
|
|
16
|
+
*
|
|
17
|
+
* @default "en"
|
|
18
|
+
*/
|
|
14
19
|
lang?: string;
|
|
15
20
|
/** Wraps every page body. Default: the body inside <main>. null for no wrapper. */
|
|
16
21
|
layout?: Layout | null;
|
|
22
|
+
/** The site's pages. With `pexis dev`, the generated `pages` from pexis.gen.ts. */
|
|
17
23
|
pages?: Page[];
|
|
24
|
+
/** The site's actions. With `pexis dev`, the generated `actions` from pexis.gen.ts. */
|
|
18
25
|
actions?: Action[];
|
|
26
|
+
/** Plugins, set up in this order. A plugin that needs another lists it in `requires`, and must come after it. */
|
|
19
27
|
plugins?: Plugin[];
|
|
20
28
|
/** App middleware, run after plugin middleware. */
|
|
21
29
|
middleware?: Middleware[];
|
|
@@ -31,10 +39,13 @@ export interface AppOptions {
|
|
|
31
39
|
navigation?: NavigationOptions;
|
|
32
40
|
/** Your own pages for "not found" (404) and "something went wrong" (500), in the site's layout. */
|
|
33
41
|
errorPages?: {
|
|
42
|
+
/** Shown with 404 when no page matches, or a page's load() returns notFound(). */
|
|
34
43
|
notFound?: ErrorPage;
|
|
44
|
+
/** Shown with 500 when a request fails. The error is logged, never shown. */
|
|
35
45
|
serverError?: ErrorPage;
|
|
36
46
|
};
|
|
37
47
|
}
|
|
48
|
+
/** Navigation the browser does itself, with no JavaScript: page transitions and prefetching. Both off by default. */
|
|
38
49
|
export interface NavigationOptions {
|
|
39
50
|
/**
|
|
40
51
|
* Cross-document View Transitions: browsers animate between pages of this
|
|
@@ -50,25 +61,88 @@ export interface NavigationOptions {
|
|
|
50
61
|
*/
|
|
51
62
|
prefetch?: false | 'conservative' | 'moderate' | 'eager';
|
|
52
63
|
}
|
|
64
|
+
/**
|
|
65
|
+
* The Speculation Rules JSON behind `navigation.prefetch`: prefetch same-site
|
|
66
|
+
* links, except the given path prefixes.
|
|
67
|
+
*
|
|
68
|
+
* @category plugins
|
|
69
|
+
* @param eagerness When the browser starts: on press, on hover, or sooner.
|
|
70
|
+
* @param exclude Path prefixes never to prefetch, such as "/auth/".
|
|
71
|
+
*/
|
|
53
72
|
export declare function speculationRules(eagerness: 'conservative' | 'moderate' | 'eager', exclude: readonly string[]): string;
|
|
73
|
+
/** The app createApp() returns: the whole site as one request handler, and what plugins and tools read. */
|
|
54
74
|
export interface App {
|
|
55
75
|
/**
|
|
56
76
|
* The whole site, as one web-standard request handler. Adapters pass what
|
|
57
77
|
* they know about the connection, such as the client's address.
|
|
58
78
|
*/
|
|
59
79
|
fetch(request: Request, connection?: Connection): Promise<Response>;
|
|
80
|
+
/** The app's settings. */
|
|
60
81
|
readonly config: AppConfig;
|
|
82
|
+
/** Every page, plugins' included, in routing order. */
|
|
61
83
|
readonly pages: readonly Page[];
|
|
84
|
+
/** Every action, plugins' included. */
|
|
62
85
|
readonly actions: readonly Action[];
|
|
63
86
|
/** Every public page path, with route parameters filled in. */
|
|
64
87
|
entries(): Promise<string[]>;
|
|
65
88
|
/** Check rules from plugins and the app, for @pexis/checks. */
|
|
66
89
|
readonly checkRules: readonly CheckRuleLike[];
|
|
90
|
+
/**
|
|
91
|
+
* Whether this app has something to say about the request: one of its pages,
|
|
92
|
+
* actions or plugin routes (including the right path with the wrong method).
|
|
93
|
+
* For mounting Pexis inside another server, which handles everything else.
|
|
94
|
+
*/
|
|
95
|
+
matches(request: Request): boolean;
|
|
67
96
|
}
|
|
97
|
+
/** Where agents read the site's tools: `/pexis/actions.json`. Every page names it in a `Link` header. */
|
|
68
98
|
export declare const TOOLS_PATH = "/pexis/actions.json";
|
|
69
|
-
/**
|
|
99
|
+
/**
|
|
100
|
+
* Why an agent with a token may not run this action, or null if it may: it
|
|
101
|
+
* needs the person's approval, is for people only, or is outside the
|
|
102
|
+
* granted scopes. The core applies it to every agent request.
|
|
103
|
+
*
|
|
104
|
+
* @experimental
|
|
105
|
+
* @param agent Who the agent acts for, and what it was granted.
|
|
106
|
+
* @param action The action it wants to run.
|
|
107
|
+
*/
|
|
70
108
|
export declare function agentRefusal(agent: AgentIdentity, action: Action): string | null;
|
|
71
|
-
/**
|
|
109
|
+
/**
|
|
110
|
+
* Serializes JSON-LD for a script block, adding the schema.org context, with
|
|
111
|
+
* `<` escaped so the data cannot close the script.
|
|
112
|
+
*
|
|
113
|
+
* @category plugins
|
|
114
|
+
* @param data schema.org data, without "@context".
|
|
115
|
+
*/
|
|
72
116
|
export declare function jsonLd(data: Record<string, unknown>): string;
|
|
117
|
+
/**
|
|
118
|
+
* Builds the app: pages, actions, layout, plugins, and security and
|
|
119
|
+
* navigation options. The result is one web-standard request handler,
|
|
120
|
+
* `app.fetch(request)`, that an adapter serves on Node, Bun or Cloudflare
|
|
121
|
+
* Workers, or another server mounts. Throws when the options are invalid,
|
|
122
|
+
* such as two pages on one path or two actions with one name.
|
|
123
|
+
*
|
|
124
|
+
* @param options The app's origin, pages, actions, plugins and settings.
|
|
125
|
+
* @example
|
|
126
|
+
* ```ts
|
|
127
|
+
* export default createApp({
|
|
128
|
+
* origin: process.env.SITE_ORIGIN ?? 'http://localhost:3000',
|
|
129
|
+
* layout: site,
|
|
130
|
+
* pages,
|
|
131
|
+
* actions,
|
|
132
|
+
* plugins: [markdown(), openapi(), siteFiles()],
|
|
133
|
+
* });
|
|
134
|
+
* ```
|
|
135
|
+
*/
|
|
73
136
|
export declare function createApp(options: AppOptions): App;
|
|
137
|
+
/**
|
|
138
|
+
* Declares a plugin: a name and a setup function that receives the plugin
|
|
139
|
+
* API. Throws when the name is not valid.
|
|
140
|
+
*
|
|
141
|
+
* @param plugin Its name, the plugins it requires, and setup.
|
|
142
|
+
* @example
|
|
143
|
+
* ```ts
|
|
144
|
+
* const stylesheet = (href: string) =>
|
|
145
|
+
* definePlugin({ name: 'stylesheet', setup: (api) => api.head(() => html`<link rel="stylesheet" href="${href}">`) });
|
|
146
|
+
* ```
|
|
147
|
+
*/
|
|
74
148
|
export declare function definePlugin(plugin: Plugin): Plugin;
|
package/dist/app.js
CHANGED
|
@@ -2,10 +2,12 @@ import { hasContextStorage, runWithContext } from './context.js';
|
|
|
2
2
|
import { createCors } from './cors.js';
|
|
3
3
|
import { crossSiteRefusal, isSafeMethod } from './csrf.js';
|
|
4
4
|
import { renderForm, TARGET_ID } from './form.js';
|
|
5
|
+
import { IN_PLACE } from './components.js';
|
|
5
6
|
import { escapeHtml, html, raw, renderToString } from './html.js';
|
|
7
|
+
import { Fragment, jsx } from './jsx-runtime.js';
|
|
6
8
|
import { checkPath, compilePath, isSignal } from './page.js';
|
|
7
9
|
import { rateLimiter } from './rate-limit.js';
|
|
8
|
-
import { createRegistry, isInvalid } from './registry.js';
|
|
10
|
+
import { createRegistry, describeAction, isInvalid } from './registry.js';
|
|
9
11
|
import { validate } from './schema.js';
|
|
10
12
|
import { BodyError, contentSecurityPolicy, createNonce, DEFAULT_ACTION_RATE_LIMIT, DEFAULT_MAX_BODY_BYTES, documentSecurityHeaders, readActionInput, } from './security.js';
|
|
11
13
|
import { usedStyles } from './styles.js';
|
|
@@ -28,6 +30,14 @@ export function memoryStateWarning(items, env) {
|
|
|
28
30
|
].join('\n');
|
|
29
31
|
}
|
|
30
32
|
const VIEW_TRANSITIONS = '@view-transition{navigation:auto}@media (prefers-reduced-motion: reduce){::view-transition-group(*),::view-transition-old(*),::view-transition-new(*){animation:none!important}}';
|
|
33
|
+
/**
|
|
34
|
+
* The Speculation Rules JSON behind `navigation.prefetch`: prefetch same-site
|
|
35
|
+
* links, except the given path prefixes.
|
|
36
|
+
*
|
|
37
|
+
* @category plugins
|
|
38
|
+
* @param eagerness When the browser starts: on press, on hover, or sooner.
|
|
39
|
+
* @param exclude Path prefixes never to prefetch, such as "/auth/".
|
|
40
|
+
*/
|
|
31
41
|
export function speculationRules(eagerness, exclude) {
|
|
32
42
|
return JSON.stringify({
|
|
33
43
|
prefetch: [
|
|
@@ -44,11 +54,20 @@ export function speculationRules(eagerness, exclude) {
|
|
|
44
54
|
],
|
|
45
55
|
}).replaceAll('<', '\\u003c');
|
|
46
56
|
}
|
|
57
|
+
/** Where agents read the site's tools: `/pexis/actions.json`. Every page names it in a `Link` header. */
|
|
47
58
|
export const TOOLS_PATH = '/pexis/actions.json';
|
|
48
59
|
const ACTION_PATH = /^\/actions\/([a-z][a-z0-9_]{0,63})$/;
|
|
49
60
|
const PLUGIN_NAME = /^[a-z0-9@][a-z0-9@/._-]*$/;
|
|
50
61
|
const STATUS = { done: 200, invalid: 422, forbidden: 403, failed: 500 };
|
|
51
|
-
/**
|
|
62
|
+
/**
|
|
63
|
+
* Why an agent with a token may not run this action, or null if it may: it
|
|
64
|
+
* needs the person's approval, is for people only, or is outside the
|
|
65
|
+
* granted scopes. The core applies it to every agent request.
|
|
66
|
+
*
|
|
67
|
+
* @experimental
|
|
68
|
+
* @param agent Who the agent acts for, and what it was granted.
|
|
69
|
+
* @param action The action it wants to run.
|
|
70
|
+
*/
|
|
52
71
|
export function agentRefusal(agent, action) {
|
|
53
72
|
if (action.agents === false)
|
|
54
73
|
return 'This action is for people only. Use the form on the page.';
|
|
@@ -63,9 +82,44 @@ export function agentRefusal(agent, action) {
|
|
|
63
82
|
const RISK_ORDER = { read: 0, write: 1, irreversible: 2 };
|
|
64
83
|
/** Calls one request may make, so actions calling each other in a circle stop. */
|
|
65
84
|
const MAX_CALLS = 100;
|
|
85
|
+
/** The inputs whose form data carries a list: groups of checkboxes. */
|
|
86
|
+
function listFields(action) {
|
|
87
|
+
return new Set(Object.entries(action.input).filter(([, f]) => f.kind === 'choices').map(([name]) => name));
|
|
88
|
+
}
|
|
66
89
|
function json(body, status = 200) {
|
|
67
90
|
return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json; charset=utf-8' } });
|
|
68
91
|
}
|
|
92
|
+
/**
|
|
93
|
+
* The result with its link kept only when it stays on this site: a path, or a
|
|
94
|
+
* URL on the app's own origin, stored as a path. Anything else (another site,
|
|
95
|
+
* javascript:, a malformed URL, empty text) is a mistake in the action, so it
|
|
96
|
+
* is dropped and logged rather than rendered.
|
|
97
|
+
*/
|
|
98
|
+
function withSafeLink(action, result, ctx) {
|
|
99
|
+
if (result.link === undefined)
|
|
100
|
+
return result;
|
|
101
|
+
const { link, ...rest } = result;
|
|
102
|
+
const href = typeof link?.href === 'string' ? link.href : '';
|
|
103
|
+
const text = typeof link?.text === 'string' ? link.text.trim() : '';
|
|
104
|
+
let url = null;
|
|
105
|
+
if (text && text.length <= 200 && !href.startsWith('//') && !href.includes('\\')) {
|
|
106
|
+
try {
|
|
107
|
+
url = new URL(href, ctx.url);
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
url = null;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
if (!url || url.origin !== ctx.url.origin) {
|
|
114
|
+
console.error(`[pexis] Action "${action.name}" returned a link that is not on this site, or has no text; it was dropped.`);
|
|
115
|
+
return rest;
|
|
116
|
+
}
|
|
117
|
+
return { ...rest, link: { href: url.pathname + url.search + url.hash, text } };
|
|
118
|
+
}
|
|
119
|
+
/** A result's link as an absolute URL, for agents and JSON. */
|
|
120
|
+
function absoluteLink(result, ctx) {
|
|
121
|
+
return result.link ? { link: { href: new URL(result.link.href, ctx.url).href, text: result.link.text } } : {};
|
|
122
|
+
}
|
|
69
123
|
function wantsJson(ctx) {
|
|
70
124
|
return (ctx.request.headers.get('accept') ?? '').includes('application/json');
|
|
71
125
|
}
|
|
@@ -102,7 +156,13 @@ function fragment(target, status, body) {
|
|
|
102
156
|
function messageFragment(target, status, message) {
|
|
103
157
|
return fragment(target, status, html `<p class="px-result" tabindex="-1">${message}</p>`);
|
|
104
158
|
}
|
|
105
|
-
/**
|
|
159
|
+
/**
|
|
160
|
+
* Serializes JSON-LD for a script block, adding the schema.org context, with
|
|
161
|
+
* `<` escaped so the data cannot close the script.
|
|
162
|
+
*
|
|
163
|
+
* @category plugins
|
|
164
|
+
* @param data schema.org data, without "@context".
|
|
165
|
+
*/
|
|
106
166
|
export function jsonLd(data) {
|
|
107
167
|
// Escaping "<" stops a value such as "</script>" from ending the block.
|
|
108
168
|
return JSON.stringify({ '@context': 'https://schema.org', ...data }).replaceAll('<', '\\u003c');
|
|
@@ -113,7 +173,79 @@ function backLink(ctx) {
|
|
|
113
173
|
return referer;
|
|
114
174
|
return '/';
|
|
115
175
|
}
|
|
176
|
+
// After a people-only action, the person goes back to the page they were on
|
|
177
|
+
// (Post/Redirect/Get) and sees the outcome there once. The message travels in
|
|
178
|
+
// a short-lived HttpOnly cookie, never the URL, since it can hold personal
|
|
179
|
+
// details. It is shown escaped, so even an edited cookie is only text.
|
|
180
|
+
const NOTICE_MAX = 1000;
|
|
181
|
+
function noticeCookieName(origin) {
|
|
182
|
+
return origin.startsWith('https://') ? '__Host-pexis_notice' : 'pexis_notice';
|
|
183
|
+
}
|
|
184
|
+
function noticeCookie(origin, value, maxAge) {
|
|
185
|
+
return [`${noticeCookieName(origin)}=${value}`, 'Path=/', 'HttpOnly', 'SameSite=Lax', `Max-Age=${maxAge}`, origin.startsWith('https://') ? 'Secure' : ''].filter(Boolean).join('; ');
|
|
186
|
+
}
|
|
187
|
+
function readCookie(header, name) {
|
|
188
|
+
for (const part of (header ?? '').split(';')) {
|
|
189
|
+
const at = part.indexOf('=');
|
|
190
|
+
if (at !== -1 && part.slice(0, at).trim() === name)
|
|
191
|
+
return part.slice(at + 1).trim();
|
|
192
|
+
}
|
|
193
|
+
return undefined;
|
|
194
|
+
}
|
|
195
|
+
/** The page a people-only form was sent from, when it is a page of this site. */
|
|
196
|
+
function returnPage(ctx) {
|
|
197
|
+
const referer = ctx.request.headers.get('referer');
|
|
198
|
+
if (!referer || !URL.canParse(referer))
|
|
199
|
+
return null;
|
|
200
|
+
const url = new URL(referer);
|
|
201
|
+
if (url.origin !== ctx.url.origin || url.pathname.startsWith('/actions/') || url.pathname.startsWith('/pexis/'))
|
|
202
|
+
return null;
|
|
203
|
+
return url.pathname + url.search;
|
|
204
|
+
}
|
|
205
|
+
function encodeNotice(notice) {
|
|
206
|
+
const bytes = new TextEncoder().encode(JSON.stringify(notice));
|
|
207
|
+
let binary = '';
|
|
208
|
+
for (const b of bytes)
|
|
209
|
+
binary += String.fromCharCode(b);
|
|
210
|
+
return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
|
|
211
|
+
}
|
|
212
|
+
function decodeNotice(value) {
|
|
213
|
+
if (!value || value.length > NOTICE_MAX * 2 || !/^[A-Za-z0-9_-]+$/.test(value))
|
|
214
|
+
return null;
|
|
215
|
+
try {
|
|
216
|
+
const binary = atob(value.replaceAll('-', '+').replaceAll('_', '/'));
|
|
217
|
+
const parsed = JSON.parse(new TextDecoder().decode(Uint8Array.from(binary, (c) => c.charCodeAt(0))));
|
|
218
|
+
if (typeof parsed.message !== 'string' || !parsed.message)
|
|
219
|
+
return null;
|
|
220
|
+
const link = parsed.link;
|
|
221
|
+
// A link is rendered only as a path on this site, whatever the cookie says.
|
|
222
|
+
const safe = link && typeof link.href === 'string' && typeof link.text === 'string' && link.href.startsWith('/') && !link.href.startsWith('//') && !link.href.includes('\\');
|
|
223
|
+
return { message: parsed.message.slice(0, NOTICE_MAX), ...(safe ? { link: { href: link.href, text: link.text.slice(0, 200) } } : {}) };
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
return null;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
116
229
|
const defaultLayout = { kind: 'layout', render: ({ children }) => html `<main>${children}</main>` };
|
|
230
|
+
/**
|
|
231
|
+
* Builds the app: pages, actions, layout, plugins, and security and
|
|
232
|
+
* navigation options. The result is one web-standard request handler,
|
|
233
|
+
* `app.fetch(request)`, that an adapter serves on Node, Bun or Cloudflare
|
|
234
|
+
* Workers, or another server mounts. Throws when the options are invalid,
|
|
235
|
+
* such as two pages on one path or two actions with one name.
|
|
236
|
+
*
|
|
237
|
+
* @param options The app's origin, pages, actions, plugins and settings.
|
|
238
|
+
* @example
|
|
239
|
+
* ```ts
|
|
240
|
+
* export default createApp({
|
|
241
|
+
* origin: process.env.SITE_ORIGIN ?? 'http://localhost:3000',
|
|
242
|
+
* layout: site,
|
|
243
|
+
* pages,
|
|
244
|
+
* actions,
|
|
245
|
+
* plugins: [markdown(), openapi(), siteFiles()],
|
|
246
|
+
* });
|
|
247
|
+
* ```
|
|
248
|
+
*/
|
|
117
249
|
export function createApp(options) {
|
|
118
250
|
if (!/^https?:\/\//.test(options.origin) || !URL.canParse(options.origin)) {
|
|
119
251
|
throw new Error(`createApp: origin "${options.origin}" must be an absolute http(s) URL, such as https://example.com.`);
|
|
@@ -146,6 +278,7 @@ export function createApp(options) {
|
|
|
146
278
|
// Paths where a visit has an effect or is private, never prefetched.
|
|
147
279
|
const prefetchExclusions = new Set(['/actions/', '/pexis/']);
|
|
148
280
|
const pluginMiddleware = [];
|
|
281
|
+
const answerers = [];
|
|
149
282
|
const heads = [];
|
|
150
283
|
const bodyEnds = [];
|
|
151
284
|
const listeners = [];
|
|
@@ -182,7 +315,11 @@ export function createApp(options) {
|
|
|
182
315
|
const seen = new Set();
|
|
183
316
|
const api = {
|
|
184
317
|
config,
|
|
185
|
-
use: (mw) =>
|
|
318
|
+
use: (mw, useOptions) => {
|
|
319
|
+
pluginMiddleware.push(mw);
|
|
320
|
+
if (useOptions?.answers)
|
|
321
|
+
answerers.push(useOptions.answers);
|
|
322
|
+
},
|
|
186
323
|
maxBodyBytes,
|
|
187
324
|
noPrefetch: (prefix) => {
|
|
188
325
|
if (!/^\/[A-Za-z0-9._~/-]*\/$/.test(prefix))
|
|
@@ -230,7 +367,6 @@ export function createApp(options) {
|
|
|
230
367
|
},
|
|
231
368
|
entries: () => entries(),
|
|
232
369
|
fetch: (request, connection) => app.fetch(request, connection),
|
|
233
|
-
renderPage: (path, ctx) => renderPageAt(path, ctx),
|
|
234
370
|
};
|
|
235
371
|
for (const plugin of options.plugins ?? []) {
|
|
236
372
|
if (!PLUGIN_NAME.test(plugin.name))
|
|
@@ -252,6 +388,7 @@ export function createApp(options) {
|
|
|
252
388
|
console.warn(memoryWarning);
|
|
253
389
|
// Validates names and catches duplicate actions.
|
|
254
390
|
const registry = createRegistry(actions);
|
|
391
|
+
const offersTools = registry.describe().length > 0;
|
|
255
392
|
// Undo actions must be this app's own, and something must keep the records:
|
|
256
393
|
// a declared undo with nowhere to record it would promise what cannot happen.
|
|
257
394
|
const undoTargets = new Set();
|
|
@@ -377,6 +514,9 @@ export function createApp(options) {
|
|
|
377
514
|
const headers = new Headers({ 'content-type': 'text/html; charset=utf-8' });
|
|
378
515
|
if (!doc.index)
|
|
379
516
|
headers.set('x-robots-tag', 'noindex');
|
|
517
|
+
// Agents find the site's actions from any page's headers, even with a HEAD request.
|
|
518
|
+
if (offersTools)
|
|
519
|
+
headers.append('link', `<${TOOLS_PATH}>; rel="service-desc"; type="application/json"`);
|
|
380
520
|
documentSecurityHeaders(headers, config.origin, cspExtra === false ? null : contentSecurityPolicy(ctx.nonce, cspExtra ?? {}));
|
|
381
521
|
return headers;
|
|
382
522
|
}
|
|
@@ -480,9 +620,21 @@ export function createApp(options) {
|
|
|
480
620
|
return signalResponse(data, ctx);
|
|
481
621
|
}
|
|
482
622
|
const head = typeof page.head === 'function' ? page.head(data, ctx) : page.head;
|
|
623
|
+
let body = page.render({ data, ctx, params: ctx.params });
|
|
624
|
+
// The outcome of a people-only action, shown once at the top of the page
|
|
625
|
+
// it was sent from. Focused on load, with no role: a screen reader reads a
|
|
626
|
+
// focused element in full (a focused role="status" is read by NVDA only
|
|
627
|
+
// as "status bar"), and the page works without script.
|
|
628
|
+
const notice = ctx.request.method === 'GET' ? decodeNotice(readCookie(ctx.request.headers.get('cookie'), noticeCookieName(config.origin))) : null;
|
|
629
|
+
if (notice) {
|
|
630
|
+
const link = notice.link ? html ` <a href="${notice.link.href}">${notice.link.text}</a>` : '';
|
|
631
|
+
body = jsx(Fragment, { children: [html `<p class="px-notice" tabindex="-1" autofocus>${notice.message}${link}</p>`, body] });
|
|
632
|
+
ctx.response.headers.append('set-cookie', noticeCookie(config.origin, '', 0));
|
|
633
|
+
ctx.response.headers.set('cache-control', 'private, no-store');
|
|
634
|
+
}
|
|
483
635
|
const doc = {
|
|
484
636
|
head,
|
|
485
|
-
body
|
|
637
|
+
body,
|
|
486
638
|
layout: page.layout === undefined ? appLayout : page.layout,
|
|
487
639
|
lang: page.lang ?? ctx.lang ?? config.lang,
|
|
488
640
|
index: page.index,
|
|
@@ -490,17 +642,53 @@ export function createApp(options) {
|
|
|
490
642
|
};
|
|
491
643
|
return page.stream ? streamingResponse(ctx, doc) : documentResponse(ctx, doc);
|
|
492
644
|
}
|
|
493
|
-
|
|
645
|
+
/**
|
|
646
|
+
* Renders the page at path again, as the same person, and returns the
|
|
647
|
+
* content of its <Region id={region}>, or null when there is no such page or
|
|
648
|
+
* region, or the page or the app's middleware sends the person elsewhere.
|
|
649
|
+
* Only the page's body is rendered: the layout cannot hold regions. form
|
|
650
|
+
* carries the state of the form that was just sent, so it comes back with
|
|
651
|
+
* its values and errors.
|
|
652
|
+
*
|
|
653
|
+
* After an action, the app's own middleware runs again for the page's
|
|
654
|
+
* address (withMiddleware), so a page it protects is protected here too, as
|
|
655
|
+
* a GET of that page would be. Plugin middleware has already run for this
|
|
656
|
+
* request and set up what it provides (the session, the database); running
|
|
657
|
+
* it again would read a session the action has not saved yet.
|
|
658
|
+
*/
|
|
659
|
+
async function renderRegion(path, ctx, region, form, withMiddleware = false) {
|
|
494
660
|
// Only a path on this site: "//host" or "https://host" would resolve elsewhere.
|
|
495
|
-
if (!path.startsWith('/') || path.startsWith('//') || path.includes('\\'))
|
|
661
|
+
if (!path.startsWith('/') || path.startsWith('//') || path.includes('\\') || path.length > 2048)
|
|
496
662
|
return null;
|
|
497
663
|
const url = new URL(path, ctx.url);
|
|
664
|
+
if (url.origin !== ctx.url.origin)
|
|
665
|
+
return null;
|
|
498
666
|
const rewritten = applyRewrites(url);
|
|
499
667
|
const found = matchPage(rewritten.pathname);
|
|
500
668
|
if (!found)
|
|
501
669
|
return null;
|
|
502
|
-
const
|
|
503
|
-
|
|
670
|
+
const rendering = { region, ...(form ? { form } : {}) };
|
|
671
|
+
// Its own response: what the page's load() sets (caching, a status, a
|
|
672
|
+
// cookie) belongs to a page load, never to this reply, which must not be cached.
|
|
673
|
+
const pageCtx = { ...ctx, ...rewritten.context, url, params: found.params, route: { kind: 'page', page: found.page, params: found.params }, response: { headers: new Headers() }, [IN_PLACE]: rendering };
|
|
674
|
+
let captured = null;
|
|
675
|
+
const render = async () => {
|
|
676
|
+
const page = found.page;
|
|
677
|
+
let data;
|
|
678
|
+
if (page.load) {
|
|
679
|
+
data = await page.load(pageCtx);
|
|
680
|
+
if (isSignal(data))
|
|
681
|
+
return new Response(null, { status: 204 });
|
|
682
|
+
}
|
|
683
|
+
await page.render({ data, ctx: pageCtx, params: pageCtx.params });
|
|
684
|
+
if (rendering.captured !== undefined)
|
|
685
|
+
captured = (await rendering.captured).value;
|
|
686
|
+
return new Response(null, { status: 204 });
|
|
687
|
+
};
|
|
688
|
+
const appChain = withMiddleware ? (options.middleware ?? []) : [];
|
|
689
|
+
const run = (i) => (i < appChain.length ? appChain[i](pageCtx, () => run(i + 1)) : render());
|
|
690
|
+
await runWithContext(pageCtx, () => run(0));
|
|
691
|
+
return captured;
|
|
504
692
|
}
|
|
505
693
|
// --- Actions -----------------------------------------------------------------
|
|
506
694
|
function emit(event) {
|
|
@@ -553,7 +741,7 @@ export function createApp(options) {
|
|
|
553
741
|
}
|
|
554
742
|
return { kind: 'invalid', errors: { ...result.errors }, values: input };
|
|
555
743
|
}
|
|
556
|
-
return { kind: 'done', result };
|
|
744
|
+
return { kind: 'done', result: withSafeLink(action, result, ctx) };
|
|
557
745
|
}
|
|
558
746
|
catch (error) {
|
|
559
747
|
console.error(`[pexis] Action "${action.name}" failed:`, withoutValues(error, input));
|
|
@@ -615,10 +803,10 @@ export function createApp(options) {
|
|
|
615
803
|
console.error(`[pexis] Could not mark writes undone after "${action.name}":`, error.message);
|
|
616
804
|
}
|
|
617
805
|
}
|
|
618
|
-
function actionJson(outcome) {
|
|
806
|
+
function actionJson(outcome, ctx) {
|
|
619
807
|
switch (outcome.kind) {
|
|
620
808
|
case 'done':
|
|
621
|
-
return json({ ok: true, message: outcome.result.message, data: outcome.result.data }, 200);
|
|
809
|
+
return json({ ok: true, message: outcome.result.message, data: outcome.result.data, ...absoluteLink(outcome.result, ctx) }, 200);
|
|
622
810
|
case 'invalid':
|
|
623
811
|
return json({ ok: false, message: 'Some values need fixing.', errors: outcome.errors }, 422);
|
|
624
812
|
case 'forbidden':
|
|
@@ -632,7 +820,7 @@ export function createApp(options) {
|
|
|
632
820
|
const status = STATUS[outcome.kind];
|
|
633
821
|
switch (outcome.kind) {
|
|
634
822
|
case 'done':
|
|
635
|
-
return simplePage(ctx, status, action.title, action.description, html `<h1>${action.title}</h1><p role="status">${outcome.result.message}</p><p><a href="${back}">Back</a></p>`);
|
|
823
|
+
return simplePage(ctx, status, action.title, action.description, html `<h1>${action.title}</h1><p role="status">${outcome.result.message}</p>${outcome.result.link ? html `<p><a href="${outcome.result.link.href}">${outcome.result.link.text}</a></p>` : ''}<p><a href="${back}">Back</a></p>`);
|
|
636
824
|
case 'invalid':
|
|
637
825
|
return simplePage(ctx, status, action.title, action.description, html `<h1>${action.title}</h1><p role="alert">Some values need fixing.</p>${renderForm(action, { values: outcome.values, errors: outcome.errors })}`);
|
|
638
826
|
case 'forbidden':
|
|
@@ -642,26 +830,36 @@ export function createApp(options) {
|
|
|
642
830
|
}
|
|
643
831
|
}
|
|
644
832
|
/**
|
|
645
|
-
* The result for an in-place region: the outcome's message, then the
|
|
646
|
-
*
|
|
647
|
-
*
|
|
648
|
-
*
|
|
649
|
-
*
|
|
833
|
+
* The result for an in-place region: the outcome's message, then the region
|
|
834
|
+
* as the page now renders it (Px-Page names the page), so a list in it shows
|
|
835
|
+
* the change. The form that was sent (Px-Form) comes back as the person left
|
|
836
|
+
* it, with any errors; after success, a copy the page gives its own values
|
|
837
|
+
* (a saved setting, a row's id) keeps them. When the page cannot be rendered again, the
|
|
838
|
+
* message alone: the page keeps its form. Focus goes to the message, or to
|
|
839
|
+
* the first field with an error.
|
|
650
840
|
*/
|
|
651
|
-
function actionFragment(action, outcome, ctx, target, input) {
|
|
652
|
-
const values = outcome.kind === 'invalid' ? outcome.values : input;
|
|
653
|
-
const form = renderForm(action, outcome.kind === 'invalid' ? { values, errors: outcome.errors } : { values }, { url: new URL(ctx.request.url).pathname, target });
|
|
841
|
+
async function actionFragment(action, outcome, ctx, target, input) {
|
|
654
842
|
const status = STATUS[outcome.kind];
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
843
|
+
// No role="status": the script moves focus to the message, and focus alone
|
|
844
|
+
// is read everywhere. NVDA announces a focused status only as "status bar",
|
|
845
|
+
// without its text (PEX-74, heard with real NVDA and VoiceOver in CI).
|
|
846
|
+
const text = outcome.kind === 'done' ? outcome.result.message : outcome.kind === 'invalid' ? 'Some values need fixing.' : outcome.kind === 'forbidden' ? 'You are not allowed to do this.' : 'Something went wrong. Nothing was changed. Please try again.';
|
|
847
|
+
// A link goes inside the message, so moving focus there reads both.
|
|
848
|
+
const link = outcome.kind === 'done' && outcome.result.link ? html ` <a href="${outcome.result.link.href}">${outcome.result.link.text}</a>` : '';
|
|
849
|
+
const message = html `<p class="px-result" tabindex="-1">${text}${link}</p>`;
|
|
850
|
+
const state = outcome.kind === 'invalid' ? { values: outcome.values, errors: outcome.errors } : { values: input };
|
|
851
|
+
// Px-Form: which copy of this action's form in the region was sent, so only it shows the values.
|
|
852
|
+
const index = Number(ctx.request.headers.get('px-form') ?? '0');
|
|
853
|
+
const form = { action: action.name, index: Number.isInteger(index) && index >= 0 && index < 1000 ? index : 0, state, overrides: outcome.kind !== 'done' };
|
|
854
|
+
const page = ctx.request.headers.get('px-page');
|
|
855
|
+
const region = page === null ? null : await renderRegion(page, ctx, target, form, true);
|
|
856
|
+
if (region === null)
|
|
857
|
+
return fragment(target, status, message);
|
|
858
|
+
// Px-Swap: the reply replaces the whole region, even when it holds no form
|
|
859
|
+
// (a list whose last row was just removed).
|
|
860
|
+
const response = fragment(target, status, html `${message}${raw(region)}`);
|
|
861
|
+
response.headers.set('px-swap', 'region');
|
|
862
|
+
return response;
|
|
665
863
|
}
|
|
666
864
|
async function tooManyRequests(ctx, retryAfter, target = null) {
|
|
667
865
|
const message = `Too many requests. Please wait ${retryAfter} seconds and try again.`;
|
|
@@ -712,7 +910,7 @@ export function createApp(options) {
|
|
|
712
910
|
}
|
|
713
911
|
let input;
|
|
714
912
|
try {
|
|
715
|
-
input = await readActionInput(ctx.request, ctx.url, maxBodyBytes);
|
|
913
|
+
input = await readActionInput(ctx.request, ctx.url, maxBodyBytes, listFields(action));
|
|
716
914
|
}
|
|
717
915
|
catch (error) {
|
|
718
916
|
if (error instanceof BodyError)
|
|
@@ -737,7 +935,15 @@ export function createApp(options) {
|
|
|
737
935
|
fields: Object.keys(input).filter((key) => Object.hasOwn(action.input, key)),
|
|
738
936
|
userAgent: ctx.request.headers.get('user-agent'),
|
|
739
937
|
});
|
|
740
|
-
const
|
|
938
|
+
const back = !viaJson && action.agents === false && outcome.kind === 'done' ? returnPage(ctx) : null;
|
|
939
|
+
const notice = outcome.kind === 'done' ? encodeNotice({ message: outcome.result.message.slice(0, NOTICE_MAX), ...(outcome.result.link ? { link: outcome.result.link } : {}) }) : '';
|
|
940
|
+
const response = back && notice.length <= NOTICE_MAX * 2
|
|
941
|
+
? new Response(null, { status: 303, headers: { location: back, 'set-cookie': noticeCookie(config.origin, notice, 60) } })
|
|
942
|
+
: viaJson
|
|
943
|
+
? actionJson(outcome, ctx)
|
|
944
|
+
: target
|
|
945
|
+
? await actionFragment(action, outcome, ctx, target, input)
|
|
946
|
+
: await actionHtml(action, outcome, ctx);
|
|
741
947
|
// Results can hold personal data (a booking reference, a name): never cached.
|
|
742
948
|
response.headers.set('cache-control', 'no-store');
|
|
743
949
|
return response;
|
|
@@ -780,7 +986,7 @@ export function createApp(options) {
|
|
|
780
986
|
});
|
|
781
987
|
switch (outcome.kind) {
|
|
782
988
|
case 'done':
|
|
783
|
-
return { ok: true, message: outcome.result.message, data: outcome.result.data };
|
|
989
|
+
return { ok: true, message: outcome.result.message, data: outcome.result.data, ...absoluteLink(outcome.result, ctx) };
|
|
784
990
|
case 'invalid':
|
|
785
991
|
return { ok: false, outcome: 'invalid', message: 'Some values need fixing.', errors: outcome.errors };
|
|
786
992
|
case 'forbidden':
|
|
@@ -796,13 +1002,29 @@ export function createApp(options) {
|
|
|
796
1002
|
const route = ctx.route;
|
|
797
1003
|
switch (route.kind) {
|
|
798
1004
|
case 'builtin':
|
|
799
|
-
|
|
1005
|
+
// Each tool says where to send it, so an agent can call it without the page.
|
|
1006
|
+
return json({ tools: registry.list().filter((a) => a.agents !== false).map((a) => ({ ...describeAction(a), url: `/actions/${a.name}`, method: a.method })) });
|
|
800
1007
|
case 'action':
|
|
801
1008
|
return actionResponse(route.action, ctx);
|
|
802
1009
|
case 'route':
|
|
803
1010
|
return pluginRoutes.find((r) => r.method === route.method && r.compiled.path === route.path).handler(ctx);
|
|
804
|
-
case 'page':
|
|
1011
|
+
case 'page': {
|
|
1012
|
+
// A search or filter form that goes to a page, sent in place: the
|
|
1013
|
+
// region alone, as the page renders it for this address. Px-Url tells
|
|
1014
|
+
// the script which address the region now shows, for the address bar.
|
|
1015
|
+
const id = ctx.request.headers.get('px-target');
|
|
1016
|
+
if (id !== null && TARGET_ID.test(id) && ctx.request.method === 'GET' && !wantsJson(ctx)) {
|
|
1017
|
+
const path = ctx.url.pathname + ctx.url.search;
|
|
1018
|
+
const region = await renderRegion(path, ctx, id);
|
|
1019
|
+
if (region !== null) {
|
|
1020
|
+
const response = fragment(id, 200, raw(region));
|
|
1021
|
+
response.headers.set('px-url', path);
|
|
1022
|
+
response.headers.set('px-swap', 'region');
|
|
1023
|
+
return response;
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
805
1026
|
return pageResponse(route.page, ctx);
|
|
1027
|
+
}
|
|
806
1028
|
case 'none': {
|
|
807
1029
|
if (route.allow)
|
|
808
1030
|
return wrongMethod(ctx, route.allow);
|
|
@@ -971,7 +1193,20 @@ export function createApp(options) {
|
|
|
971
1193
|
response = new Response(null, { status: response.status, headers: response.headers });
|
|
972
1194
|
return response;
|
|
973
1195
|
}
|
|
974
|
-
|
|
1196
|
+
function matches(request) {
|
|
1197
|
+
const url = new URL(request.url);
|
|
1198
|
+
const method = request.method === 'HEAD' ? 'GET' : request.method;
|
|
1199
|
+
const { pathname } = applyRewrites(url);
|
|
1200
|
+
const route = matchRoute(method, pathname);
|
|
1201
|
+
if (route.kind !== 'none' || route.allow)
|
|
1202
|
+
return true;
|
|
1203
|
+
// Middleware sees the request as sent, before rewrites.
|
|
1204
|
+
if (answerers.some((answers) => answers(url, method)))
|
|
1205
|
+
return true;
|
|
1206
|
+
// "/menu/" is answered with a redirect to "/menu" when that is a page.
|
|
1207
|
+
return method === 'GET' && pathname.length > 1 && pathname.endsWith('/') && Boolean(matchPage(pathname.replace(/\/+$/, '')));
|
|
1208
|
+
}
|
|
1209
|
+
app = Object.freeze({ fetch, config, pages: orderedPages, actions: registry.list(), entries, checkRules, matches });
|
|
975
1210
|
return app;
|
|
976
1211
|
}
|
|
977
1212
|
/**
|
|
@@ -1000,6 +1235,17 @@ function withoutValues(error, input) {
|
|
|
1000
1235
|
text = text.split(value).join('[value removed]');
|
|
1001
1236
|
return text;
|
|
1002
1237
|
}
|
|
1238
|
+
/**
|
|
1239
|
+
* Declares a plugin: a name and a setup function that receives the plugin
|
|
1240
|
+
* API. Throws when the name is not valid.
|
|
1241
|
+
*
|
|
1242
|
+
* @param plugin Its name, the plugins it requires, and setup.
|
|
1243
|
+
* @example
|
|
1244
|
+
* ```ts
|
|
1245
|
+
* const stylesheet = (href: string) =>
|
|
1246
|
+
* definePlugin({ name: 'stylesheet', setup: (api) => api.head(() => html`<link rel="stylesheet" href="${href}">`) });
|
|
1247
|
+
* ```
|
|
1248
|
+
*/
|
|
1003
1249
|
export function definePlugin(plugin) {
|
|
1004
1250
|
if (!PLUGIN_NAME.test(plugin.name))
|
|
1005
1251
|
throw new Error(`Plugin name "${plugin.name}" is not valid.`);
|