@foliwake/cli 0.0.0-stage → 0.6.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/CHANGELOG.md +35 -0
- package/LICENSE +202 -0
- package/README.md +643 -2
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +9 -0
- package/dist/command-words.d.ts +13 -0
- package/dist/command-words.js +53 -0
- package/dist/commands/account/keys/create.d.ts +12 -0
- package/dist/commands/account/keys/create.js +36 -0
- package/dist/commands/account/keys/list.d.ts +9 -0
- package/dist/commands/account/keys/list.js +23 -0
- package/dist/commands/account/keys/revoke.d.ts +12 -0
- package/dist/commands/account/keys/revoke.js +15 -0
- package/dist/commands/branch/bootstrap.d.ts +11 -0
- package/dist/commands/branch/bootstrap.js +23 -0
- package/dist/commands/branch/delete.d.ts +17 -0
- package/dist/commands/branch/delete.js +38 -0
- package/dist/commands/branch/history.d.ts +14 -0
- package/dist/commands/branch/history.js +24 -0
- package/dist/commands/branch/list.d.ts +11 -0
- package/dist/commands/branch/list.js +15 -0
- package/dist/commands/branch/update.d.ts +19 -0
- package/dist/commands/branch/update.js +49 -0
- package/dist/commands/code/deploy.d.ts +15 -0
- package/dist/commands/code/deploy.js +78 -0
- package/dist/commands/code/prepare.d.ts +13 -0
- package/dist/commands/code/prepare.js +54 -0
- package/dist/commands/code/release.d.ts +19 -0
- package/dist/commands/code/release.js +51 -0
- package/dist/commands/code/rollback.d.ts +17 -0
- package/dist/commands/code/rollback.js +38 -0
- package/dist/commands/connect.d.ts +19 -0
- package/dist/commands/connect.js +100 -0
- package/dist/commands/create.d.ts +30 -0
- package/dist/commands/create.js +163 -0
- package/dist/commands/credential/list.d.ts +10 -0
- package/dist/commands/credential/list.js +21 -0
- package/dist/commands/credential/rm.d.ts +12 -0
- package/dist/commands/credential/rm.js +18 -0
- package/dist/commands/credential/set.d.ts +15 -0
- package/dist/commands/credential/set.js +58 -0
- package/dist/commands/dev.d.ts +25 -0
- package/dist/commands/dev.js +89 -0
- package/dist/commands/login.d.ts +20 -0
- package/dist/commands/login.js +94 -0
- package/dist/commands/logout.d.ts +14 -0
- package/dist/commands/logout.js +61 -0
- package/dist/commands/migration/commit.d.ts +13 -0
- package/dist/commands/migration/commit.js +42 -0
- package/dist/commands/migration/prepare.d.ts +18 -0
- package/dist/commands/migration/prepare.js +53 -0
- package/dist/commands/operation/cancel.d.ts +14 -0
- package/dist/commands/operation/cancel.js +21 -0
- package/dist/commands/operation/get.d.ts +14 -0
- package/dist/commands/operation/get.js +26 -0
- package/dist/commands/operation/list.d.ts +12 -0
- package/dist/commands/operation/list.js +25 -0
- package/dist/commands/operation/recover.d.ts +20 -0
- package/dist/commands/operation/recover.js +49 -0
- package/dist/commands/page/changes.d.ts +13 -0
- package/dist/commands/page/changes.js +26 -0
- package/dist/commands/page/check.d.ts +12 -0
- package/dist/commands/page/check.js +25 -0
- package/dist/commands/page/replace.d.ts +13 -0
- package/dist/commands/page/replace.js +59 -0
- package/dist/commands/page/unpreview.d.ts +17 -0
- package/dist/commands/page/unpreview.js +54 -0
- package/dist/commands/page/unpublish.d.ts +18 -0
- package/dist/commands/page/unpublish.js +36 -0
- package/dist/commands/project/preview.d.ts +8 -0
- package/dist/commands/project/preview.js +20 -0
- package/dist/commands/project/publish.d.ts +16 -0
- package/dist/commands/project/publish.js +40 -0
- package/dist/commands/project/unpublish.d.ts +16 -0
- package/dist/commands/project/unpublish.js +33 -0
- package/dist/commands/release/rollback.d.ts +17 -0
- package/dist/commands/release/rollback.js +38 -0
- package/dist/commands/servers/index.d.ts +20 -0
- package/dist/commands/servers/index.js +36 -0
- package/dist/commands/servers/use.d.ts +11 -0
- package/dist/commands/servers/use.js +30 -0
- package/dist/commands/site/adopt.d.ts +11 -0
- package/dist/commands/site/adopt.js +21 -0
- package/dist/commands/site/create.d.ts +18 -0
- package/dist/commands/site/create.js +61 -0
- package/dist/commands/site/edit.d.ts +11 -0
- package/dist/commands/site/edit.js +56 -0
- package/dist/commands/site/history.d.ts +11 -0
- package/dist/commands/site/history.js +25 -0
- package/dist/commands/site/link.d.ts +15 -0
- package/dist/commands/site/link.js +35 -0
- package/dist/commands/site/list.d.ts +9 -0
- package/dist/commands/site/list.js +29 -0
- package/dist/commands/site/reset-storage.d.ts +15 -0
- package/dist/commands/site/reset-storage.js +61 -0
- package/dist/commands/site/set.d.ts +16 -0
- package/dist/commands/site/set.js +45 -0
- package/dist/commands/site/show.d.ts +10 -0
- package/dist/commands/site/show.js +19 -0
- package/dist/commands/site/status.d.ts +11 -0
- package/dist/commands/site/status.js +15 -0
- package/dist/commands/site/unlink.d.ts +11 -0
- package/dist/commands/site/unlink.js +28 -0
- package/dist/commands/source/add.d.ts +32 -0
- package/dist/commands/source/add.js +103 -0
- package/dist/commands/source/adopt-pages.d.ts +14 -0
- package/dist/commands/source/adopt-pages.js +30 -0
- package/dist/commands/source/check.d.ts +17 -0
- package/dist/commands/source/check.js +52 -0
- package/dist/commands/source/list.d.ts +11 -0
- package/dist/commands/source/list.js +15 -0
- package/dist/commands/source/mappings/check.d.ts +13 -0
- package/dist/commands/source/mappings/check.js +69 -0
- package/dist/commands/source/pending.d.ts +12 -0
- package/dist/commands/source/pending.js +25 -0
- package/dist/commands/source/plugins.d.ts +6 -0
- package/dist/commands/source/plugins.js +17 -0
- package/dist/commands/source/sync.d.ts +16 -0
- package/dist/commands/source/sync.js +58 -0
- package/dist/commands/whoami.d.ts +6 -0
- package/dist/commands/whoami.js +21 -0
- package/dist/connect-prompts.d.ts +16 -0
- package/dist/connect-prompts.js +24 -0
- package/dist/connect.d.ts +133 -0
- package/dist/connect.js +416 -0
- package/dist/core-command.d.ts +91 -0
- package/dist/core-command.js +262 -0
- package/dist/core-types.d.ts +21 -0
- package/dist/core-types.js +1 -0
- package/dist/create-connect.d.ts +26 -0
- package/dist/create-connect.js +93 -0
- package/dist/dev/code-watcher.d.ts +66 -0
- package/dist/dev/code-watcher.js +254 -0
- package/dist/dev/dev-checks.d.ts +14 -0
- package/dist/dev/dev-checks.js +138 -0
- package/dist/dev/dev-reload.d.ts +51 -0
- package/dist/dev/dev-reload.js +345 -0
- package/dist/dev/flags.d.ts +15 -0
- package/dist/dev/flags.js +43 -0
- package/dist/dev/html.d.ts +30 -0
- package/dist/dev/html.js +106 -0
- package/dist/dev/kit-files.d.ts +7 -0
- package/dist/dev/kit-files.js +33 -0
- package/dist/dev/local-code.d.ts +22 -0
- package/dist/dev/local-code.js +101 -0
- package/dist/dev/remote-config.d.ts +57 -0
- package/dist/dev/remote-config.js +100 -0
- package/dist/dev/remote-dev.d.ts +41 -0
- package/dist/dev/remote-dev.js +527 -0
- package/dist/dev/remote-fetch.d.ts +5 -0
- package/dist/dev/remote-fetch.js +36 -0
- package/dist/dev/remote-html.d.ts +10 -0
- package/dist/dev/remote-html.js +60 -0
- package/dist/dev/remote-page.d.ts +34 -0
- package/dist/dev/remote-page.js +183 -0
- package/dist/dev/remote-routes.d.ts +63 -0
- package/dist/dev/remote-routes.js +114 -0
- package/dist/dev/signal-stop.d.ts +17 -0
- package/dist/dev/signal-stop.js +46 -0
- package/dist/dev/start.d.ts +18 -0
- package/dist/dev/start.js +80 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +7 -0
- package/dist/lib/diagnostics.d.ts +15 -0
- package/dist/lib/diagnostics.js +12 -0
- package/dist/lib/front-matter.d.ts +6 -0
- package/dist/lib/front-matter.js +59 -0
- package/dist/lib/operation-result.d.ts +3 -0
- package/dist/lib/operation-result.js +16 -0
- package/dist/lib/problem-groups.d.ts +27 -0
- package/dist/lib/problem-groups.js +49 -0
- package/dist/lib/problems.d.ts +50 -0
- package/dist/lib/problems.js +94 -0
- package/dist/lib/prompts.d.ts +38 -0
- package/dist/lib/prompts.js +77 -0
- package/dist/lib/result-types.d.ts +198 -0
- package/dist/lib/result-types.js +3 -0
- package/dist/lib/rules.d.ts +15 -0
- package/dist/lib/rules.js +26 -0
- package/dist/lib/summaries.d.ts +19 -0
- package/dist/lib/summaries.js +22 -0
- package/dist/lib/sync-problems.d.ts +21 -0
- package/dist/lib/sync-problems.js +19 -0
- package/dist/main.d.ts +2 -0
- package/dist/main.js +40 -0
- package/dist/project-preview.d.ts +35 -0
- package/dist/project-preview.js +156 -0
- package/dist/project-publish.d.ts +28 -0
- package/dist/project-publish.js +173 -0
- package/dist/remote/connection.d.ts +8 -0
- package/dist/remote/connection.js +19 -0
- package/dist/remote/core-failure.d.ts +8 -0
- package/dist/remote/core-failure.js +15 -0
- package/dist/remote/credentials.d.ts +15 -0
- package/dist/remote/credentials.js +112 -0
- package/dist/remote/device-login.d.ts +33 -0
- package/dist/remote/device-login.js +161 -0
- package/dist/remote/remote-caller.d.ts +14 -0
- package/dist/remote/remote-caller.js +52 -0
- package/dist/remote/rpc-wire.d.ts +18 -0
- package/dist/remote/rpc-wire.js +57 -0
- package/dist/remote/servers.d.ts +80 -0
- package/dist/remote/servers.js +162 -0
- package/dist/remote/session.d.ts +53 -0
- package/dist/remote/session.js +132 -0
- package/dist/remote/sign-in-here.d.ts +5 -0
- package/dist/remote/sign-in-here.js +33 -0
- package/dist/remote/sign-in.d.ts +25 -0
- package/dist/remote/sign-in.js +55 -0
- package/dist/remote/wait-slices.d.ts +16 -0
- package/dist/remote/wait-slices.js +21 -0
- package/dist/render/add.d.ts +3 -0
- package/dist/render/add.js +9 -0
- package/dist/render/branch-write.d.ts +9 -0
- package/dist/render/branch-write.js +28 -0
- package/dist/render/branches.d.ts +5 -0
- package/dist/render/branches.js +28 -0
- package/dist/render/credentials.d.ts +5 -0
- package/dist/render/credentials.js +39 -0
- package/dist/render/operation-result.d.ts +16 -0
- package/dist/render/operation-result.js +65 -0
- package/dist/render/operation.d.ts +7 -0
- package/dist/render/operation.js +15 -0
- package/dist/render/page-changes.d.ts +3 -0
- package/dist/render/page-changes.js +36 -0
- package/dist/render/pending.d.ts +3 -0
- package/dist/render/pending.js +46 -0
- package/dist/render/plugin-list.d.ts +3 -0
- package/dist/render/plugin-list.js +30 -0
- package/dist/render/probe.d.ts +3 -0
- package/dist/render/probe.js +61 -0
- package/dist/render/problems.d.ts +35 -0
- package/dist/render/problems.js +64 -0
- package/dist/render/recovery.d.ts +2 -0
- package/dist/render/recovery.js +36 -0
- package/dist/render/reset-storage.d.ts +4 -0
- package/dist/render/reset-storage.js +70 -0
- package/dist/render/site-status.d.ts +2 -0
- package/dist/render/site-status.js +81 -0
- package/dist/render/source-list.d.ts +2 -0
- package/dist/render/source-list.js +37 -0
- package/dist/render/sync.d.ts +5 -0
- package/dist/render/sync.js +66 -0
- package/dist/settings.d.ts +10 -0
- package/dist/settings.js +45 -0
- package/dist/site-entry-edit.d.ts +5 -0
- package/dist/site-entry-edit.js +44 -0
- package/dist/source-entry.d.ts +32 -0
- package/dist/source-entry.js +89 -0
- package/dist/version.d.ts +3 -0
- package/dist/version.js +10 -0
- package/package.json +108 -3
|
@@ -0,0 +1,527 @@
|
|
|
1
|
+
// `foliwake dev --remote [preview|live]`: local frontend code against content from a deployed Foliwake site.
|
|
2
|
+
//
|
|
3
|
+
// The remote document is never passed through. It is parsed (parse5, a WHATWG HTML parser) and only content
|
|
4
|
+
// is kept: the children of <main>, <title>, <meta name="description">, <html lang> and
|
|
5
|
+
// <html data-html-contract> (remote-page.ts). That body is wrapped in the LOCAL shell (renderPageShell),
|
|
6
|
+
// which links the local /styles and /scripts, and the local stylesheets of the components the page uses (as
|
|
7
|
+
// the local descriptor declares them). The remote shell's /code/cd_… links are never copied and /code/… is
|
|
8
|
+
// refused, so deployed JavaScript and CSS cannot load.
|
|
9
|
+
//
|
|
10
|
+
// Routes (classifyRemoteRoute, remote-routes.ts):
|
|
11
|
+
// /components/… /scripts/… /styles/… local working files
|
|
12
|
+
// /_foliwake/block-kit.js, lit-html.js the block kit of the installed @foliwake/block-kit
|
|
13
|
+
// /media/<64 hex>.<image ext> fetched from the remote origin
|
|
14
|
+
// /code/… refused (404 with an explanation)
|
|
15
|
+
// /_dev/…, /_foliwake/blocks local dev endpoints; the block catalog is a stub here
|
|
16
|
+
// anything else the remote page, in the local shell
|
|
17
|
+
//
|
|
18
|
+
// It is not a proxy: requests go only to the one configured origin, with GET, a fixed set of request
|
|
19
|
+
// headers (remoteRequestHeaders) and redirect:'manual'; nothing from the browser request is forwarded
|
|
20
|
+
// except the path, the query and a validated Accept-Language. Only a fixed set of response headers is
|
|
21
|
+
// produced (pickRemoteHeaders). The credential stays in this process. The remote site is never polled:
|
|
22
|
+
// a page is fetched when the browser asks for it.
|
|
23
|
+
import http, {} from 'node:http';
|
|
24
|
+
import { HTML_CONTRACT } from '@foliwake/site-check/formats/constants';
|
|
25
|
+
import { DESCRIPTOR_PATH, shellStylesheets } from '@foliwake/site-check/formats/descriptor';
|
|
26
|
+
import { COMMAND } from '../settings.js';
|
|
27
|
+
import { createLiveCodeWatcher } from './code-watcher.js';
|
|
28
|
+
import { createDevChecker, descriptorDiagnostics, toProblem } from './dev-checks.js';
|
|
29
|
+
import { DEV_CLIENT_PATH, DEV_CLIENT_SCRIPT, DEV_EVENTS_PATH, createReloadHub, formatProblem, injectDevClient, } from './dev-reload.js';
|
|
30
|
+
import { escapeHtml, renderDiagnosticsPage, renderPageShell } from './html.js';
|
|
31
|
+
import { BASE_HEADERS, NotFound, serveCodeFile } from './local-code.js';
|
|
32
|
+
import { TooLarge, errorReason, readLimited } from './remote-fetch.js';
|
|
33
|
+
import { blockCatalogStub, noticeBanner, problemsBanner, renderRemoteErrorPage } from './remote-html.js';
|
|
34
|
+
import { compatibilityProblems, extractRemotePage, readLocalDescriptor, remoteText, } from './remote-page.js';
|
|
35
|
+
import { BLOCK_CATALOG_PATH, DEFAULT_REMOTE_TIMEOUT_MS, DEPLOYED_CODE_TEXT, REMOTE_MEDIA_CACHE, checkLocalRequest, classifyRemoteRoute, pickRemoteHeaders, remoteRequestHeaders, remoteUrl, } from './remote-routes.js';
|
|
36
|
+
const MAX_PAGE_BYTES = 8 * 1024 * 1024;
|
|
37
|
+
const MAX_MEDIA_BYTES = 32 * 1024 * 1024;
|
|
38
|
+
const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
|
|
39
|
+
const MEDIA_TYPES = {
|
|
40
|
+
jpg: 'image/jpeg',
|
|
41
|
+
jpeg: 'image/jpeg',
|
|
42
|
+
png: 'image/png',
|
|
43
|
+
gif: 'image/gif',
|
|
44
|
+
webp: 'image/webp',
|
|
45
|
+
avif: 'image/avif',
|
|
46
|
+
};
|
|
47
|
+
const TAG = `[${COMMAND}]`;
|
|
48
|
+
const LISTEN_HOST = '127.0.0.1';
|
|
49
|
+
export function createRemoteDevServer({ cwd, target, authorization, redact = (t) => t, log = (text) => process.stderr.write(text + '\n'), reload, fetch: fetchImpl = (input, init) => fetch(input, init), timeoutMs = DEFAULT_REMOTE_TIMEOUT_MS, }) {
|
|
50
|
+
const { channel, origin } = target;
|
|
51
|
+
const reported = new Map();
|
|
52
|
+
const say = (text) => log(redact(`${TAG} ${text}`));
|
|
53
|
+
function send(res, status, headers, body, method) {
|
|
54
|
+
res.writeHead(status, { ...BASE_HEADERS, ...headers });
|
|
55
|
+
res.end(method === 'HEAD' ? undefined : typeof body === 'string' ? redact(body) : body);
|
|
56
|
+
}
|
|
57
|
+
function sendText(res, status, text, method, headers = {}) {
|
|
58
|
+
send(res, status, { 'Content-Type': 'text/plain; charset=utf-8', ...headers }, text, method);
|
|
59
|
+
}
|
|
60
|
+
// The change generation when each request arrived: a local change while the
|
|
61
|
+
// remote page is being fetched makes the client reload once it connects.
|
|
62
|
+
const generations = new WeakMap();
|
|
63
|
+
// Every HTML response goes through here: with --watch it gets the dev client.
|
|
64
|
+
function sendHtml(res, status, html, method, headers = {}) {
|
|
65
|
+
const page = reload ? injectDevClient(html, generations.get(res) ?? reload.generation()) : html;
|
|
66
|
+
send(res, status, { 'Content-Type': 'text/html; charset=utf-8', 'X-Foliwake-Remote': channel, ...headers }, page, method);
|
|
67
|
+
}
|
|
68
|
+
function sendError(res, status, method, title, lines, detail = null, headers = {}) {
|
|
69
|
+
say(`${channel} ${title}: ${lines.join(' ')}`);
|
|
70
|
+
sendHtml(res, status, renderRemoteErrorPage({ title, lines, detail }), method, headers);
|
|
71
|
+
}
|
|
72
|
+
const authHint = target.auth
|
|
73
|
+
? `check ${target.auth.passwordEnv} (the password of user "${target.auth.username}"; set in the environment, ` +
|
|
74
|
+
`never in a file in Git)`
|
|
75
|
+
: target.from === '--remote-url'
|
|
76
|
+
? 'the site needs credentials, but none are configured: add --remote-auth-user <name> --remote-auth-env <NAME>'
|
|
77
|
+
: `the site needs credentials, but ${target.from} configures none: add "auth": {"type": "basic", "username": ` +
|
|
78
|
+
`…, "passwordEnv": …}`;
|
|
79
|
+
// Upstream requests in progress: server.close() aborts them all.
|
|
80
|
+
const active = new Set();
|
|
81
|
+
/**
|
|
82
|
+
* Runs one remote request with a signal that aborts when the browser goes
|
|
83
|
+
* away before the response is complete (the ServerResponse closes without
|
|
84
|
+
* having finished; a completed request's normal close is not cancellation),
|
|
85
|
+
* when the server stops, or after timeoutMs. The signal stays active while
|
|
86
|
+
* the remote body is read; the listener is removed when `work` settles.
|
|
87
|
+
*/
|
|
88
|
+
async function withUpstreamSignal(res, work) {
|
|
89
|
+
const controller = new AbortController();
|
|
90
|
+
const onClose = () => {
|
|
91
|
+
if (!res.writableFinished)
|
|
92
|
+
controller.abort(new Error('the browser closed the request'));
|
|
93
|
+
};
|
|
94
|
+
if (res.destroyed)
|
|
95
|
+
onClose();
|
|
96
|
+
else
|
|
97
|
+
res.once('close', onClose);
|
|
98
|
+
active.add(controller);
|
|
99
|
+
try {
|
|
100
|
+
await work(AbortSignal.any([controller.signal, AbortSignal.timeout(timeoutMs)]), () => controller.signal.aborted);
|
|
101
|
+
}
|
|
102
|
+
finally {
|
|
103
|
+
res.off('close', onClose);
|
|
104
|
+
active.delete(controller);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/** Aborts every upstream request in progress (server stop). */
|
|
108
|
+
function abortActive() {
|
|
109
|
+
for (const controller of active)
|
|
110
|
+
controller.abort(new Error('the dev server is stopping'));
|
|
111
|
+
active.clear();
|
|
112
|
+
}
|
|
113
|
+
// A request cancelled by the browser or by a server stop gets no answer.
|
|
114
|
+
function dropCancelled(res) {
|
|
115
|
+
if (!res.destroyed)
|
|
116
|
+
res.destroy();
|
|
117
|
+
}
|
|
118
|
+
async function fetchRemote(url, kind, req, signal) {
|
|
119
|
+
return fetchImpl(url, {
|
|
120
|
+
method: 'GET',
|
|
121
|
+
redirect: 'manual',
|
|
122
|
+
headers: remoteRequestHeaders({ kind, acceptLanguage: req.headers['accept-language'], authorization }),
|
|
123
|
+
signal,
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* The local Location for a remote redirect target on the configured origin,
|
|
128
|
+
* or null. It must classify as a page or a media path by the same route rules
|
|
129
|
+
* as a browser request (no `//host`, no backslashes, no empty or dot
|
|
130
|
+
* segments, no /code, /_dev or local code paths), and it is checked to
|
|
131
|
+
* resolve to the same origin as this listener, so it can never become a
|
|
132
|
+
* network-path (`//host/…`) redirect.
|
|
133
|
+
*/
|
|
134
|
+
function localRedirectTarget(next) {
|
|
135
|
+
const route = classifyRemoteRoute(next.pathname);
|
|
136
|
+
if (route.kind !== 'page' && route.kind !== 'media')
|
|
137
|
+
return null;
|
|
138
|
+
if (!next.pathname.startsWith('/') || next.pathname.startsWith('//') || /\\/.test(next.pathname))
|
|
139
|
+
return null;
|
|
140
|
+
const local = `${next.pathname}${next.search}`;
|
|
141
|
+
const base = 'http://127.0.0.1';
|
|
142
|
+
let resolved;
|
|
143
|
+
try {
|
|
144
|
+
resolved = new URL(local, base);
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
return resolved.origin === base && `${resolved.pathname}${resolved.search}` === local ? local : null;
|
|
150
|
+
}
|
|
151
|
+
// Answers a remote redirect: same origin → the same path locally; anything else → refused.
|
|
152
|
+
function redirect(res, response, url, method, kind) {
|
|
153
|
+
const location = response.headers.get('location');
|
|
154
|
+
let next = null;
|
|
155
|
+
try {
|
|
156
|
+
next = location ? new URL(location, url) : null;
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
next = null;
|
|
160
|
+
}
|
|
161
|
+
void response.body?.cancel().catch(() => { });
|
|
162
|
+
if (next && next.origin === origin && !next.username && !next.password) {
|
|
163
|
+
const local = localRedirectTarget(next);
|
|
164
|
+
if (local)
|
|
165
|
+
return send(res, 302, { Location: local, 'X-Foliwake-Remote': channel }, kind === 'page' ? `Redirect to ${local}\n` : '', method);
|
|
166
|
+
if (kind === 'media')
|
|
167
|
+
return sendText(res, 502, `The ${channel} site redirected ${url.pathname} to an unsafe path on ${origin}; foliwake dev does not ` +
|
|
168
|
+
`follow it.\n`, method);
|
|
169
|
+
return sendError(res, 502, method, 'Redirect to an unsafe path refused', [
|
|
170
|
+
`${channel} at ${origin} redirected ${url.pathname} to a path that is not a page or media path (for example ` +
|
|
171
|
+
`//host/…).`,
|
|
172
|
+
'foliwake dev --remote only redirects to page and /media paths on this local origin.',
|
|
173
|
+
]);
|
|
174
|
+
}
|
|
175
|
+
const where = next ? next.origin : 'an invalid location';
|
|
176
|
+
if (kind === 'media')
|
|
177
|
+
return sendText(res, 502, `The ${channel} site redirected ${url.pathname} to ${where}; foliwake dev only reads from ${origin}.\n`, method);
|
|
178
|
+
return sendError(res, 502, method, `Redirect to another origin refused`, [
|
|
179
|
+
`${channel} at ${origin} redirected ${url.pathname} to ${where}.`,
|
|
180
|
+
'foliwake dev --remote never follows redirects to another origin and never sends the credentials there.',
|
|
181
|
+
`Check the configured URL in ${target.from}.`,
|
|
182
|
+
]);
|
|
183
|
+
}
|
|
184
|
+
async function descriptorState() {
|
|
185
|
+
const [descriptor, diagnostics] = await Promise.all([readLocalDescriptor(cwd), descriptorDiagnostics(cwd)]);
|
|
186
|
+
return { descriptor, diagnostics };
|
|
187
|
+
}
|
|
188
|
+
function report(pathname, problems) {
|
|
189
|
+
const text = problems.map(formatProblem).join('\n');
|
|
190
|
+
if ((reported.get(pathname) ?? '') === text)
|
|
191
|
+
return;
|
|
192
|
+
reported.set(pathname, text);
|
|
193
|
+
if (text)
|
|
194
|
+
say(`${pathname}: the local frontend cannot render this ${channel} page completely:\n${text}`);
|
|
195
|
+
else
|
|
196
|
+
say(`${pathname}: compatible again.`);
|
|
197
|
+
}
|
|
198
|
+
async function renderRemote(page, pathname, banner) {
|
|
199
|
+
const { descriptor, diagnostics } = await descriptorState();
|
|
200
|
+
const problems = compatibilityProblems({ page, descriptor, descriptorDiagnostics: diagnostics });
|
|
201
|
+
report(pathname, problems);
|
|
202
|
+
const bannerHtml = [
|
|
203
|
+
banner ? noticeBanner(banner) : '',
|
|
204
|
+
problems.length
|
|
205
|
+
? problemsBanner(`foliwake dev: ${problems.length} problem(s) between this ${channel} page and the local frontend; the ` +
|
|
206
|
+
`content is shown below.`, problems)
|
|
207
|
+
: '',
|
|
208
|
+
]
|
|
209
|
+
.filter(Boolean)
|
|
210
|
+
.join('\n');
|
|
211
|
+
const contract = Number(page.htmlContract);
|
|
212
|
+
return renderPageShell({
|
|
213
|
+
page: { title: page.title, description: page.description, body: page.body },
|
|
214
|
+
lang: page.lang ?? 'en',
|
|
215
|
+
htmlContract: Number.isInteger(contract) && contract > 0 ? contract : HTML_CONTRACT,
|
|
216
|
+
devBanner: bannerHtml,
|
|
217
|
+
componentCss: shellStylesheets(page.components, descriptor),
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
async function servePage(req, res, rawPath, query, method, signal, cancelled) {
|
|
221
|
+
const url = remoteUrl(origin, rawPath, query);
|
|
222
|
+
if (!url)
|
|
223
|
+
throw new NotFound();
|
|
224
|
+
let response;
|
|
225
|
+
try {
|
|
226
|
+
response = await fetchRemote(url, 'page', req, signal);
|
|
227
|
+
}
|
|
228
|
+
catch (error) {
|
|
229
|
+
if (cancelled())
|
|
230
|
+
return dropCancelled(res);
|
|
231
|
+
return sendError(res, 502, method, `${channel} unavailable`, [
|
|
232
|
+
`${channel} unavailable at ${origin}: ${errorReason(error)}.`,
|
|
233
|
+
`Nothing else is tried (no fallback to ${channel === 'preview' ? 'live' : 'preview'}). Check that the site ` +
|
|
234
|
+
`is up, then refresh.`,
|
|
235
|
+
]);
|
|
236
|
+
}
|
|
237
|
+
const remote = pickRemoteHeaders(response.headers);
|
|
238
|
+
const status = response.status;
|
|
239
|
+
if (REDIRECT_STATUSES.has(status))
|
|
240
|
+
return redirect(res, response, url, method, 'page');
|
|
241
|
+
if (status === 401 || status === 403) {
|
|
242
|
+
void response.body?.cancel().catch(() => { });
|
|
243
|
+
return sendError(res, status, method, `Authentication failed`, [
|
|
244
|
+
`authentication failed for ${channel} at ${origin} (HTTP ${status}): ${authHint}.`,
|
|
245
|
+
]);
|
|
246
|
+
}
|
|
247
|
+
let bytes;
|
|
248
|
+
try {
|
|
249
|
+
bytes = await readLimited(response, MAX_PAGE_BYTES);
|
|
250
|
+
}
|
|
251
|
+
catch (error) {
|
|
252
|
+
if (cancelled())
|
|
253
|
+
return dropCancelled(res);
|
|
254
|
+
if (error instanceof TooLarge)
|
|
255
|
+
return sendError(res, 502, method, 'Remote page too large', [
|
|
256
|
+
`${channel} at ${origin} returned more than ${MAX_PAGE_BYTES} bytes for ${url.pathname}.`,
|
|
257
|
+
]);
|
|
258
|
+
return sendError(res, 502, method, `${channel} unavailable`, [
|
|
259
|
+
`${channel} unavailable at ${origin}: ${errorReason(error)} while reading ${url.pathname}.`,
|
|
260
|
+
]);
|
|
261
|
+
}
|
|
262
|
+
const html = bytes.toString('utf8');
|
|
263
|
+
const isHtml = /^text\/html\b/i.test(response.headers.get('content-type') ?? '');
|
|
264
|
+
if (status >= 500) {
|
|
265
|
+
return sendError(res, 502, method, `${channel} unavailable`, [
|
|
266
|
+
`${channel} unavailable at ${origin}: HTTP ${status} for ${url.pathname}.`,
|
|
267
|
+
`Nothing else is tried (no fallback to ${channel === 'preview' ? 'live' : 'preview'}).`,
|
|
268
|
+
], isHtml ? remoteText(html) : html.slice(0, 4000), remote);
|
|
269
|
+
}
|
|
270
|
+
if (status === 404) {
|
|
271
|
+
const page = isHtml ? extractRemotePage(html) : null;
|
|
272
|
+
const body = page
|
|
273
|
+
? page.body
|
|
274
|
+
: `<h1>Not found</h1>\n<p>${escapeHtml(isHtml ? remoteText(html) : html.trim().slice(0, 400))}</p>`;
|
|
275
|
+
const shown = page ?? {
|
|
276
|
+
lang: null,
|
|
277
|
+
htmlContract: String(HTML_CONTRACT),
|
|
278
|
+
title: 'Not found',
|
|
279
|
+
description: null,
|
|
280
|
+
body,
|
|
281
|
+
components: [],
|
|
282
|
+
};
|
|
283
|
+
say(`${channel} ${url.pathname}: 404 not found at ${origin}`);
|
|
284
|
+
return sendHtml(res, 404, await renderRemote(shown, url.pathname, `${channel} at ${origin} has no page at ${url.pathname}${url.search} (HTTP 404). Unpublished pages are on ` +
|
|
285
|
+
`preview only.`), method, remote);
|
|
286
|
+
}
|
|
287
|
+
if (status !== 200) {
|
|
288
|
+
const lines = status === 409
|
|
289
|
+
? [
|
|
290
|
+
`${channel} at ${origin} cannot serve ${url.pathname} with its current code (HTTP 409). Its own ` +
|
|
291
|
+
`explanation follows.`,
|
|
292
|
+
]
|
|
293
|
+
: [`${channel} at ${origin} answered HTTP ${status} for ${url.pathname}.`];
|
|
294
|
+
return sendError(res, status >= 400 && status < 500 ? status : 502, method, status === 409 ? 'Remote page incompatible (409)' : `Remote answered ${status}`, lines, isHtml ? remoteText(html) : html.slice(0, 4000), remote);
|
|
295
|
+
}
|
|
296
|
+
if (!isHtml)
|
|
297
|
+
return sendError(res, 502, method, 'Not an HTML page', [
|
|
298
|
+
`${channel} at ${origin} returned ${response.headers.get('content-type') ?? 'no content type'} for ` +
|
|
299
|
+
`${url.pathname}, not an HTML page.`,
|
|
300
|
+
]);
|
|
301
|
+
const page = extractRemotePage(html);
|
|
302
|
+
if (!page) {
|
|
303
|
+
return sendError(res, 502, method, 'Not a Foliwake page', [
|
|
304
|
+
`The ${channel} document at ${origin}${url.pathname} has no <main> element.`,
|
|
305
|
+
`Check the configured URL in ${target.from}: it must be the Foliwake origin.`,
|
|
306
|
+
]);
|
|
307
|
+
}
|
|
308
|
+
sendHtml(res, 200, await renderRemote(page, url.pathname, null), method, remote);
|
|
309
|
+
}
|
|
310
|
+
async function serveMedia(req, res, rawPath, method, signal, cancelled) {
|
|
311
|
+
const url = remoteUrl(origin, rawPath, '');
|
|
312
|
+
if (!url)
|
|
313
|
+
throw new NotFound();
|
|
314
|
+
let response;
|
|
315
|
+
try {
|
|
316
|
+
response = await fetchRemote(url, 'media', req, signal);
|
|
317
|
+
}
|
|
318
|
+
catch (error) {
|
|
319
|
+
if (cancelled())
|
|
320
|
+
return dropCancelled(res);
|
|
321
|
+
say(`${channel} unavailable at ${origin} for ${rawPath}: ${errorReason(error)}`);
|
|
322
|
+
return sendText(res, 502, `${channel} unavailable at ${origin}: ${errorReason(error)}.\n`, method);
|
|
323
|
+
}
|
|
324
|
+
const status = response.status;
|
|
325
|
+
if (REDIRECT_STATUSES.has(status))
|
|
326
|
+
return redirect(res, response, url, method, 'media');
|
|
327
|
+
if (status !== 200) {
|
|
328
|
+
void response.body?.cancel().catch(() => { });
|
|
329
|
+
if (status === 401 || status === 403) {
|
|
330
|
+
say(`authentication failed for ${channel} at ${origin} (HTTP ${status}) for ${rawPath}: ${authHint}`);
|
|
331
|
+
return sendText(res, status, `authentication failed for ${channel} at ${origin}: ${authHint}.\n`, method);
|
|
332
|
+
}
|
|
333
|
+
if (status === 404)
|
|
334
|
+
return sendText(res, 404, `Not found on ${channel} at ${origin}.\n`, method);
|
|
335
|
+
say(`${channel} at ${origin}: HTTP ${status} for ${rawPath}`);
|
|
336
|
+
return sendText(res, 502, `${channel} at ${origin} answered HTTP ${status}.\n`, method);
|
|
337
|
+
}
|
|
338
|
+
const extension = rawPath.slice(rawPath.lastIndexOf('.') + 1);
|
|
339
|
+
const expected = MEDIA_TYPES[extension];
|
|
340
|
+
const declared = (response.headers.get('content-type') ?? '').split(';', 1)[0].trim().toLowerCase();
|
|
341
|
+
if (declared && declared !== expected) {
|
|
342
|
+
void response.body?.cancel().catch(() => { });
|
|
343
|
+
return sendText(res, 502, `${channel} at ${origin} returned ${declared} for a .${extension} media file.\n`, method);
|
|
344
|
+
}
|
|
345
|
+
let bytes;
|
|
346
|
+
try {
|
|
347
|
+
bytes = await readLimited(response, MAX_MEDIA_BYTES);
|
|
348
|
+
}
|
|
349
|
+
catch (error) {
|
|
350
|
+
if (cancelled())
|
|
351
|
+
return dropCancelled(res);
|
|
352
|
+
return sendText(res, 502, error instanceof TooLarge
|
|
353
|
+
? 'Media file too large.\n'
|
|
354
|
+
: `${channel} unavailable at ${origin}: ${errorReason(error)}.\n`, method);
|
|
355
|
+
}
|
|
356
|
+
send(res, 200, {
|
|
357
|
+
'Content-Type': expected,
|
|
358
|
+
'Content-Length': bytes.length,
|
|
359
|
+
'Cache-Control': REMOTE_MEDIA_CACHE,
|
|
360
|
+
'X-Foliwake-Remote': channel,
|
|
361
|
+
}, bytes, method);
|
|
362
|
+
}
|
|
363
|
+
async function serveDiagnostics(res, method) {
|
|
364
|
+
const { diagnostics } = await descriptorState();
|
|
365
|
+
const errors = diagnostics.filter((d) => d.severity === 'error').length;
|
|
366
|
+
const auth = target.auth
|
|
367
|
+
? `user "${target.auth.username}", password from ${target.auth.passwordEnv}`
|
|
368
|
+
: 'no credentials';
|
|
369
|
+
sendHtml(res, 200, renderDiagnosticsPage({
|
|
370
|
+
title: `Remote ${channel}: ${origin}`,
|
|
371
|
+
intro: `Content from ${channel} at ${origin} (${target.from}; ${auth}); code from this checkout. ` +
|
|
372
|
+
`${DESCRIPTOR_PATH}: ${diagnostics.length} diagnostic(s), ${errors} error(s).`,
|
|
373
|
+
diagnostics,
|
|
374
|
+
}), method);
|
|
375
|
+
}
|
|
376
|
+
async function handle(req, res) {
|
|
377
|
+
const method = req.method;
|
|
378
|
+
if (reload)
|
|
379
|
+
generations.set(res, reload.generation());
|
|
380
|
+
const address = server.address();
|
|
381
|
+
const port = address && typeof address === 'object' ? address.port : 0;
|
|
382
|
+
const allowed = checkLocalRequest({ host: req.headers.host, origin: req.headers.origin }, port);
|
|
383
|
+
if (!allowed.ok)
|
|
384
|
+
return sendText(res, allowed.status, allowed.message, method);
|
|
385
|
+
const rawUrl = req.url ?? '/';
|
|
386
|
+
const rawPath = rawUrl.split(/[?#]/, 1)[0] || '/';
|
|
387
|
+
const queryIndex = rawUrl.indexOf('?');
|
|
388
|
+
const query = queryIndex >= 0 ? rawUrl.slice(queryIndex + 1).split('#', 1)[0] : '';
|
|
389
|
+
if (reload && rawPath === DEV_EVENTS_PATH) {
|
|
390
|
+
if (method !== 'GET')
|
|
391
|
+
return sendText(res, 405, 'Method not allowed\n', method, { Allow: 'GET' });
|
|
392
|
+
return reload.handleEvents(req, res);
|
|
393
|
+
}
|
|
394
|
+
if (method !== 'GET' && method !== 'HEAD')
|
|
395
|
+
return sendText(res, 405, 'Method not allowed\n', method, { Allow: 'GET, HEAD' });
|
|
396
|
+
const route = classifyRemoteRoute(rawPath);
|
|
397
|
+
try {
|
|
398
|
+
switch (route.kind) {
|
|
399
|
+
case 'code':
|
|
400
|
+
return await serveCodeFile(res, cwd, route.prefix, route.rest, method);
|
|
401
|
+
case 'media':
|
|
402
|
+
return await withUpstreamSignal(res, (signal, cancelled) => serveMedia(req, res, route.path, method, signal, cancelled));
|
|
403
|
+
case 'deployed-code':
|
|
404
|
+
return sendText(res, 404, DEPLOYED_CODE_TEXT, method);
|
|
405
|
+
case 'dev':
|
|
406
|
+
if (rawPath === '/_dev/diagnostics')
|
|
407
|
+
return await serveDiagnostics(res, method);
|
|
408
|
+
if (rawPath === BLOCK_CATALOG_PATH ||
|
|
409
|
+
rawPath.startsWith(`${BLOCK_CATALOG_PATH}/`) ||
|
|
410
|
+
rawPath === '/_dev/blocks') {
|
|
411
|
+
return sendHtml(res, 501, blockCatalogStub(), method);
|
|
412
|
+
}
|
|
413
|
+
if (reload && rawPath === DEV_CLIENT_PATH)
|
|
414
|
+
return send(res, 200, { 'Content-Type': 'text/javascript; charset=utf-8' }, DEV_CLIENT_SCRIPT, method);
|
|
415
|
+
throw new NotFound();
|
|
416
|
+
case 'page':
|
|
417
|
+
return await withUpstreamSignal(res, (signal, cancelled) => servePage(req, res, route.path, query, method, signal, cancelled));
|
|
418
|
+
default:
|
|
419
|
+
throw new NotFound();
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
catch (error) {
|
|
423
|
+
if (error instanceof NotFound ||
|
|
424
|
+
error?.code === 'ENOENT' ||
|
|
425
|
+
error?.code === 'EISDIR') {
|
|
426
|
+
return sendHtml(res, 404, renderRemoteErrorPage({
|
|
427
|
+
title: 'Not found',
|
|
428
|
+
lines: [
|
|
429
|
+
`${rawPath} is not served by foliwake dev --remote (local files: components/, scripts/, styles/; ` +
|
|
430
|
+
`remote: pages and /media/<sha256>.<ext>).`,
|
|
431
|
+
],
|
|
432
|
+
}), method);
|
|
433
|
+
}
|
|
434
|
+
say(`internal error for ${rawPath}: ${error?.stack ?? String(error)}`);
|
|
435
|
+
if (res.headersSent) {
|
|
436
|
+
res.destroy();
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
return sendText(res, 500, 'Internal server error; see the terminal.\n', method);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
const server = http.createServer((req, res) => {
|
|
443
|
+
void handle(req, res);
|
|
444
|
+
});
|
|
445
|
+
// Stopping the server also cancels the remote requests still in progress.
|
|
446
|
+
const close = server.close.bind(server);
|
|
447
|
+
server.close = ((callback) => {
|
|
448
|
+
abortActive();
|
|
449
|
+
return close(callback);
|
|
450
|
+
});
|
|
451
|
+
return server;
|
|
452
|
+
}
|
|
453
|
+
/**
|
|
454
|
+
* Starts remote mode on 127.0.0.1. With `liveReload`, only local code is
|
|
455
|
+
* watched (the remote site is never polled); a reload fetches the page again.
|
|
456
|
+
* server.close() stops the event streams at once and the watchers after it.
|
|
457
|
+
*/
|
|
458
|
+
export async function startRemoteDevServer({ port, liveReload = false, ...options }) {
|
|
459
|
+
const log = options.log ?? ((text) => process.stderr.write(text + '\n'));
|
|
460
|
+
const redact = options.redact ?? ((t) => t);
|
|
461
|
+
const live = liveReload === false ? null : liveReload === true ? {} : liveReload;
|
|
462
|
+
let reload;
|
|
463
|
+
if (live) {
|
|
464
|
+
const checker = createDevChecker({ cwd: options.cwd });
|
|
465
|
+
reload = createReloadHub({
|
|
466
|
+
...(live.debounceMs === undefined ? {} : { debounceMs: live.debounceMs }),
|
|
467
|
+
log: (text) => log(redact(`${TAG} ${text}`)),
|
|
468
|
+
check: () => checker.check(),
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
const server = createRemoteDevServer({ ...options, ...(reload ? { reload } : {}) });
|
|
472
|
+
if (reload)
|
|
473
|
+
server.reload = reload;
|
|
474
|
+
const stops = [];
|
|
475
|
+
let stopping = null;
|
|
476
|
+
const stopAll = () => {
|
|
477
|
+
stopping ??= Promise.allSettled(stops.map((stop) => stop())).then(() => undefined);
|
|
478
|
+
return stopping;
|
|
479
|
+
};
|
|
480
|
+
let resolveStopped = () => { };
|
|
481
|
+
server.stopped = new Promise((resolve) => (resolveStopped = resolve));
|
|
482
|
+
server.once('close', () => setImmediate(() => void stopAll().then(resolveStopped)));
|
|
483
|
+
const originalClose = server.close.bind(server);
|
|
484
|
+
server.close = ((callback) => {
|
|
485
|
+
reload?.stop();
|
|
486
|
+
return originalClose(callback);
|
|
487
|
+
});
|
|
488
|
+
await new Promise((resolve, reject) => {
|
|
489
|
+
server.once('error', reject);
|
|
490
|
+
server.listen(port, LISTEN_HOST, () => {
|
|
491
|
+
server.off('error', reject);
|
|
492
|
+
resolve();
|
|
493
|
+
});
|
|
494
|
+
});
|
|
495
|
+
try {
|
|
496
|
+
if (live && reload) {
|
|
497
|
+
const hub = reload;
|
|
498
|
+
const code = createLiveCodeWatcher({
|
|
499
|
+
cwd: options.cwd,
|
|
500
|
+
...(live.polling === undefined ? {} : { polling: live.polling }),
|
|
501
|
+
...(live.codePollingIntervalMs === undefined ? {} : { pollingIntervalMs: live.codePollingIntervalMs }),
|
|
502
|
+
log: (line) => log(redact(`${TAG} ${line}`)),
|
|
503
|
+
onChange: (files) => hub.notify(files),
|
|
504
|
+
onError: (error) => log(redact(`${TAG} code watching: ${error?.message ?? String(error)}`)),
|
|
505
|
+
});
|
|
506
|
+
stops.push(() => code.stop());
|
|
507
|
+
await code.start();
|
|
508
|
+
const initial = await hub.refresh();
|
|
509
|
+
if (initial.length)
|
|
510
|
+
log(redact(`${TAG} ${initial.length} problem(s) in the local code; open pages show them until they are ` +
|
|
511
|
+
`fixed:\n${initial.map(formatProblem).join('\n')}`));
|
|
512
|
+
}
|
|
513
|
+
else {
|
|
514
|
+
const diagnostics = await descriptorDiagnostics(options.cwd);
|
|
515
|
+
const errors = diagnostics.filter((d) => d.severity === 'error').map(toProblem);
|
|
516
|
+
if (errors.length)
|
|
517
|
+
log(redact(`${TAG} ${DESCRIPTOR_PATH} has ${errors.length} error(s):\n${errors.map(formatProblem).join('\n')}`));
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
catch (error) {
|
|
521
|
+
reload?.stop();
|
|
522
|
+
await new Promise((resolve) => originalClose(() => resolve()));
|
|
523
|
+
await server.stopped;
|
|
524
|
+
throw error;
|
|
525
|
+
}
|
|
526
|
+
return server;
|
|
527
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// Reading a response of the remote site in `foliwake dev --remote` (remote-dev.ts):
|
|
2
|
+
// a size limit on the body and a short reason for a failed request.
|
|
3
|
+
/** The body is over the limit; the rest of it was cancelled. */
|
|
4
|
+
export class TooLarge extends Error {
|
|
5
|
+
}
|
|
6
|
+
export async function readLimited(response, limit) {
|
|
7
|
+
const declared = Number(response.headers.get('content-length'));
|
|
8
|
+
if (Number.isFinite(declared) && declared > limit) {
|
|
9
|
+
await response.body?.cancel().catch(() => { });
|
|
10
|
+
throw new TooLarge();
|
|
11
|
+
}
|
|
12
|
+
if (!response.body)
|
|
13
|
+
return Buffer.alloc(0);
|
|
14
|
+
const chunks = [];
|
|
15
|
+
let total = 0;
|
|
16
|
+
const reader = response.body.getReader();
|
|
17
|
+
for (;;) {
|
|
18
|
+
const { done, value } = await reader.read();
|
|
19
|
+
if (done)
|
|
20
|
+
break;
|
|
21
|
+
total += value.byteLength;
|
|
22
|
+
if (total > limit) {
|
|
23
|
+
await reader.cancel().catch(() => { });
|
|
24
|
+
throw new TooLarge();
|
|
25
|
+
}
|
|
26
|
+
chunks.push(Buffer.from(value));
|
|
27
|
+
}
|
|
28
|
+
return Buffer.concat(chunks);
|
|
29
|
+
}
|
|
30
|
+
export function errorReason(error) {
|
|
31
|
+
const cause = error !== null && typeof error === 'object' && 'cause' in error ? error.cause : null;
|
|
32
|
+
const code = cause !== null && typeof cause === 'object' && 'code' in cause ? String(cause.code) : null;
|
|
33
|
+
if (error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError'))
|
|
34
|
+
return 'no answer within the time limit';
|
|
35
|
+
return code ?? (error instanceof Error ? error.message : String(error));
|
|
36
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { DevProblem } from './dev-reload.js';
|
|
2
|
+
export declare function problemsBanner(title: string, problems: readonly DevProblem[]): string;
|
|
3
|
+
export declare function noticeBanner(text: string): string;
|
|
4
|
+
export declare function renderRemoteErrorPage({ title, lines, detail, }: {
|
|
5
|
+
title: string;
|
|
6
|
+
lines: readonly string[];
|
|
7
|
+
detail?: string | null;
|
|
8
|
+
}): string;
|
|
9
|
+
/** `/_dev/blocks` and the block catalog: not available without a block renderer. */
|
|
10
|
+
export declare function blockCatalogStub(): string;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// HTML of `foliwake dev --remote` itself: the problem and notice banners above a remote page, its error
|
|
2
|
+
// pages, and the stub of the block catalog.
|
|
3
|
+
import { escapeHtml } from './html.js';
|
|
4
|
+
const BANNER_STYLE = 'font:14px/1.45 system-ui,sans-serif;color:#1b1b1b;padding:10px 16px';
|
|
5
|
+
const ALERT_STYLE = `${BANNER_STYLE};background:#fff5f5;border-bottom:4px solid #b00020`;
|
|
6
|
+
const NOTICE_STYLE = `${BANNER_STYLE};background:#fffaf0;border-bottom:4px solid #a15c00`;
|
|
7
|
+
const ERROR_PAGE_STYLE = 'body{font:15px/1.5 system-ui,sans-serif;margin:2rem auto;max-width:60rem;padding:0 1rem;color:#1b1b1b}' +
|
|
8
|
+
'h1{font-size:1.4rem}' +
|
|
9
|
+
'pre{white-space:pre-wrap;background:#f6f6f6;padding:.6rem .8rem;border-left:4px solid #b00020}';
|
|
10
|
+
const DIAGNOSTICS_LINK = 'local diagnostics: <a href="/_dev/diagnostics">/_dev/diagnostics</a>';
|
|
11
|
+
function problemItem(p) {
|
|
12
|
+
const where = p.line == null ? p.file : `${p.file}:${p.line}${p.column == null ? '' : `:${p.column}`}`;
|
|
13
|
+
const fix = p.fix ? `<br>Fix: ${escapeHtml(p.fix)}` : '';
|
|
14
|
+
return `<li><code>${escapeHtml(where)}</code> <code>${escapeHtml(p.code)}</code> ${escapeHtml(p.message)}${fix}</li>`;
|
|
15
|
+
}
|
|
16
|
+
/** The problems as JSON inside a script element: `<`, `>` and `&` escaped. */
|
|
17
|
+
function problemsJson(problems) {
|
|
18
|
+
return JSON.stringify(problems).replace(/</g, '\\u003c').replace(/>/g, '\\u003e').replace(/&/g, '\\u0026');
|
|
19
|
+
}
|
|
20
|
+
export function problemsBanner(title, problems) {
|
|
21
|
+
const items = problems.map(problemItem).join('');
|
|
22
|
+
const list = items ? `<ol style="margin:6px 0;padding-left:20px">${items}</ol>` : '';
|
|
23
|
+
return `<div data-foliwake-dev-banner role="alert" style="${ALERT_STYLE}">
|
|
24
|
+
<strong>${escapeHtml(title)}</strong>${list}
|
|
25
|
+
</div>
|
|
26
|
+
<script type="application/json" data-foliwake-dev-problems>${problemsJson(problems)}</script>`;
|
|
27
|
+
}
|
|
28
|
+
export function noticeBanner(text) {
|
|
29
|
+
return `<div data-foliwake-dev-banner role="status" style="${NOTICE_STYLE}">${escapeHtml(text)}</div>`;
|
|
30
|
+
}
|
|
31
|
+
export function renderRemoteErrorPage({ title, lines, detail, }) {
|
|
32
|
+
return `<!doctype html>
|
|
33
|
+
<html lang="en">
|
|
34
|
+
<head>
|
|
35
|
+
<meta charset="utf-8">
|
|
36
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
37
|
+
<meta name="robots" content="noindex">
|
|
38
|
+
<title>${escapeHtml(title)}</title>
|
|
39
|
+
<style>${ERROR_PAGE_STYLE}</style>
|
|
40
|
+
</head>
|
|
41
|
+
<body data-foliwake-dev-error>
|
|
42
|
+
<h1>${escapeHtml(title)}</h1>
|
|
43
|
+
${lines.map((line) => ` <p>${escapeHtml(line)}</p>`).join('\n')}${detail ? `\n <pre>${escapeHtml(detail)}</pre>` : ''}
|
|
44
|
+
<p style="color:#555">foliwake dev --remote · ${DIAGNOSTICS_LINK}</p>
|
|
45
|
+
</body>
|
|
46
|
+
</html>
|
|
47
|
+
`;
|
|
48
|
+
}
|
|
49
|
+
/** `/_dev/blocks` and the block catalog: not available without a block renderer. */
|
|
50
|
+
export function blockCatalogStub() {
|
|
51
|
+
return renderRemoteErrorPage({
|
|
52
|
+
title: 'Block catalog not available',
|
|
53
|
+
lines: [
|
|
54
|
+
'The block catalog renders the examples of your blocks (components/<name>/<name>.example.md).',
|
|
55
|
+
`Rendering them needs the Foliwake engine (\`foliwake dev\` from the engine) or the open block ` +
|
|
56
|
+
'renderer, which is not available yet.',
|
|
57
|
+
'Pages from the remote site work as usual: open any page path.',
|
|
58
|
+
],
|
|
59
|
+
});
|
|
60
|
+
}
|