@botiverse/porthole 0.2.4 → 0.3.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.
- package/README.md +14 -9
- package/dist/check/check.d.ts +83 -0
- package/dist/check/check.js +169 -0
- package/dist/check/drivers.d.ts +24 -0
- package/dist/check/drivers.js +110 -0
- package/dist/check/index.d.ts +8 -0
- package/dist/check/index.js +8 -0
- package/dist/check/lint.d.ts +21 -0
- package/dist/check/lint.js +131 -0
- package/dist/check/page-source.d.ts +2 -0
- package/dist/check/page-source.js +2 -0
- package/dist/check/page.d.ts +51 -0
- package/dist/check/page.js +150 -0
- package/dist/check/tools.d.ts +61 -0
- package/dist/check/tools.js +140 -0
- package/dist/conformance/host-kit.d.ts +10 -2
- package/dist/conformance/host-kit.js +9 -2
- package/dist/displays/displays.d.ts +61 -0
- package/dist/displays/displays.js +113 -0
- package/dist/host/client.d.ts +92 -0
- package/dist/host/client.js +259 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +6 -0
- package/dist/node/index.d.ts +22 -1
- package/dist/node/index.js +46 -1
- package/dist/react/frame.d.ts +71 -3
- package/dist/react/frame.js +120 -19
- package/dist/react/index.d.ts +1 -0
- package/dist/react/index.js +1 -0
- package/dist/react/view.d.ts +54 -0
- package/dist/react/view.js +146 -0
- package/dist/server/bootstrap.d.ts +27 -0
- package/dist/server/bootstrap.js +63 -0
- package/dist/server/host.d.ts +74 -7
- package/dist/server/host.js +237 -9
- package/dist/server/index.d.ts +4 -2
- package/dist/server/index.js +3 -1
- package/dist/server/pages.d.ts +19 -0
- package/dist/server/pages.js +8 -0
- package/dist/server/proxy.d.ts +24 -0
- package/dist/server/proxy.js +67 -0
- package/dist/server/server.js +14 -1
- package/dist/server/types.d.ts +8 -0
- package/docs/ADOPTING.md +191 -104
- package/docs/DECISIONS.md +146 -0
- package/docs/DESIGN.md +58 -0
- package/examples/app.mjs +62 -64
- package/examples/conformance/page.spec.mjs +23 -0
- package/examples/conformance/playwright.config.mjs +1 -1
- package/examples/conformance/porthole.spec.mjs +5 -3
- package/examples/displays.mjs +19 -0
- package/examples/mcp/server.mjs +121 -0
- package/package.json +9 -1
- package/src/check/check.ts +278 -0
- package/src/check/drivers.ts +144 -0
- package/src/check/index.ts +15 -0
- package/src/check/lint.ts +238 -0
- package/src/check/page-source.ts +19 -0
- package/src/check/page.ts +204 -0
- package/src/check/tools.ts +206 -0
- package/src/conformance/host-kit.ts +20 -11
- package/src/displays/displays.ts +191 -0
- package/src/host/client.ts +364 -0
- package/src/index.ts +25 -0
- package/src/node/index.ts +66 -2
- package/src/react/frame.tsx +191 -33
- package/src/react/index.ts +8 -0
- package/src/react/view.tsx +232 -0
- package/src/server/bootstrap.ts +97 -0
- package/src/server/host.ts +331 -15
- package/src/server/index.ts +11 -1
- package/src/server/pages.ts +28 -0
- package/src/server/proxy.ts +86 -0
- package/src/server/server.ts +26 -2
- package/src/server/types.ts +5 -0
package/dist/react/frame.js
CHANGED
|
@@ -18,6 +18,21 @@ export const PLACEHOLDER_HEIGHT_PX = 96;
|
|
|
18
18
|
/** Without a provider: one registry for the page, and no one to confirm (gated calls refused). */
|
|
19
19
|
const PAGE = { live: createLiveFrames(), heights: new Map() };
|
|
20
20
|
const Page = createContext(PAGE);
|
|
21
|
+
/** The provider's page state, for the binding's other components (`PortholeView`). */
|
|
22
|
+
export const PortholeContext = Page;
|
|
23
|
+
/** The page's own nonce: `<meta name="csp-nonce" content>`, else the first `script[nonce]`'s. */
|
|
24
|
+
function pageNonce() {
|
|
25
|
+
if (typeof document === "undefined") {
|
|
26
|
+
return undefined;
|
|
27
|
+
}
|
|
28
|
+
const meta = document.querySelector('meta[name="csp-nonce"]')?.content;
|
|
29
|
+
const script = document.querySelector("script[nonce]")?.nonce;
|
|
30
|
+
return meta !== undefined && meta !== ""
|
|
31
|
+
? meta
|
|
32
|
+
: script !== undefined && script !== ""
|
|
33
|
+
? script
|
|
34
|
+
: undefined;
|
|
35
|
+
}
|
|
21
36
|
export function PortholeProvider(props) {
|
|
22
37
|
const live = useMemo(() => createLiveFrames(), []);
|
|
23
38
|
const heights = useMemo(() => new Map(), []);
|
|
@@ -33,9 +48,19 @@ export function PortholeProvider(props) {
|
|
|
33
48
|
// The default copyText: the host's page writes the clipboard (in the frame's click, which
|
|
34
49
|
// activated this page too) and shows the person what went on it, or offers to copy it.
|
|
35
50
|
const [notice, setNotice] = useState(null);
|
|
51
|
+
const ownNotify = useRef(props.notify);
|
|
52
|
+
useLayoutEffect(() => {
|
|
53
|
+
ownNotify.current = props.notify;
|
|
54
|
+
});
|
|
36
55
|
const copyText = useCallback(async ({ text }, context) => {
|
|
37
56
|
const copied = await writeClipboard(text, globalThis.document);
|
|
38
|
-
|
|
57
|
+
const said = { text, copied, title: context.title };
|
|
58
|
+
if (ownNotify.current === undefined) {
|
|
59
|
+
setNotice(said);
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
ownNotify.current(said, { copy: () => writeClipboard(text, globalThis.document) });
|
|
63
|
+
}
|
|
39
64
|
return copied;
|
|
40
65
|
}, []);
|
|
41
66
|
const closeNotice = useCallback(() => setNotice(null), []);
|
|
@@ -46,11 +71,41 @@ export function PortholeProvider(props) {
|
|
|
46
71
|
useLayoutEffect(() => {
|
|
47
72
|
ownLocator.current = props.locator;
|
|
48
73
|
});
|
|
49
|
-
const
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
const
|
|
74
|
+
const ownClient = useRef(props.client);
|
|
75
|
+
useLayoutEffect(() => {
|
|
76
|
+
ownClient.current = props.client;
|
|
77
|
+
});
|
|
78
|
+
const locate = useCallback((instance, signal) => ownLocator.current !== undefined
|
|
79
|
+
? ownLocator.current.locate(instance, signal)
|
|
80
|
+
: ownClient.current !== undefined
|
|
81
|
+
? ownClient.current.locate(instance, signal)
|
|
82
|
+
: Promise.reject(new Error("No locator (PortholeProvider.locator or client)")), []);
|
|
83
|
+
const locates = props.locator !== undefined || props.client !== undefined;
|
|
84
|
+
// `"auto"`: the page's own nonce, read once.
|
|
85
|
+
const [autoNonce] = useState(() => (props.nonce === "auto" ? pageNonce() : undefined));
|
|
86
|
+
const nonce = props.nonce === "auto" ? autoNonce : props.nonce;
|
|
87
|
+
const { client, scheme, theme, themeKey } = props;
|
|
88
|
+
// openLink without a frame handler: the provider's, or a new tab.
|
|
89
|
+
const ownOpen = useRef(props.openLink);
|
|
90
|
+
useLayoutEffect(() => {
|
|
91
|
+
ownOpen.current = props.openLink;
|
|
92
|
+
});
|
|
93
|
+
const handlers = useMemo(() => ({
|
|
94
|
+
openLink: ({ url }) => {
|
|
95
|
+
if (ownOpen.current === undefined) {
|
|
96
|
+
globalThis.open?.(url, "_blank", "noopener");
|
|
97
|
+
}
|
|
98
|
+
else {
|
|
99
|
+
ownOpen.current(url);
|
|
100
|
+
}
|
|
101
|
+
return true;
|
|
102
|
+
},
|
|
103
|
+
}), []);
|
|
104
|
+
const ownHandlers = useRef(props.handlers);
|
|
105
|
+
useLayoutEffect(() => {
|
|
106
|
+
ownHandlers.current = props.handlers;
|
|
107
|
+
});
|
|
108
|
+
const merged = useCallback(() => ({ ...handlers, ...ownHandlers.current }), [handlers]);
|
|
54
109
|
const value = useMemo(() => ({
|
|
55
110
|
live,
|
|
56
111
|
heights,
|
|
@@ -59,19 +114,51 @@ export function PortholeProvider(props) {
|
|
|
59
114
|
...(hostInfo === undefined ? {} : { hostInfo }),
|
|
60
115
|
...(locates ? { locate } : {}),
|
|
61
116
|
...(nonce === undefined ? {} : { nonce }),
|
|
62
|
-
|
|
117
|
+
...(client === undefined ? {} : { client }),
|
|
118
|
+
...(scheme === undefined ? {} : { scheme }),
|
|
119
|
+
...(theme === undefined ? {} : { theme }),
|
|
120
|
+
...(themeKey === undefined ? {} : { themeKey }),
|
|
121
|
+
handlers: merged,
|
|
122
|
+
}), [
|
|
123
|
+
live,
|
|
124
|
+
heights,
|
|
125
|
+
confirm,
|
|
126
|
+
copyText,
|
|
127
|
+
hostInfo,
|
|
128
|
+
locates,
|
|
129
|
+
locate,
|
|
130
|
+
nonce,
|
|
131
|
+
client,
|
|
132
|
+
scheme,
|
|
133
|
+
theme,
|
|
134
|
+
themeKey,
|
|
135
|
+
merged,
|
|
136
|
+
]);
|
|
63
137
|
const current = queue[0] ?? null;
|
|
64
|
-
return (_jsxs(Page.Provider, { value: value, children: [props.children, props.confirm === undefined
|
|
138
|
+
return (_jsxs(Page.Provider, { value: value, children: [props.children, props.confirm === undefined && props.renderConfirm !== undefined && current !== null
|
|
139
|
+
? props.renderConfirm(current.request, {
|
|
140
|
+
accept: () => {
|
|
141
|
+
// Inside the app's own click: the effect is the person's (a window it opens).
|
|
142
|
+
current.proceed();
|
|
143
|
+
current.resolve("accepted");
|
|
144
|
+
setQueue((waiting) => waiting.slice(1));
|
|
145
|
+
},
|
|
146
|
+
decline: () => {
|
|
147
|
+
current.resolve("declined");
|
|
148
|
+
setQueue((waiting) => waiting.slice(1));
|
|
149
|
+
},
|
|
150
|
+
})
|
|
151
|
+
: null, props.confirm === undefined && props.renderConfirm === undefined ? (_jsx(ConfirmDialog, { request: current?.request ?? null, ...(props.dialogClassName === undefined ? {} : { className: props.dialogClassName }), onAnswer: (accepted) => {
|
|
65
152
|
// A yes runs the effect inside this very click (a window it opens is the person's).
|
|
66
153
|
if (accepted) {
|
|
67
154
|
current?.proceed();
|
|
68
155
|
}
|
|
69
156
|
current?.resolve(accepted ? "accepted" : "declined");
|
|
70
157
|
setQueue((waiting) => waiting.slice(1));
|
|
71
|
-
} })) : null, _jsx(CopyToast, { notice: notice, ...(props.toastClassName === undefined ? {} : { className: props.toastClassName }), onClose: closeNotice, onCopy: (failed) => {
|
|
158
|
+
} })) : null, props.notify !== undefined ? null : (_jsx(CopyToast, { notice: notice, ...(props.toastClassName === undefined ? {} : { className: props.toastClassName }), onClose: closeNotice, onCopy: (failed) => {
|
|
72
159
|
// A click on the host's own page: the write has the gesture it needs now.
|
|
73
160
|
void writeClipboard(failed.text, globalThis.document).then((copied) => setNotice({ ...failed, copied }));
|
|
74
|
-
} })] }));
|
|
161
|
+
} }))] }));
|
|
75
162
|
}
|
|
76
163
|
const PLACEHOLDER_STYLE = {
|
|
77
164
|
position: "absolute",
|
|
@@ -163,7 +250,10 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
|
|
|
163
250
|
const [ready, setReady] = useState(false);
|
|
164
251
|
// The height this display started at: later reports don't make it start again.
|
|
165
252
|
const [startHeight] = useState(initialHeightPx);
|
|
166
|
-
const { document: view, content, partial
|
|
253
|
+
const { document: view, content, partial } = frame;
|
|
254
|
+
const scheme = frame.scheme ?? page.scheme ?? "light";
|
|
255
|
+
// A run's content errors, told once each (a loop throwing the same error says it once).
|
|
256
|
+
const told = useRef(new Set());
|
|
167
257
|
// By value: a config or instance made inline (each render) is the same display.
|
|
168
258
|
const config = useByValue(frame.config);
|
|
169
259
|
const instance = useByValue(frame.instance);
|
|
@@ -182,9 +272,14 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
|
|
|
182
272
|
frame.onResize?.(size);
|
|
183
273
|
return;
|
|
184
274
|
}
|
|
185
|
-
case "contentError":
|
|
186
|
-
|
|
275
|
+
case "contentError": {
|
|
276
|
+
const { message } = detail;
|
|
277
|
+
if (!told.current.has(message)) {
|
|
278
|
+
told.current.add(message);
|
|
279
|
+
frame.onContentError?.(message);
|
|
280
|
+
}
|
|
187
281
|
return;
|
|
282
|
+
}
|
|
188
283
|
case "hostError":
|
|
189
284
|
frame.onHostError?.(detail);
|
|
190
285
|
return;
|
|
@@ -225,10 +320,16 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
|
|
|
225
320
|
displayId: latest().displayId,
|
|
226
321
|
title: latest().title,
|
|
227
322
|
});
|
|
228
|
-
// The handlers present now (a declared one must be), each calling the latest prop's
|
|
323
|
+
// The handlers present now (a declared one must be), each calling the latest prop's, else
|
|
324
|
+
// the provider's (P072).
|
|
229
325
|
const handlers = {};
|
|
230
|
-
|
|
231
|
-
|
|
326
|
+
const declared = new Set(Object.keys(config.capabilities));
|
|
327
|
+
for (const name of new Set([
|
|
328
|
+
...Object.keys(first.handlers ?? {}),
|
|
329
|
+
...Object.keys(page.handlers?.() ?? {}).filter((each) => declared.has(each)),
|
|
330
|
+
])) {
|
|
331
|
+
handlers[name] = (args, context) => (latest().handlers?.[name] ??
|
|
332
|
+
page.handlers?.()?.[name])?.(args, named(context));
|
|
232
333
|
}
|
|
233
334
|
// Copy buttons without a handler of the host's: the provider's, which shows a toast.
|
|
234
335
|
if (config.capabilities.copyText !== undefined && handlers.copyText === undefined) {
|
|
@@ -247,14 +348,14 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
|
|
|
247
348
|
confirm: (request, proceed) => (latest().confirm ?? page.confirm ?? (() => Promise.resolve(false)))({ ...request, display: { id: latest().displayId, title: latest().title } }, proceed),
|
|
248
349
|
}
|
|
249
350
|
: {}),
|
|
250
|
-
theme: (each) => latest().theme?.(each) ?? {},
|
|
351
|
+
theme: (each) => (latest().theme ?? page.theme)?.(each) ?? {},
|
|
251
352
|
...(page.hostInfo === undefined ? {} : { hostInfo: page.hostInfo }),
|
|
252
353
|
...(page.locate === undefined ? {} : { locator: { locate: page.locate } }),
|
|
253
354
|
...(page.nonce === undefined ? {} : { nonce: page.nonce }),
|
|
254
355
|
}).mount(container, {
|
|
255
356
|
displayId: first.displayId,
|
|
256
357
|
title: first.title,
|
|
257
|
-
scheme: first.scheme,
|
|
358
|
+
scheme: first.scheme ?? page.scheme ?? "light",
|
|
258
359
|
initialHeightPx: startHeight,
|
|
259
360
|
...(view === undefined ? {} : { document: view }),
|
|
260
361
|
...(instance === undefined ? {} : { instance }),
|
|
@@ -345,7 +446,7 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
|
|
|
345
446
|
handle.current?.setTheme(scheme);
|
|
346
447
|
}
|
|
347
448
|
}, [scheme, mountScheme]);
|
|
348
|
-
const
|
|
449
|
+
const themeKey = frame.themeKey ?? page.themeKey;
|
|
349
450
|
const [mountThemeKey] = useState(themeKey);
|
|
350
451
|
useEffect(() => {
|
|
351
452
|
if (themeKey !== undefined && themeKey !== mountThemeKey) {
|
package/dist/react/index.d.ts
CHANGED
|
@@ -10,5 +10,6 @@
|
|
|
10
10
|
*/
|
|
11
11
|
export { PLACEHOLDER_HEIGHT_PX, PortholeFrame, PortholeProvider, type PlaceholderProps, type PortholeFrameProps, type PortholeProviderProps, } from "./frame.tsx";
|
|
12
12
|
export { ARM_DELAY_MS, ConfirmDialog, type ConfirmDialogProps } from "./dialog.tsx";
|
|
13
|
+
export { cssVariableTheme, PortholeView, usePortholeLink, useRunAgain, type PortholeFallbackProps, type PortholeViewProps, } from "./view.tsx";
|
|
13
14
|
export { CopyToast, TOAST_CHARS, TOAST_MS, clipped, type CopyNotice, type CopyToastProps, } from "./toast.tsx";
|
|
14
15
|
export { admitFrame, createLiveFrames, type FrameState, type LiveFrames } from "./live.ts";
|
package/dist/react/index.js
CHANGED
|
@@ -10,5 +10,6 @@
|
|
|
10
10
|
*/
|
|
11
11
|
export { PLACEHOLDER_HEIGHT_PX, PortholeFrame, PortholeProvider, } from "./frame.js";
|
|
12
12
|
export { ARM_DELAY_MS, ConfirmDialog } from "./dialog.js";
|
|
13
|
+
export { cssVariableTheme, PortholeView, usePortholeLink, useRunAgain, } from "./view.js";
|
|
13
14
|
export { CopyToast, TOAST_CHARS, TOAST_MS, clipped, } from "./toast.js";
|
|
14
15
|
export { admitFrame, createLiveFrames } from "./live.js";
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { type ReactElement, type ReactNode } from "react";
|
|
2
|
+
import type { ColorScheme } from "../config/schema.ts";
|
|
3
|
+
import { type FrameFallback } from "../host/client.ts";
|
|
4
|
+
import type { InstanceRef } from "../isolation/types.ts";
|
|
5
|
+
import { type PortholeFrameProps } from "./frame.tsx";
|
|
6
|
+
/**
|
|
7
|
+
* The host kit's React side (P072): a display by its kind, served or opaque as the server says
|
|
8
|
+
* now, located through the provider's client, with a fallback when its frame shows nothing.
|
|
9
|
+
*
|
|
10
|
+
* <PortholeProvider client={porthole} scheme={mode}>
|
|
11
|
+
* <PortholeView display="page" instance={instance} content={opaqueCopy}
|
|
12
|
+
* fallback={({ title, message, link, retry }) => <Fallback … />} />
|
|
13
|
+
* </PortholeProvider>
|
|
14
|
+
*/
|
|
15
|
+
/** What a fallback is drawn from: why the frame showed nothing, its clean address, a retry. */
|
|
16
|
+
export interface PortholeFallbackProps extends FrameFallback {
|
|
17
|
+
/** The instance's clean address (its "open in a new tab"), or null. */
|
|
18
|
+
readonly link: string | null;
|
|
19
|
+
/** Shows the display again. */
|
|
20
|
+
readonly retry: () => void;
|
|
21
|
+
}
|
|
22
|
+
export interface PortholeViewProps extends Omit<PortholeFrameProps, "config" | "instance" | "content" | "fill"> {
|
|
23
|
+
/** The display kind (`defineDisplays`). */
|
|
24
|
+
readonly display: string;
|
|
25
|
+
/** The instance to show while frames are served. */
|
|
26
|
+
readonly instance?: InstanceRef;
|
|
27
|
+
/**
|
|
28
|
+
* The content: a served shell's to draw, and what an opaque frame shows while frames aren't
|
|
29
|
+
* served (a stored page's HTML). Without it, a served-only display shows the fallback then.
|
|
30
|
+
*/
|
|
31
|
+
readonly content?: string;
|
|
32
|
+
/** Drawn instead of the frame when it showed nothing. Default: a line and a link. */
|
|
33
|
+
readonly fallback?: (props: PortholeFallbackProps) => ReactNode;
|
|
34
|
+
/** Drawn while the server's meta isn't known yet. */
|
|
35
|
+
readonly pending?: ReactNode;
|
|
36
|
+
}
|
|
37
|
+
export declare function PortholeView(props: PortholeViewProps): ReactElement | null;
|
|
38
|
+
/** An instance's clean address, and its "open in a new tab" and "copy link" (P072). */
|
|
39
|
+
export declare function usePortholeLink(instance: InstanceRef | null): {
|
|
40
|
+
readonly link: string | null;
|
|
41
|
+
readonly open: () => void;
|
|
42
|
+
readonly copy: () => Promise<boolean>;
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Theme values read from the page's own CSS variables (P072): `tokens` maps each of Porthole's
|
|
46
|
+
* theme variables to the app's (`{ "--color-text-primary": "--app-fg" }`). Read when a frame asks,
|
|
47
|
+
* so pass `themeKey` to re-read after the app's theme changes.
|
|
48
|
+
*/
|
|
49
|
+
export declare function cssVariableTheme(tokens: Readonly<Record<string, string>>, root?: () => Element): (scheme: ColorScheme) => Record<string, string>;
|
|
50
|
+
/** A display's "run again": pass `generation` to the frame, call `runAgain` from a button. */
|
|
51
|
+
export declare function useRunAgain(): {
|
|
52
|
+
readonly generation: number;
|
|
53
|
+
readonly runAgain: () => void;
|
|
54
|
+
};
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { useCallback, useContext, useEffect, useState, useSyncExternalStore, } from "react";
|
|
3
|
+
import { frameFallback } from "../host/client.js";
|
|
4
|
+
import { PortholeFrame, PortholeContext } from "./frame.js";
|
|
5
|
+
function useClient() {
|
|
6
|
+
const client = useContext(PortholeContext).client;
|
|
7
|
+
if (client === undefined) {
|
|
8
|
+
throw new Error("PortholeView needs a PortholeProvider with a client (portholeClient)");
|
|
9
|
+
}
|
|
10
|
+
return client;
|
|
11
|
+
}
|
|
12
|
+
/** The client's meta, as a React value (re-renders when frames start or stop being served). */
|
|
13
|
+
function useMeta(client) {
|
|
14
|
+
return useSyncExternalStore((listener) => client.subscribe(listener), () => client.meta(), () => null);
|
|
15
|
+
}
|
|
16
|
+
function DefaultFallback({ title, message, link }) {
|
|
17
|
+
return (_jsxs("div", { "data-porthole-fallback": "", role: "status", style: { padding: 16 }, children: [_jsx("strong", { children: title }), " ", _jsx("span", { children: message }), " ", link === null ? null : (_jsx("a", { href: link, target: "_blank", rel: "noopener", children: "Open in a new tab" }))] }));
|
|
18
|
+
}
|
|
19
|
+
export function PortholeView(props) {
|
|
20
|
+
const client = useClient();
|
|
21
|
+
const meta = useMeta(client);
|
|
22
|
+
const { display, instance, content, fallback, pending, onOutcome, ...frame } = props;
|
|
23
|
+
const [failed, setFailed] = useState(null);
|
|
24
|
+
const [generation, setGeneration] = useState(0);
|
|
25
|
+
const [link, setLink] = useState(null);
|
|
26
|
+
const kind = display;
|
|
27
|
+
const config = client.config(kind);
|
|
28
|
+
const served = meta?.served === true && config?.isolation !== "opaque";
|
|
29
|
+
const url = config?.mode === "url";
|
|
30
|
+
const retry = useCallback(() => {
|
|
31
|
+
setFailed(null);
|
|
32
|
+
setGeneration((each) => each + 1);
|
|
33
|
+
}, []);
|
|
34
|
+
useEffect(() => {
|
|
35
|
+
if (failed === null || instance === undefined) {
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
let live = true;
|
|
39
|
+
void client.link(instance).then((found) => {
|
|
40
|
+
if (live) {
|
|
41
|
+
setLink(found);
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
return () => {
|
|
45
|
+
live = false;
|
|
46
|
+
};
|
|
47
|
+
}, [client, failed, instance]);
|
|
48
|
+
if (meta === null || config === null) {
|
|
49
|
+
// Not known yet; or a url kind while frames aren't served.
|
|
50
|
+
if (meta !== null && config === null) {
|
|
51
|
+
const said = {
|
|
52
|
+
kind: "failed",
|
|
53
|
+
title: "This can't be shown now",
|
|
54
|
+
message: "Its content isn't being served.",
|
|
55
|
+
};
|
|
56
|
+
return _jsx(_Fragment, { children: (fallback ?? DefaultFallback)({ ...said, link: null, retry }) });
|
|
57
|
+
}
|
|
58
|
+
return _jsx(_Fragment, { children: pending ?? null });
|
|
59
|
+
}
|
|
60
|
+
if (!served && content === undefined) {
|
|
61
|
+
const said = {
|
|
62
|
+
kind: "failed",
|
|
63
|
+
title: "This can't be shown now",
|
|
64
|
+
message: "Its content isn't being served.",
|
|
65
|
+
};
|
|
66
|
+
return _jsx(_Fragment, { children: (fallback ?? DefaultFallback)({ ...said, link: null, retry }) });
|
|
67
|
+
}
|
|
68
|
+
if (failed !== null) {
|
|
69
|
+
return _jsx(_Fragment, { children: (fallback ?? DefaultFallback)({ ...failed, link, retry }) });
|
|
70
|
+
}
|
|
71
|
+
return (_jsx(PortholeFrame, { ...frame, config: config, generation: (frame.generation ?? 0) + generation, ...(served && instance !== undefined ? { instance } : {}), ...(content === undefined ? {} : { content }), onOutcome: (outcome) => {
|
|
72
|
+
onOutcome?.(outcome);
|
|
73
|
+
const said = frameFallback(outcome, { url });
|
|
74
|
+
if (said !== null) {
|
|
75
|
+
setFailed(said);
|
|
76
|
+
}
|
|
77
|
+
} }));
|
|
78
|
+
}
|
|
79
|
+
/** An instance's clean address, and its "open in a new tab" and "copy link" (P072). */
|
|
80
|
+
export function usePortholeLink(instance) {
|
|
81
|
+
const client = useClient();
|
|
82
|
+
const key = instance === null ? "" : JSON.stringify(instance);
|
|
83
|
+
// The address found for the instance it was found for: another instance shows none until its own.
|
|
84
|
+
const [found, setFound] = useState(() => ({ key, link: instance === null ? null : client.knownLink(instance) }));
|
|
85
|
+
useEffect(() => {
|
|
86
|
+
if (key === "") {
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
let live = true;
|
|
90
|
+
void client.link(JSON.parse(key)).then((each) => {
|
|
91
|
+
if (live) {
|
|
92
|
+
setFound({ key, link: each });
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
return () => {
|
|
96
|
+
live = false;
|
|
97
|
+
};
|
|
98
|
+
}, [client, key]);
|
|
99
|
+
const link = found.key === key ? found.link : null;
|
|
100
|
+
const open = useCallback(() => {
|
|
101
|
+
if (key !== "") {
|
|
102
|
+
client.openInTab(JSON.parse(key));
|
|
103
|
+
}
|
|
104
|
+
}, [client, key]);
|
|
105
|
+
const copy = useCallback(async () => {
|
|
106
|
+
if (link === null) {
|
|
107
|
+
return false;
|
|
108
|
+
}
|
|
109
|
+
try {
|
|
110
|
+
await navigator.clipboard.writeText(link);
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
return false;
|
|
115
|
+
}
|
|
116
|
+
}, [link]);
|
|
117
|
+
return { link, open, copy };
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Theme values read from the page's own CSS variables (P072): `tokens` maps each of Porthole's
|
|
121
|
+
* theme variables to the app's (`{ "--color-text-primary": "--app-fg" }`). Read when a frame asks,
|
|
122
|
+
* so pass `themeKey` to re-read after the app's theme changes.
|
|
123
|
+
*/
|
|
124
|
+
export function cssVariableTheme(tokens, root) {
|
|
125
|
+
return () => {
|
|
126
|
+
const element = root?.() ?? globalThis.document?.documentElement;
|
|
127
|
+
if (element === undefined) {
|
|
128
|
+
return {};
|
|
129
|
+
}
|
|
130
|
+
const style = getComputedStyle(element);
|
|
131
|
+
const values = {};
|
|
132
|
+
for (const [ours, theirs] of Object.entries(tokens)) {
|
|
133
|
+
const value = style.getPropertyValue(theirs).trim();
|
|
134
|
+
if (value !== "") {
|
|
135
|
+
values[ours] = value;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return values;
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
/** A display's "run again": pass `generation` to the frame, call `runAgain` from a button. */
|
|
142
|
+
export function useRunAgain() {
|
|
143
|
+
const [generation, setGeneration] = useState(0);
|
|
144
|
+
const runAgain = useCallback(() => setGeneration((each) => each + 1), []);
|
|
145
|
+
return { generation, runAgain };
|
|
146
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type ContentHost, type ContentHostOptions } from "./host.ts";
|
|
2
|
+
/**
|
|
3
|
+
* The host kit on a runtime that hands each request its settings (Cloudflare Workers' `env`)
|
|
4
|
+
* (P072): one content host per settings object, made on first use. Settings that can't be served
|
|
5
|
+
* fail closed: every request is a plain 503 naming why, told to the log once.
|
|
6
|
+
*
|
|
7
|
+
* const porthole = contentHostFor((env) => ({ domain: env.CONTENT_DOMAIN, secret: env.PORTHOLE_SECRET, … }));
|
|
8
|
+
* export default {
|
|
9
|
+
* async fetch(request, env) {
|
|
10
|
+
* return (await porthole.fetch(request, env)) ?? app.fetch(request, env);
|
|
11
|
+
* },
|
|
12
|
+
* };
|
|
13
|
+
*/
|
|
14
|
+
export interface ContentHostFor<E extends object, V> {
|
|
15
|
+
/** The content host for these settings; throws, naming why, where they can't be served. */
|
|
16
|
+
host(env: E): ContentHost<V>;
|
|
17
|
+
/**
|
|
18
|
+
* The content domain's answer for a request (`ContentHost.fetch`), or null for the app's own;
|
|
19
|
+
* a plain 503 for every request while the settings can't be served.
|
|
20
|
+
*/
|
|
21
|
+
fetch(request: Request, env: E): Promise<Response | null>;
|
|
22
|
+
/** `ContentHost.routes`, for these settings. */
|
|
23
|
+
routes(request: Request, env: E, viewerOf: (request: Request) => V | null | Promise<V | null>): Promise<Response | null>;
|
|
24
|
+
}
|
|
25
|
+
export declare function contentHostFor<E extends object, V>(build: (env: E) => ContentHostOptions<V>, options?: {
|
|
26
|
+
readonly log?: (problem: string) => void;
|
|
27
|
+
}): ContentHostFor<E, V>;
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { createContentHost } from "./host.js";
|
|
2
|
+
/** Why the content host can't be made for some settings. */
|
|
3
|
+
class Unservable extends Error {
|
|
4
|
+
name = "ContentHostUnservable";
|
|
5
|
+
}
|
|
6
|
+
export function contentHostFor(build, options = {}) {
|
|
7
|
+
const made = new WeakMap();
|
|
8
|
+
const hostOf = (env) => {
|
|
9
|
+
let found = made.get(env);
|
|
10
|
+
if (found === undefined) {
|
|
11
|
+
try {
|
|
12
|
+
found = createContentHost(build(env));
|
|
13
|
+
}
|
|
14
|
+
catch (error) {
|
|
15
|
+
found = new Unservable(`the content domain can't be served: ${error instanceof Error ? error.message : String(error)}`);
|
|
16
|
+
(options.log ?? (() => { }))(found.message);
|
|
17
|
+
}
|
|
18
|
+
made.set(env, found);
|
|
19
|
+
}
|
|
20
|
+
if (found instanceof Unservable) {
|
|
21
|
+
throw found;
|
|
22
|
+
}
|
|
23
|
+
return found;
|
|
24
|
+
};
|
|
25
|
+
const unavailable = (error) => new Response(`Unavailable: ${error.message}.`, {
|
|
26
|
+
status: 503,
|
|
27
|
+
headers: {
|
|
28
|
+
"content-type": "text/plain; charset=utf-8",
|
|
29
|
+
"cache-control": "no-store",
|
|
30
|
+
"x-content-type-options": "nosniff",
|
|
31
|
+
"x-robots-tag": "noindex, nofollow",
|
|
32
|
+
},
|
|
33
|
+
});
|
|
34
|
+
return {
|
|
35
|
+
host: hostOf,
|
|
36
|
+
async fetch(request, env) {
|
|
37
|
+
let host;
|
|
38
|
+
try {
|
|
39
|
+
host = hostOf(env);
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
if (error instanceof Unservable) {
|
|
43
|
+
return unavailable(error);
|
|
44
|
+
}
|
|
45
|
+
throw error;
|
|
46
|
+
}
|
|
47
|
+
return host.fetch(request);
|
|
48
|
+
},
|
|
49
|
+
async routes(request, env, viewerOf) {
|
|
50
|
+
let host;
|
|
51
|
+
try {
|
|
52
|
+
host = hostOf(env);
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
if (error instanceof Unservable) {
|
|
56
|
+
return unavailable(error);
|
|
57
|
+
}
|
|
58
|
+
throw error;
|
|
59
|
+
}
|
|
60
|
+
return host.routes(viewerOf)(request);
|
|
61
|
+
},
|
|
62
|
+
};
|
|
63
|
+
}
|
package/dist/server/host.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { PortholeConfig } from "../config/schema.ts";
|
|
2
2
|
import type { InstanceRef } from "../isolation/types.ts";
|
|
3
|
+
import type { Displays } from "../displays/displays.ts";
|
|
4
|
+
import type { ContentClientMeta } from "../host/client.ts";
|
|
3
5
|
import { type ContentDomainInfo } from "./domain.ts";
|
|
4
6
|
import { type Naming } from "./naming.ts";
|
|
5
7
|
import type { Access, ArtifactStore, AuthorizeAnswer, AuthorizeRequest, Grant, PortholeServer, TicketStore, Upstream } from "./types.ts";
|
|
@@ -27,6 +29,11 @@ export interface HealthOptions {
|
|
|
27
29
|
* its clients whether frames are served pushes it from here.
|
|
28
30
|
*/
|
|
29
31
|
readonly onChange?: (view: ContentHealthView) => void;
|
|
32
|
+
/**
|
|
33
|
+
* Told when frames start or stop being served (P072): `meta().served` flipped. Deduplicated:
|
|
34
|
+
* once per flip, not per check.
|
|
35
|
+
*/
|
|
36
|
+
readonly onServedChange?: (served: boolean) => void;
|
|
30
37
|
}
|
|
31
38
|
/** Where content stands, for the app's own meta and logs. */
|
|
32
39
|
export interface ContentHealthView {
|
|
@@ -54,6 +61,13 @@ export interface ContentMeta {
|
|
|
54
61
|
readonly contentSource: string | null;
|
|
55
62
|
readonly health: ContentHealthView | null;
|
|
56
63
|
}
|
|
64
|
+
export type { ContentClientMeta } from "../host/client.ts";
|
|
65
|
+
/** A logger (pino, console, winston): the kit's events at their level (P072). */
|
|
66
|
+
export interface ContentLogger {
|
|
67
|
+
readonly info?: (message: string, event: ContentHostEvent) => void;
|
|
68
|
+
readonly warn?: (message: string, event: ContentHostEvent) => void;
|
|
69
|
+
readonly error?: (message: string, event: ContentHostEvent) => void;
|
|
70
|
+
}
|
|
57
71
|
type Awaitable<T> = T | Promise<T>;
|
|
58
72
|
export interface ContentHostOptions<V> {
|
|
59
73
|
/** `content.example.com`, `content.localhost:8790`; empty: content off. Or parsed settings. */
|
|
@@ -63,8 +77,18 @@ export interface ContentHostOptions<V> {
|
|
|
63
77
|
/** At least 32 random bytes (or a string of at least 32 bytes). */
|
|
64
78
|
readonly secret: Uint8Array | string;
|
|
65
79
|
readonly tickets?: TicketStore;
|
|
66
|
-
/**
|
|
67
|
-
|
|
80
|
+
/**
|
|
81
|
+
* The configs content is served under, given the content source (`https://*.<domain>`). Or
|
|
82
|
+
* `displays` (P072), which says it for every kind once.
|
|
83
|
+
*/
|
|
84
|
+
readonly configs?: Readonly<Record<string, PortholeConfig>> | ((source: string) => Readonly<Record<string, PortholeConfig>>);
|
|
85
|
+
/** The app's display kinds (`defineDisplays`): their served configs, in place of `configs`. */
|
|
86
|
+
readonly displays?: Displays;
|
|
87
|
+
/**
|
|
88
|
+
* Where `routes` answers on the app's origin (P072): `<prefix>/frames`, `/authorize`, `/meta`,
|
|
89
|
+
* `/handoff`. Default `/porthole`.
|
|
90
|
+
*/
|
|
91
|
+
readonly prefix?: string;
|
|
68
92
|
/**
|
|
69
93
|
* How a scope is named (`prefixedName("a-")`); default: keyed labels. Redirect entry needs one
|
|
70
94
|
* that says which scope a label names (`prefixedName` does).
|
|
@@ -104,7 +128,8 @@ export interface ContentHostOptions<V> {
|
|
|
104
128
|
readonly perMinute: number;
|
|
105
129
|
readonly key?: (request: Request, viewer: V | null) => string;
|
|
106
130
|
};
|
|
107
|
-
|
|
131
|
+
/** The kit's events: a function, or a logger (`{ info, warn, error }`). */
|
|
132
|
+
readonly log?: ((event: ContentHostEvent) => void) | ContentLogger;
|
|
108
133
|
/**
|
|
109
134
|
* Redirect entry (P068): clean addresses (`urlOf`) that open directly, in a new tab, on a
|
|
110
135
|
* reload, from a bookmark or a link someone with access was sent. Without a cookie, the content
|
|
@@ -114,8 +139,11 @@ export interface ContentHostOptions<V> {
|
|
|
114
139
|
readonly entry?: EntryOptions<V>;
|
|
115
140
|
}
|
|
116
141
|
export interface EntryOptions<V> {
|
|
117
|
-
/**
|
|
118
|
-
|
|
142
|
+
/**
|
|
143
|
+
* The app's authorize route (`ContentHost.authorize`), an absolute URL on an app origin.
|
|
144
|
+
* Default: `<first app origin><prefix>/authorize`, where `routes` answers it.
|
|
145
|
+
*/
|
|
146
|
+
readonly authorizeUrl?: string;
|
|
119
147
|
/**
|
|
120
148
|
* Policy 1 for a clean address: the instance a scope's path means, or null/undefined: nothing
|
|
121
149
|
* (404). The path is the address's pathname; its query rides along but never chooses the
|
|
@@ -130,7 +158,30 @@ export interface EntryOptions<V> {
|
|
|
130
158
|
* Only ever on a tab: in a frame, the person is asked to open a new tab instead. `entry` is the
|
|
131
159
|
* address being opened, decoded (P070).
|
|
132
160
|
*/
|
|
133
|
-
readonly signIn
|
|
161
|
+
readonly signIn?: (returnTo: string, request: Request, entry: EntryContext) => Awaitable<Response>;
|
|
162
|
+
/**
|
|
163
|
+
* A single-page app's sign-in route (P072): the default `signIn` sends the person there with
|
|
164
|
+
* `?next=<authorize URL>`, and the app goes on to `next` once signed in (check it with
|
|
165
|
+
* `entryTarget`).
|
|
166
|
+
*/
|
|
167
|
+
readonly spa?: {
|
|
168
|
+
readonly route: string;
|
|
169
|
+
};
|
|
170
|
+
/**
|
|
171
|
+
* The clean path of an instance (the reverse of `at`), or null: `issue` then answers its clean
|
|
172
|
+
* address as `link` (P072), for "open in a new tab" and "copy link".
|
|
173
|
+
*/
|
|
174
|
+
readonly pathOf?: (instance: InstanceRef) => string | null;
|
|
175
|
+
/**
|
|
176
|
+
* A viewer handoff, for an app whose page authenticates with a token rather than a cookie
|
|
177
|
+
* (P072): `POST <prefix>/handoff`, made with the app's own credential, leaves a short-lived key
|
|
178
|
+
* for its viewer in a cookie only the authorize route gets. `id` says who the viewer is (at
|
|
179
|
+
* most 512 characters); `viewer` turns it back into the app's viewer, or null.
|
|
180
|
+
*/
|
|
181
|
+
readonly handoff?: {
|
|
182
|
+
readonly id: (viewer: V) => string;
|
|
183
|
+
readonly viewer: (id: string, request: Request) => Awaitable<V | null>;
|
|
184
|
+
};
|
|
134
185
|
/**
|
|
135
186
|
* The app's refusal page on a tab (a frame gets Porthole's plain one), for the address in
|
|
136
187
|
* `entry`. Nothing (null, undefined): Porthole's own (P070).
|
|
@@ -177,6 +228,23 @@ export interface ContentHost<V> {
|
|
|
177
228
|
* nothing is served. Opens through redirect entry (`entry`); frames take tickets (`issue`).
|
|
178
229
|
*/
|
|
179
230
|
urlOf(scope: string, path?: string): string | null;
|
|
231
|
+
/** Where `routes` answers (`/porthole`). */
|
|
232
|
+
readonly prefix: string;
|
|
233
|
+
/**
|
|
234
|
+
* The app's Porthole routes in one handler (P072): `POST <prefix>/frames` (`issue`), `GET
|
|
235
|
+
* <prefix>/authorize`, `GET <prefix>/meta` (`clientMeta`), `POST`/`DELETE <prefix>/handoff`.
|
|
236
|
+
* Null for any other request: the app's own routes.
|
|
237
|
+
*/
|
|
238
|
+
routes(viewerOf: (request: Request) => Awaitable<V | null>): (request: Request) => Promise<Response | null>;
|
|
239
|
+
/** What `GET <prefix>/meta` answers the page. */
|
|
240
|
+
clientMeta(): ContentClientMeta;
|
|
241
|
+
/** The viewer handoff (`entry.handoff`), as a fetch handler: POST sets it, DELETE clears it. */
|
|
242
|
+
handoff(viewerOf: (request: Request) => Awaitable<V | null>): (request: Request) => Promise<Response>;
|
|
243
|
+
/** Drops cached `authorize` answers (`authorizeTtlSeconds`): all, or a scope's, or a subject's. */
|
|
244
|
+
forget(filter?: {
|
|
245
|
+
readonly scope?: string;
|
|
246
|
+
readonly subject?: string;
|
|
247
|
+
}): void;
|
|
180
248
|
/** The app's authorize route for redirect entry (`entry.authorizeUrl`), as a fetch handler. */
|
|
181
249
|
authorize(viewerOf: (request: Request) => Awaitable<V | null>): (request: Request) => Promise<Response>;
|
|
182
250
|
/** A url-mode app's access for a WebSocket upgrade (`server.access`), or null. */
|
|
@@ -189,4 +257,3 @@ export interface ContentHost<V> {
|
|
|
189
257
|
close(): void;
|
|
190
258
|
}
|
|
191
259
|
export declare function createContentHost<V>(options: ContentHostOptions<V>): ContentHost<V>;
|
|
192
|
-
export {};
|