@pwfabric/cli 1.0.0-rc.1 → 1.0.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/dist/dev/shell.d.ts +5 -9
- package/dist/dev/shell.js +6 -29
- package/dist/dev/shell.js.map +1 -1
- package/dist/host/local-host.js +1 -1
- package/dist/host/local-host.js.map +1 -1
- package/package.json +8 -8
package/dist/dev/shell.d.ts
CHANGED
|
@@ -14,21 +14,17 @@ export declare function loadRuntimeAssets(): Promise<RuntimeAssets>;
|
|
|
14
14
|
* the shell seeds each from (see {@link buildShellHtml}), so blocks that reach
|
|
15
15
|
* for these get the renderer's own instance instead of `undefined`.
|
|
16
16
|
*
|
|
17
|
-
* The renderer bundle (`@pwfabric/embed`'s `embed.js`) carries `react-dom
|
|
18
|
-
* `@pwfabric/core`
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
17
|
+
* The renderer bundle (`@pwfabric/embed`'s `embed.js`) carries `react-dom`
|
|
18
|
+
* and `@pwfabric/core` in its `__PW_VENDOR__` table but does not seed these
|
|
19
|
+
* globals itself, so a block that uses a VALUE from core (as opposed to a
|
|
20
|
+
* type) reads the renderer's instance here instead of `undefined`. The
|
|
21
|
+
* authoring kit (`__pwfabric_sdk`) the renderer seeds itself.
|
|
22
22
|
*/
|
|
23
23
|
export declare const SHELL_SEEDED_GLOBALS: Readonly<Record<string, string>>;
|
|
24
|
-
/** Whether `name` can be an `export const { name }` binding. */
|
|
25
|
-
export declare function isExportableName(name: string): boolean;
|
|
26
24
|
/** Evaluates the renderer bundle in an isolated context and returns what it put on `globalThis`. */
|
|
27
25
|
export declare function seededGlobals(embedJs: string): Record<string, unknown>;
|
|
28
26
|
/** The global each shim file reads (every specifier sharing a shim names the same global). */
|
|
29
27
|
export declare function shimGlobal(shim: string): string;
|
|
30
|
-
/** Source of one shim module. */
|
|
31
|
-
export declare function shimSource(shim: string, global: string, names: readonly string[]): string;
|
|
32
28
|
/**
|
|
33
29
|
* Every shim file the import map can point at, with its source.
|
|
34
30
|
*
|
package/dist/dev/shell.js
CHANGED
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
import { readFile } from 'node:fs/promises';
|
|
18
18
|
import { createRequire } from 'node:module';
|
|
19
19
|
import vm from 'node:vm';
|
|
20
|
-
import { BLOCK_HOST_IMPORTS, blockImportMap, blockShimFiles,
|
|
20
|
+
import { BLOCK_HOST_IMPORTS, blockImportMap, blockShimFiles, shimSource, } from '@pwfabric/core';
|
|
21
21
|
import { webfontStylesheetHref, themeWebfonts } from './theme.js';
|
|
22
22
|
const require = createRequire(import.meta.url);
|
|
23
23
|
let cachedAssets = null;
|
|
@@ -45,16 +45,15 @@ const VENDOR_GLOBAL = '__PW_VENDOR__';
|
|
|
45
45
|
* the shell seeds each from (see {@link buildShellHtml}), so blocks that reach
|
|
46
46
|
* for these get the renderer's own instance instead of `undefined`.
|
|
47
47
|
*
|
|
48
|
-
* The renderer bundle (`@pwfabric/embed`'s `embed.js`) carries `react-dom
|
|
49
|
-
* `@pwfabric/core`
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
*
|
|
48
|
+
* The renderer bundle (`@pwfabric/embed`'s `embed.js`) carries `react-dom`
|
|
49
|
+
* and `@pwfabric/core` in its `__PW_VENDOR__` table but does not seed these
|
|
50
|
+
* globals itself, so a block that uses a VALUE from core (as opposed to a
|
|
51
|
+
* type) reads the renderer's instance here instead of `undefined`. The
|
|
52
|
+
* authoring kit (`__pwfabric_sdk`) the renderer seeds itself.
|
|
53
53
|
*/
|
|
54
54
|
export const SHELL_SEEDED_GLOBALS = {
|
|
55
55
|
__pwfabric_react_dom: 'react-dom',
|
|
56
56
|
__pwfabric_core: '@pwfabric/core',
|
|
57
|
-
__pwfabric_sdk: '@pwfabric/authoring',
|
|
58
57
|
};
|
|
59
58
|
/** Packages to read export names from when no bundle seeds their global. */
|
|
60
59
|
const NAME_SOURCES = {
|
|
@@ -65,13 +64,6 @@ const NAME_SOURCES = {
|
|
|
65
64
|
const FALLBACK_NAMES = {
|
|
66
65
|
__pwfabric_sdk: ['defineBlock'],
|
|
67
66
|
};
|
|
68
|
-
const RESERVED = new Set(('break case catch class const continue debugger default delete do else enum export extends false finally for ' +
|
|
69
|
-
'function if import in instanceof new null return super switch this throw true try typeof var void while with ' +
|
|
70
|
-
'yield let static implements interface package private protected public await arguments eval').split(' '));
|
|
71
|
-
/** Whether `name` can be an `export const { name }` binding. */
|
|
72
|
-
export function isExportableName(name) {
|
|
73
|
-
return /^[A-Za-z_$][\w$]*$/.test(name) && !RESERVED.has(name);
|
|
74
|
-
}
|
|
75
67
|
/** Evaluates the renderer bundle in an isolated context and returns what it put on `globalThis`. */
|
|
76
68
|
export function seededGlobals(embedJs) {
|
|
77
69
|
const sandbox = { console, setTimeout, clearTimeout, queueMicrotask };
|
|
@@ -105,21 +97,6 @@ export function shimGlobal(shim) {
|
|
|
105
97
|
const entry = BLOCK_HOST_IMPORTS.find((i) => i.shim === shim && i.global);
|
|
106
98
|
return entry?.global ?? `__pwfabric_${shim.replace(/[^A-Za-z0-9]+/g, '_')}`;
|
|
107
99
|
}
|
|
108
|
-
/** Source of one shim module. */
|
|
109
|
-
export function shimSource(shim, global, names) {
|
|
110
|
-
const exported = [...new Set(names)].filter(isExportableName).sort();
|
|
111
|
-
const specifiers = specifiersForShim(shim);
|
|
112
|
-
const lines = [
|
|
113
|
-
`// Generated by pwf. Serves ${specifiers.map((s) => `'${s}'`).join(', ')} to compiled blocks:`,
|
|
114
|
-
`// re-exports the instance the page seeded on globalThis.${global}.`,
|
|
115
|
-
`const m = globalThis.${global} ?? {}`,
|
|
116
|
-
'export default m',
|
|
117
|
-
];
|
|
118
|
-
if (exported.length > 0) {
|
|
119
|
-
lines.push(`export const {\n${exported.map((n) => ` ${n},`).join('\n')}\n} = m`);
|
|
120
|
-
}
|
|
121
|
-
return `${lines.join('\n')}\n`;
|
|
122
|
-
}
|
|
123
100
|
/**
|
|
124
101
|
* Every shim file the import map can point at, with its source.
|
|
125
102
|
*
|
package/dist/dev/shell.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shell.js","sourceRoot":"","sources":["../../src/dev/shell.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAA;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAC3C,OAAO,EAAE,MAAM,SAAS,CAAA;AACxB,OAAO,EACL,kBAAkB,EAClB,cAAc,EACd,cAAc,EACd,iBAAiB,GAClB,MAAM,gBAAgB,CAAA;AACvB,OAAO,EAAE,qBAAqB,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAEjE,MAAM,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;AAY9C,IAAI,YAAY,GAAkC,IAAI,CAAA;AAEtD,iGAAiG;AACjG,MAAM,UAAU,iBAAiB;IAC/B,YAAY,KAAK,CAAC,KAAK,IAAI,EAAE;QAC3B,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,kBAAkB,CAAC,CAAA;QACtD,MAAM,SAAS,GAAG,OAAO,CAAC,OAAO,CAAC,0BAA0B,CAAC,CAAA;QAC7D,MAAM,CAAC,QAAQ,EAAE,OAAO,EAAE,SAAS,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;YACvD,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;YAC5B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;YAC3B,QAAQ,CAAC,GAAG,UAAU,MAAM,EAAE,MAAM,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC;SAC7D,CAAC,CAAA;QACF,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,CAAC,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,C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The runtime half of a pwapp: the shell page, the runner and renderer\n * bundles, and the shim modules the import map points at.\n *\n * Every bare specifier a compiled block may import comes from one list in\n * the engine (`BLOCK_HOST_IMPORTS`). The import map and the shim files are\n * derived from it here, so a block compiled against that list always links.\n *\n * A shim re-exports a global the renderer seeded from its own bundled copy\n * (one React, one runtime, one zod for every block). Its named exports are\n * not typed out by hand: they are read off the very globals the renderer\n * bundle seeds, by evaluating that bundle once in an isolated context. An\n * ESM import of a name a shim does not export fails the whole module at link\n * time, so the list has to be complete — and reading it from the bundle that\n * serves it is the only way it stays complete.\n */\nimport { readFile } from 'node:fs/promises'\nimport { createRequire } from 'node:module'\nimport vm from 'node:vm'\nimport {\n BLOCK_HOST_IMPORTS,\n blockImportMap,\n blockShimFiles,\n specifiersForShim,\n} from '@pwfabric/core'\nimport { webfontStylesheetHref, themeWebfonts } from './theme.js'\n\nconst require = createRequire(import.meta.url)\n\n/** The runner and renderer bundles a pwapp ships. */\nexport interface RuntimeAssets {\n /** `assets/runner.js` — the ES module exporting `runApp`. */\n readonly runnerJs: string\n /** Its source map, when the build has one. */\n readonly runnerMap?: string\n /** `assets/embed.js` — the classic script that defines `window.PWFabric`. */\n readonly embedJs: string\n}\n\nlet cachedAssets: Promise<RuntimeAssets> | null = null\n\n/** Reads the built runner and renderer from the installed engine packages (once per process). */\nexport function loadRuntimeAssets(): Promise<RuntimeAssets> {\n cachedAssets ??= (async () => {\n const runnerPath = require.resolve('@pwfabric/runner')\n const embedPath = require.resolve('@pwfabric/embed/embed.js')\n const [runnerJs, embedJs, runnerMap] = await Promise.all([\n readFile(runnerPath, 'utf8'),\n readFile(embedPath, 'utf8'),\n readFile(`${runnerPath}.map`, 'utf8').catch(() => undefined),\n ])\n return { runnerJs, embedJs, ...(runnerMap !== undefined ? { runnerMap } : {}) }\n })()\n cachedAssets.catch(() => {\n cachedAssets = null\n })\n return cachedAssets\n}\n\n/** The vendor table the renderer exposes besides the `__pwfabric_*` globals. */\nconst VENDOR_GLOBAL = '__PW_VENDOR__'\n\n/**\n * Globals the renderer bundle does not seed itself, and the vendor-table key\n * the shell seeds each from (see {@link buildShellHtml}), so blocks that reach\n * for these get the renderer's own instance instead of `undefined`.\n *\n * The renderer bundle (`@pwfabric/embed`'s `embed.js`) carries `react-dom`,\n * `@pwfabric/core` and `@pwfabric/authoring` (the `sdk@v1` shim's package)\n * in its `__PW_VENDOR__` table but does not seed these globals itself, so a\n * block that uses a VALUE from core or the authoring kit (as opposed to a\n * type) reads the renderer's instance here instead of `undefined`.\n */\nexport const SHELL_SEEDED_GLOBALS: Readonly<Record<string, string>> = {\n __pwfabric_react_dom: 'react-dom',\n __pwfabric_core: '@pwfabric/core',\n __pwfabric_sdk: '@pwfabric/authoring',\n}\n\n/** Packages to read export names from when no bundle seeds their global. */\nconst NAME_SOURCES: Readonly<Record<string, string>> = {\n __pwfabric_core: '@pwfabric/core',\n __pwfabric_sdk: '@pwfabric/authoring',\n}\n\n/** Export names a shim falls back to when neither a bundle nor a package says more. */\nconst FALLBACK_NAMES: Readonly<Record<string, readonly string[]>> = {\n __pwfabric_sdk: ['defineBlock'],\n}\n\nconst RESERVED = new Set(\n (\n 'break case catch class const continue debugger default delete do else enum export extends false finally for ' +\n 'function if import in instanceof new null return super switch this throw true try typeof var void while with ' +\n 'yield let static implements interface package private protected public await arguments eval'\n ).split(' ')\n)\n\n/** Whether `name` can be an `export const { name }` binding. */\nexport function isExportableName(name: string): boolean {\n return /^[A-Za-z_$][\\w$]*$/.test(name) && !RESERVED.has(name)\n}\n\n/** Evaluates the renderer bundle in an isolated context and returns what it put on `globalThis`. */\nexport function seededGlobals(embedJs: string): Record<string, unknown> {\n const sandbox: Record<string, unknown> = { console, setTimeout, clearTimeout, queueMicrotask }\n sandbox['globalThis'] = sandbox\n sandbox['self'] = sandbox\n const context = vm.createContext(sandbox)\n try {\n vm.runInContext(embedJs, context, { filename: 'embed.js', timeout: 10_000 })\n } catch {\n // A bundle that needs a document past its globals still seeded them first.\n }\n const out: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(sandbox)) {\n if (k.startsWith('__pwfabric_') || k === VENDOR_GLOBAL) out[k] = v\n }\n return out\n}\n\nasync function namesFromPackage(pkg: string): Promise<string[] | null> {\n try {\n const mod = (await import(pkg)) as Record<string, unknown>\n return Object.keys(mod)\n } catch {\n return null\n }\n}\n\n/** The global each shim file reads (every specifier sharing a shim names the same global). */\nexport function shimGlobal(shim: string): string {\n const entry = BLOCK_HOST_IMPORTS.find((i) => i.shim === shim && i.global)\n return entry?.global ?? `__pwfabric_${shim.replace(/[^A-Za-z0-9]+/g, '_')}`\n}\n\n/** Source of one shim module. */\nexport function shimSource(shim: string, global: string, names: readonly string[]): string {\n const exported = [...new Set(names)].filter(isExportableName).sort()\n const specifiers = specifiersForShim(shim)\n const lines = [\n `// Generated by pwf. Serves ${specifiers.map((s) => `'${s}'`).join(', ')} to compiled blocks:`,\n `// re-exports the instance the page seeded on globalThis.${global}.`,\n `const m = globalThis.${global} ?? {}`,\n 'export default m',\n ]\n if (exported.length > 0) {\n lines.push(`export const {\\n${exported.map((n) => ` ${n},`).join('\\n')}\\n} = m`)\n }\n return `${lines.join('\\n')}\\n`\n}\n\n/**\n * Every shim file the import map can point at, with its source.\n *\n * Names come from, in order: the global the renderer seeds; the vendor table\n * entry the shell seeds the global from; the package itself (for globals no\n * standalone page seeds — their exports resolve to `undefined`, which keeps a\n * block linking instead of failing at load).\n */\nexport async function buildShims(embedJs: string): Promise<Map<string, string>> {\n const seeded = seededGlobals(embedJs)\n const vendor = (seeded[VENDOR_GLOBAL] ?? {}) as Record<string, unknown>\n const out = new Map<string, string>()\n for (const shim of blockShimFiles()) {\n const global = shimGlobal(shim)\n let names: string[] | null = null\n const value = seeded[global]\n if (value && typeof value === 'object') names = Object.keys(value)\n const vendorKey = SHELL_SEEDED_GLOBALS[global]\n if (!names && vendorKey && vendor[vendorKey] && typeof vendor[vendorKey] === 'object') {\n names = Object.keys(vendor[vendorKey] as object)\n }\n if (!names && NAME_SOURCES[global]) names = await namesFromPackage(NAME_SOURCES[global] as string)\n out.set(shim, shimSource(shim, global, names ?? [...(FALLBACK_NAMES[global] ?? [])]))\n }\n return out\n}\n\nlet cachedShims: { embedJs: string; shims: Promise<Map<string, string>> } | null = null\n\n/** {@link buildShims}, once per renderer bundle. */\nexport function shimsFor(embedJs: string): Promise<Map<string, string>> {\n if (cachedShims?.embedJs !== embedJs) cachedShims = { embedJs, shims: buildShims(embedJs) }\n return cachedShims.shims\n}\n\n/** The import map: every host import → `./shims/<file>`. */\nexport function importMap(): { readonly imports: Record<string, string> } {\n return blockImportMap('./shims')\n}\n\nexport function escapeHtml(s: string): string {\n return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\"/g, '"')\n}\n\n/** JSON safe to place inside a `<script>` element. */\nexport function scriptJson(value: unknown): string {\n return JSON.stringify(value).replace(/</g, '\\\\u003c')\n}\n\nexport interface ShellOptions {\n readonly title: string\n /** `<html lang>`; default `en`. */\n readonly lang?: string\n /** The app's appearance configuration (its webfonts are linked). */\n readonly appearance?: Record<string, unknown>\n /** Markup appended to `<body>` (the dev server's reload client). */\n readonly bodyExtra?: string\n /** The policy for the shell's `<meta http-equiv=\"Content-Security-Policy\">`; none when absent. */\n readonly csp?: string\n}\n\n/** The exact text of the shell's inline import map (the CSP hashes this). */\nexport function importMapText(): string {\n return scriptJson(importMap())\n}\n\n/**\n * `assets/seed.js`: seeds the globals the renderer does not seed itself from\n * its vendor table (a file, not an inline script, so the policy needs no hash).\n */\nexport function seedScript(): string {\n const seeds = Object.entries(SHELL_SEEDED_GLOBALS)\n .map(([global, key]) => ` g.${global} = g.${global} || v[${JSON.stringify(key)}];`)\n .join('\\n')\n return `// Generated by pwf: globals the renderer carries in ${VENDOR_GLOBAL} but does not seed.\n(function (g) {\n var v = g.${VENDOR_GLOBAL} || {};\n${seeds}\n})(globalThis)\n`\n}\n\n/** `assets/boot.js`: the module that starts the runner. */\nexport function bootScript(locale: 'en' | 'tr' = 'en'): string {\n return `// Generated by pwf: starts the app.\nimport { runApp } from './runner.js'\n\nrunApp({ source: './pwpack', blocks: './blocks/', engines: './engines', router: 'hash', locale: '${locale}' })\n`\n}\n\n/** A BCP-47-looking tag, or `en`. */\nexport function htmlLangOf(locale: string | undefined): string {\n const tag = (locale ?? '').trim()\n return /^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/.test(tag) ? tag : 'en'\n}\n\n/** `tr-TR` → `tr`; the runner's copy knows `en` and `tr`. */\nexport function runnerLocaleOf(locale: string | undefined): 'en' | 'tr' {\n return /^tr(?:[-_]|$)/i.test(locale ?? '') ? 'tr' : 'en'\n}\n\n/**\n * `index.html`, in the order the pwapp format requires: import map, the\n * renderer (a classic script that seeds the shared globals) and `seed.js`,\n * the mount element, then `boot.js`, which starts the runner. The import map\n * is the only inline script, so a Content Security Policy needs one hash.\n * Every address is relative, so the folder works at a host root, under a\n * sub-path, or from disk behind any static server.\n */\nexport function buildShellHtml(options: ShellOptions): string {\n const href = webfontStylesheetHref(themeWebfonts(options.appearance))\n const fonts = href\n ? `\n <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\" />\n <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin />\n <link rel=\"stylesheet\" href=\"${escapeHtml(href)}\" />`\n : ''\n const csp = options.csp\n ? `\n <meta http-equiv=\"Content-Security-Policy\" content=\"${escapeHtml(options.csp)}\" />`\n : ''\n return `<!doctype html>\n<html lang=\"${escapeHtml(htmlLangOf(options.lang))}\">\n <head>\n <meta charset=\"UTF-8\" />${csp}\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <title>${escapeHtml(options.title)}</title>\n <link rel=\"icon\" href=\"data:,\" />\n <link rel=\"stylesheet\" href=\"./assets/theme.css\" />${fonts}\n <script type=\"importmap\">${importMapText()}</script>\n <script src=\"./assets/embed.js\"></script>\n <script src=\"./assets/seed.js\"></script>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"module\" src=\"./assets/boot.js\"></script>${options.bodyExtra ?? ''}\n </body>\n</html>\n`\n}\n\n/**\n * The shell with `<base href=\"/\">` as the first element of its head, unless it\n * already declares a base.\n *\n * The shell addresses its scripts and the import map relatively (`./assets/…`,\n * `./shims/…`) so the folder works under any sub-path. When a server answers a\n * nested page path (`/team/members`) with that shell, the browser would resolve\n * those addresses against `/team/` and miss every file. The pwapp format puts\n * the fix on the host: under path routing it declares the app's base with\n * `<base href>`. This server serves the app at its root, so the base is `/`.\n */\nexport function withBaseHref(body: Uint8Array, href = '/'): Uint8Array {\n const html = new TextDecoder().decode(body)\n if (/<bases/i.test(html)) return body\n const at = html.search(/<head[^>]*>/i)\n if (at < 0) return body\n const end = html.indexOf('>', at) + 1\n const tag = `\n <base href=\"${href.replace(/\"/g, '"')}\" />`\n return new TextEncoder().encode(html.slice(0, end) + tag + html.slice(end))\n}\n"]}
|
|
1
|
+
{"version":3,"file":"shell.js","sourceRoot":"","sources":["../../src/dev/shell.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAA;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAC3C,OAAO,EAAE,MAAM,SAAS,CAAA;AACxB,OAAO,EACL,kBAAkB,EAClB,cAAc,EACd,cAAc,EACd,UAAU,GACX,MAAM,gBAAgB,CAAA;AACvB,OAAO,EAAE,qBAAqB,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAEjE,MAAM,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;AAY9C,IAAI,YAAY,GAAkC,IAAI,CAAA;AAEtD,iGAAiG;AACjG,MAAM,UAAU,iBAAiB;IAC/B,YAAY,KAAK,CAAC,KAAK,IAAI,EAAE;QAC3B,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,kBAAkB,CAAC,CAAA;QACtD,MAAM,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IAAI,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC;QAAE,OAAO,IAAI,CAAA;IACrC,MAAM,EAAE,GAAG,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC,CAAA;IACtC,IAAI,EAAE,GAAG,CAAC;QAAE,OAAO,IAAI,CAAA;IACvB,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,CAAA;IACrC,MAAM,GAAG,GAAG;kBACI,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,MAAM,CAAA;IAClD,OAAO,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,GAAG,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAA;AAC7E,CAAC","sourcesContent":["/**\n * The runtime half of a pwapp: the shell page, the runner and renderer\n * bundles, and the shim modules the import map points at.\n *\n * Every bare specifier a compiled block may import comes from one list in\n * the engine (`BLOCK_HOST_IMPORTS`). The import map and the shim files are\n * derived from it here, so a block compiled against that list always links.\n *\n * A shim re-exports a global the renderer seeded from its own bundled copy\n * (one React, one runtime, one zod for every block). Its named exports are\n * not typed out by hand: they are read off the very globals the renderer\n * bundle seeds, by evaluating that bundle once in an isolated context. An\n * ESM import of a name a shim does not export fails the whole module at link\n * time, so the list has to be complete — and reading it from the bundle that\n * serves it is the only way it stays complete.\n */\nimport { readFile } from 'node:fs/promises'\nimport { createRequire } from 'node:module'\nimport vm from 'node:vm'\nimport {\n BLOCK_HOST_IMPORTS,\n blockImportMap,\n blockShimFiles,\n shimSource,\n} from '@pwfabric/core'\nimport { webfontStylesheetHref, themeWebfonts } from './theme.js'\n\nconst require = createRequire(import.meta.url)\n\n/** The runner and renderer bundles a pwapp ships. */\nexport interface RuntimeAssets {\n /** `assets/runner.js` — the ES module exporting `runApp`. */\n readonly runnerJs: string\n /** Its source map, when the build has one. */\n readonly runnerMap?: string\n /** `assets/embed.js` — the classic script that defines `window.PWFabric`. */\n readonly embedJs: string\n}\n\nlet cachedAssets: Promise<RuntimeAssets> | null = null\n\n/** Reads the built runner and renderer from the installed engine packages (once per process). */\nexport function loadRuntimeAssets(): Promise<RuntimeAssets> {\n cachedAssets ??= (async () => {\n const runnerPath = require.resolve('@pwfabric/runner')\n const embedPath = require.resolve('@pwfabric/embed/embed.js')\n const [runnerJs, embedJs, runnerMap] = await Promise.all([\n readFile(runnerPath, 'utf8'),\n readFile(embedPath, 'utf8'),\n readFile(`${runnerPath}.map`, 'utf8').catch(() => undefined),\n ])\n return { runnerJs, embedJs, ...(runnerMap !== undefined ? { runnerMap } : {}) }\n })()\n cachedAssets.catch(() => {\n cachedAssets = null\n })\n return cachedAssets\n}\n\n/** The vendor table the renderer exposes besides the `__pwfabric_*` globals. */\nconst VENDOR_GLOBAL = '__PW_VENDOR__'\n\n/**\n * Globals the renderer bundle does not seed itself, and the vendor-table key\n * the shell seeds each from (see {@link buildShellHtml}), so blocks that reach\n * for these get the renderer's own instance instead of `undefined`.\n *\n * The renderer bundle (`@pwfabric/embed`'s `embed.js`) carries `react-dom`\n * and `@pwfabric/core` in its `__PW_VENDOR__` table but does not seed these\n * globals itself, so a block that uses a VALUE from core (as opposed to a\n * type) reads the renderer's instance here instead of `undefined`. The\n * authoring kit (`__pwfabric_sdk`) the renderer seeds itself.\n */\nexport const SHELL_SEEDED_GLOBALS: Readonly<Record<string, string>> = {\n __pwfabric_react_dom: 'react-dom',\n __pwfabric_core: '@pwfabric/core',\n}\n\n/** Packages to read export names from when no bundle seeds their global. */\nconst NAME_SOURCES: Readonly<Record<string, string>> = {\n __pwfabric_core: '@pwfabric/core',\n __pwfabric_sdk: '@pwfabric/authoring',\n}\n\n/** Export names a shim falls back to when neither a bundle nor a package says more. */\nconst FALLBACK_NAMES: Readonly<Record<string, readonly string[]>> = {\n __pwfabric_sdk: ['defineBlock'],\n}\n\n/** Evaluates the renderer bundle in an isolated context and returns what it put on `globalThis`. */\nexport function seededGlobals(embedJs: string): Record<string, unknown> {\n const sandbox: Record<string, unknown> = { console, setTimeout, clearTimeout, queueMicrotask }\n sandbox['globalThis'] = sandbox\n sandbox['self'] = sandbox\n const context = vm.createContext(sandbox)\n try {\n vm.runInContext(embedJs, context, { filename: 'embed.js', timeout: 10_000 })\n } catch {\n // A bundle that needs a document past its globals still seeded them first.\n }\n const out: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(sandbox)) {\n if (k.startsWith('__pwfabric_') || k === VENDOR_GLOBAL) out[k] = v\n }\n return out\n}\n\nasync function namesFromPackage(pkg: string): Promise<string[] | null> {\n try {\n const mod = (await import(pkg)) as Record<string, unknown>\n return Object.keys(mod)\n } catch {\n return null\n }\n}\n\n/** The global each shim file reads (every specifier sharing a shim names the same global). */\nexport function shimGlobal(shim: string): string {\n const entry = BLOCK_HOST_IMPORTS.find((i) => i.shim === shim && i.global)\n return entry?.global ?? `__pwfabric_${shim.replace(/[^A-Za-z0-9]+/g, '_')}`\n}\n\n/**\n * Every shim file the import map can point at, with its source.\n *\n * Names come from, in order: the global the renderer seeds; the vendor table\n * entry the shell seeds the global from; the package itself (for globals no\n * standalone page seeds — their exports resolve to `undefined`, which keeps a\n * block linking instead of failing at load).\n */\nexport async function buildShims(embedJs: string): Promise<Map<string, string>> {\n const seeded = seededGlobals(embedJs)\n const vendor = (seeded[VENDOR_GLOBAL] ?? {}) as Record<string, unknown>\n const out = new Map<string, string>()\n for (const shim of blockShimFiles()) {\n const global = shimGlobal(shim)\n let names: string[] | null = null\n const value = seeded[global]\n if (value && typeof value === 'object') names = Object.keys(value)\n const vendorKey = SHELL_SEEDED_GLOBALS[global]\n if (!names && vendorKey && vendor[vendorKey] && typeof vendor[vendorKey] === 'object') {\n names = Object.keys(vendor[vendorKey] as object)\n }\n if (!names && NAME_SOURCES[global]) names = await namesFromPackage(NAME_SOURCES[global] as string)\n out.set(shim, shimSource(shim, global, names ?? [...(FALLBACK_NAMES[global] ?? [])]))\n }\n return out\n}\n\nlet cachedShims: { embedJs: string; shims: Promise<Map<string, string>> } | null = null\n\n/** {@link buildShims}, once per renderer bundle. */\nexport function shimsFor(embedJs: string): Promise<Map<string, string>> {\n if (cachedShims?.embedJs !== embedJs) cachedShims = { embedJs, shims: buildShims(embedJs) }\n return cachedShims.shims\n}\n\n/** The import map: every host import → `./shims/<file>`. */\nexport function importMap(): { readonly imports: Record<string, string> } {\n return blockImportMap('./shims')\n}\n\nexport function escapeHtml(s: string): string {\n return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\"/g, '"')\n}\n\n/** JSON safe to place inside a `<script>` element. */\nexport function scriptJson(value: unknown): string {\n return JSON.stringify(value).replace(/</g, '\\\\u003c')\n}\n\nexport interface ShellOptions {\n readonly title: string\n /** `<html lang>`; default `en`. */\n readonly lang?: string\n /** The app's appearance configuration (its webfonts are linked). */\n readonly appearance?: Record<string, unknown>\n /** Markup appended to `<body>` (the dev server's reload client). */\n readonly bodyExtra?: string\n /** The policy for the shell's `<meta http-equiv=\"Content-Security-Policy\">`; none when absent. */\n readonly csp?: string\n}\n\n/** The exact text of the shell's inline import map (the CSP hashes this). */\nexport function importMapText(): string {\n return scriptJson(importMap())\n}\n\n/**\n * `assets/seed.js`: seeds the globals the renderer does not seed itself from\n * its vendor table (a file, not an inline script, so the policy needs no hash).\n */\nexport function seedScript(): string {\n const seeds = Object.entries(SHELL_SEEDED_GLOBALS)\n .map(([global, key]) => ` g.${global} = g.${global} || v[${JSON.stringify(key)}];`)\n .join('\\n')\n return `// Generated by pwf: globals the renderer carries in ${VENDOR_GLOBAL} but does not seed.\n(function (g) {\n var v = g.${VENDOR_GLOBAL} || {};\n${seeds}\n})(globalThis)\n`\n}\n\n/** `assets/boot.js`: the module that starts the runner. */\nexport function bootScript(locale: 'en' | 'tr' = 'en'): string {\n return `// Generated by pwf: starts the app.\nimport { runApp } from './runner.js'\n\nrunApp({ source: './pwpack', blocks: './blocks/', engines: './engines', router: 'hash', locale: '${locale}' })\n`\n}\n\n/** A BCP-47-looking tag, or `en`. */\nexport function htmlLangOf(locale: string | undefined): string {\n const tag = (locale ?? '').trim()\n return /^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/.test(tag) ? tag : 'en'\n}\n\n/** `tr-TR` → `tr`; the runner's copy knows `en` and `tr`. */\nexport function runnerLocaleOf(locale: string | undefined): 'en' | 'tr' {\n return /^tr(?:[-_]|$)/i.test(locale ?? '') ? 'tr' : 'en'\n}\n\n/**\n * `index.html`, in the order the pwapp format requires: import map, the\n * renderer (a classic script that seeds the shared globals) and `seed.js`,\n * the mount element, then `boot.js`, which starts the runner. The import map\n * is the only inline script, so a Content Security Policy needs one hash.\n * Every address is relative, so the folder works at a host root, under a\n * sub-path, or from disk behind any static server.\n */\nexport function buildShellHtml(options: ShellOptions): string {\n const href = webfontStylesheetHref(themeWebfonts(options.appearance))\n const fonts = href\n ? `\n <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\" />\n <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin />\n <link rel=\"stylesheet\" href=\"${escapeHtml(href)}\" />`\n : ''\n const csp = options.csp\n ? `\n <meta http-equiv=\"Content-Security-Policy\" content=\"${escapeHtml(options.csp)}\" />`\n : ''\n return `<!doctype html>\n<html lang=\"${escapeHtml(htmlLangOf(options.lang))}\">\n <head>\n <meta charset=\"UTF-8\" />${csp}\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <title>${escapeHtml(options.title)}</title>\n <link rel=\"icon\" href=\"data:,\" />\n <link rel=\"stylesheet\" href=\"./assets/theme.css\" />${fonts}\n <script type=\"importmap\">${importMapText()}</script>\n <script src=\"./assets/embed.js\"></script>\n <script src=\"./assets/seed.js\"></script>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"module\" src=\"./assets/boot.js\"></script>${options.bodyExtra ?? ''}\n </body>\n</html>\n`\n}\n\n/**\n * The shell with `<base href=\"/\">` as the first element of its head, unless it\n * already declares a base.\n *\n * The shell addresses its scripts and the import map relatively (`./assets/…`,\n * `./shims/…`) so the folder works under any sub-path. When a server answers a\n * nested page path (`/team/members`) with that shell, the browser would resolve\n * those addresses against `/team/` and miss every file. The pwapp format puts\n * the fix on the host: under path routing it declares the app's base with\n * `<base href>`. This server serves the app at its root, so the base is `/`.\n */\nexport function withBaseHref(body: Uint8Array, href = '/'): Uint8Array {\n const html = new TextDecoder().decode(body)\n if (/<bases/i.test(html)) return body\n const at = html.search(/<head[^>]*>/i)\n if (at < 0) return body\n const end = html.indexOf('>', at) + 1\n const tag = `\n <base href=\"${href.replace(/\"/g, '"')}\" />`\n return new TextEncoder().encode(html.slice(0, end) + tag + html.slice(end))\n}\n"]}
|
package/dist/host/local-host.js
CHANGED
|
@@ -46,7 +46,7 @@ export const SESSION_COOKIE = 'pwf_dev_session';
|
|
|
46
46
|
const SESSION_TTL_MS = 8 * 3600_000;
|
|
47
47
|
const TRANSACTION_TTL_MS = 5 * 60_000;
|
|
48
48
|
/** The provider buttons a session server can name (envelope `auth.json` `providers[].method`). */
|
|
49
|
-
const PROVIDER_METHODS = new Set(['
|
|
49
|
+
const PROVIDER_METHODS = new Set(['phiwebs', 'google', 'github', 'microsoft']);
|
|
50
50
|
function normalisePrefix(prefix) {
|
|
51
51
|
const trimmed = prefix.replace(/^\/+|\/+$/g, '');
|
|
52
52
|
if (!trimmed)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"local-host.js","sourceRoot":"","sources":["../../src/host/local-host.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAGH,OAAO,EACL,SAAS,EACT,SAAS,EACT,YAAY,EACZ,cAAc,EACd,QAAQ,EACR,YAAY,EACZ,SAAS,EACT,QAAQ,GACT,MAAM,WAAW,CAAA;AAClB,OAAO,EACL,QAAQ,EACR,YAAY,EACZ,WAAW,EACX,WAAW,GAGZ,MA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,CAAC,KAAK,EAAE,CAAA;YACd,YAAY,CAAC,KAAK,EAAE,CAAA;YACpB,MAAM,CAAC,KAAK,EAAE,CAAA;QAChB,CAAC;KACF,CAAA;AACH,CAAC,CAAA;AAED,SAAS,aAAa,CAAC,QAAgB,EAAE,IAAY;IACnD,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAA;IACxC,OAAO,GAAG,IAAI,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,cAAc,kBAAkB,CAAC,IAAI,CAAC,GAAG,IAAI,EAAE,CAAA;AAChG,CAAC;AAED,SAAS,SAAS,CAAC,KAAa;IAC9B,MAAM,EAAE,GAAG,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAA;IAC7B,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAA;AACxE,CAAC","sourcesContent":["/**\n * The local host — the session protocol and the data protocol, in process,\n * for development.\n *\n * NOT A PRODUCTION SERVER. Records live in memory and vanish on restart; the\n * one development user signs in without a password; the issuer stand-in mints\n * unsigned ID tokens; there is no rate limit, no CORS, no TLS. It exists so an\n * app that declares data and sign-in runs on a laptop with no hosted service,\n * and so the runner's sign-in wall, account control, gate and data paths are\n * exercised against the same addresses and answers a session server gives.\n *\n * Everything is mounted under `prefix` (e.g. `/_host`); `<base>` below is\n * `<origin><prefix>`, which is also the app's own API base the runner derives\n * from `loginUrl` (session-protocol §2).\n *\n * App door (session-protocol §4, §8)\n * POST <base>/login, <base>/register any credentials → the development user\n * POST <base>/logout revokes the presented token\n * GET <base>/session the principal behind the token\n * GET <base>/_auth/start/<method> provider sign-in, through the same redirects\n * GET <base>/_auth/callback/<method> …ends here: HttpOnly cookie, back to returnTo\n * GET <base>/_auth/session the cookie's session (needs x-pwapp-request: 1)\n * POST <base>/_auth/logout deletes the cookie (needs x-pwapp-request: 1)\n * External issuer stand-in (session-protocol §3) — see ./oidc.ts\n * GET <base>/oidc/.well-known/openid-configuration, GET <base>/oidc/authorize,\n * POST <base>/oidc/token\n * Records (data-protocol §5) — see ./records.ts\n * GET|POST <base>/records/<T>, GET <base>/records/<T>/count, GET <base>/records/<T>/aggregate,\n * GET|PATCH|DELETE <base>/records/<T>/<id>\n * Pages\n * GET <base>/surfaces/<key>.receipt.json the receipt, entity sources rewritten to <base>,\n * refused without a session when sign-in is required\n *\n * Every credential is accepted on `x-app-session` or `Authorization: Bearer`.\n * Tokens are opaque and random, kept only as hashes, and never logged.\n */\n\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport {\n HostError,\n cookiesOf,\n credentialOf,\n readJsonObject,\n redirect,\n safeReturnTo,\n sendError,\n sendJson,\n} from './http.js'\nimport {\n readAuth,\n readEntities,\n readReceipt,\n surfaceKeys,\n type AuthDeclaration,\n type EntityDeclaration,\n} from './definitions.js'\nimport { RecordStore, type Target } from './records.js'\nimport { rewriteEntitySources } from './receipts.js'\nimport { DevIssuer, type Grant } from './oidc.js'\nimport { TokenStore, type Principal } from './tokens.js'\nimport type { CreateLocalHost, LocalHost, LocalHostOptions } from './types.js'\n\nexport const DEFAULT_DEV_USER = { id: 'dev-user', name: 'Developer', email: 'dev@localhost' } as const\n\n/** The cookie the provider round trip leaves on the app's origin. */\nexport const SESSION_COOKIE = 'pwf_dev_session'\n\nconst SESSION_TTL_MS = 8 * 3600_000\nconst TRANSACTION_TTL_MS = 5 * 60_000\n\n/** The provider buttons a session server can name (envelope `auth.json` `providers[].method`). */\nconst PROVIDER_METHODS = new Set(['host', 'google', 'github', 'microsoft'])\n\nfunction normalisePrefix(prefix: string): string {\n const trimmed = prefix.replace(/^\\/+|\\/+$/g, '')\n if (!trimmed) throw new Error('createLocalHost: prefix must name a path, e.g. \"/_host\"')\n return `/${trimmed}`\n}\n\nfunction providersOf(auth: AuthDeclaration): string[] {\n return auth.methods.filter((m) => PROVIDER_METHODS.has(m))\n}\n\n/**\n * The envelope `auth.json` for this declaration, pointed at `base` — the\n * same shape a publisher writes (session-protocol §2), or `undefined` when the\n * app has no way in.\n *\n * - `external`: `oauth2-pkce` against the local issuer stand-in, keeping the\n * declared client id, scopes (plus `offline_access`, which is what makes a\n * refresh token exist) and audience.\n * - `app`: the password door when `password` is declared; the provider\n * buttons and the start address for every declared provider method; the\n * gateway's session and logout addresses for either; `methods` as declared.\n */\nexport function authAddresses(auth: AuthDeclaration | undefined, base: string): Record<string, unknown> | undefined {\n if (!auth) return undefined\n if (auth.topology === 'external') {\n if (!auth.issuer) return undefined\n const scopes = auth.issuer.scopes.includes('offline_access')\n ? [...auth.issuer.scopes]\n : [...auth.issuer.scopes, 'offline_access']\n return {\n provider: 'oauth2-pkce',\n issuer: `${base}/oidc`,\n clientId: auth.issuer.clientId,\n scopes,\n ...(auth.issuer.audience ? { audience: auth.issuer.audience } : {}),\n }\n }\n const door: Record<string, unknown> = {}\n if (auth.methods.includes('password')) {\n door.provider = 'password'\n door.loginUrl = `${base}/login`\n door.registerUrl = `${base}/register`\n door.logoutUrl = `${base}/logout`\n door.sessionUrl = `${base}/session`\n }\n const providers = providersOf(auth)\n if (providers.length > 0) {\n door.provider = door.provider ?? 'platform'\n door.providers = providers.map((method) => ({ method }))\n door.startUrl = `${base}/_auth/start`\n door.gatewaySessionUrl = `${base}/_auth/session`\n door.gatewayLogoutUrl = `${base}/_auth/logout`\n }\n if (Object.keys(door).length === 0) return undefined\n // The runner asks the gateway on every app door, not only a provider one:\n // for a stored-nothing session on boot, and on every sign-out (it falls back\n // to `/_auth/session` and `/_auth/logout` at the page's origin, which on\n // `pwf dev` are not the host's). The host answers both under its base.\n door.gatewaySessionUrl ??= `${base}/_auth/session`\n door.gatewayLogoutUrl ??= `${base}/_auth/logout`\n door.methods = [...auth.methods]\n return door\n}\n\nfunction segments(rest: string): string[] {\n try {\n return rest.split('/').filter(Boolean).map((s) => decodeURIComponent(s))\n } catch {\n throw new HostError(400, 'INVALID_PATH', 'The path is not valid percent-encoding.')\n }\n}\n\nfunction methodNotAllowed(): never {\n throw new HostError(405, 'METHOD_NOT_ALLOWED', 'This route does not take that method.')\n}\n\nfunction notFound(): never {\n throw new HostError(404, 'NOT_FOUND', 'No such route on the local host.')\n}\n\nexport const createLocalHost: CreateLocalHost = (options: LocalHostOptions): LocalHost => {\n const root = options.root\n const prefix = normalisePrefix(options.prefix)\n const user: Principal = {\n id: options.user?.id ?? DEFAULT_DEV_USER.id,\n email: options.user?.email ?? DEFAULT_DEV_USER.email,\n displayName: options.user?.name ?? DEFAULT_DEV_USER.name,\n }\n\n const bearer = new TokenStore<Grant>()\n const transactions = new TokenStore<{ readonly returnTo: string; readonly method: string; readonly expiresAt: number }>()\n const records = new RecordStore(root, user)\n const issuer = new DevIssuer(bearer, user)\n\n const originOf = (req: IncomingMessage): string => `http://${req.headers.host ?? 'localhost'}`\n\n const principalOf = (req: IncomingMessage): Principal | undefined => bearer.get(credentialOf(req))?.principal\n\n function startSession(): { token: string; expiresAt: string; principal: Principal } {\n const expiresAt = Date.now() + SESSION_TTL_MS\n const token = bearer.issue({ principal: user, kind: 'session', expiresAt })\n return { token, expiresAt: new Date(expiresAt).toISOString(), principal: user }\n }\n\n const sessionCookie = (token: string, maxAgeS: number): string =>\n `${SESSION_COOKIE}=${encodeURIComponent(token)}; Path=${prefix}/_auth; HttpOnly; SameSite=Lax; Max-Age=${maxAgeS}`\n\n function requireRunnerRequest(req: IncomingMessage): void {\n if (req.headers['x-pwapp-request'] !== '1') {\n throw new HostError(403, 'RUNNER_REQUEST_REQUIRED', 'This address answers only the runner (x-pwapp-request: 1).')\n }\n }\n\n // ---------------------------------------------------------------- app door\n\n async function door(req: IncomingMessage, res: ServerResponse, action: string): Promise<void> {\n const auth = readAuth(root)\n if (action === 'session') {\n if (req.method !== 'GET') methodNotAllowed()\n const presented = credentialOf(req)\n const grant = bearer.get(presented)\n if (grant) {\n sendJson(res, 200, { data: { principal: grant.principal } })\n return\n }\n if (presented !== undefined || auth?.required) {\n throw new HostError(401, 'SIGN_IN_REQUIRED', 'No live session.')\n }\n sendJson(res, 200, { data: { principal: null } })\n return\n }\n if (req.method !== 'POST') methodNotAllowed()\n if (action === 'logout') {\n bearer.revoke(credentialOf(req))\n sendJson(res, 200, { data: { signedOut: true } })\n return\n }\n // login / register: the credentials are read (and must be JSON) but not\n // checked — the development user has no password.\n await readJsonObject(req)\n if (!auth || auth.topology !== 'app' || !auth.methods.includes('password')) {\n throw new HostError(404, 'NO_PASSWORD_DOOR', 'This app declares no password sign-in.')\n }\n sendJson(res, action === 'register' ? 201 : 200, { data: startSession() })\n }\n\n function gateway(req: IncomingMessage, res: ServerResponse, url: URL, parts: string[]): void {\n const [action, method] = parts\n if (action === 'start' || action === 'callback') {\n if (req.method !== 'GET') methodNotAllowed()\n if (parts.length !== 2 || !method) notFound()\n if (action === 'start') {\n const returnTo = safeReturnTo(url.searchParams.get('returnTo'))\n const auth = readAuth(root)\n if (!auth || auth.topology !== 'app' || !providersOf(auth).includes(method)) {\n redirect(res, withAuthError(returnTo, 'provider_unavailable'))\n return\n }\n // The provider's own leg is played by the callback below: the browser\n // still leaves the app, comes back to the callback, and lands on returnTo.\n const tx = transactions.issue({ returnTo, method, expiresAt: Date.now() + TRANSACTION_TTL_MS })\n redirect(res, `${prefix}/_auth/callback/${encodeURIComponent(method)}?tx=${encodeURIComponent(tx)}`)\n return\n }\n const tx = transactions.take(url.searchParams.get('tx') ?? undefined)\n if (!tx || tx.method !== method) {\n redirect(res, withAuthError('/', 'invalid_transaction'))\n return\n }\n const session = startSession()\n redirect(res, tx.returnTo, [sessionCookie(session.token, SESSION_TTL_MS / 1000)])\n return\n }\n if (parts.length !== 1) notFound()\n if (action === 'session') {\n if (req.method !== 'GET') methodNotAllowed()\n requireRunnerRequest(req)\n const token = cookiesOf(req)[SESSION_COOKIE]\n const grant = bearer.get(token)\n if (!token || !grant || grant.kind !== 'session') {\n throw new HostError(401, 'SIGN_IN_REQUIRED', 'No session cookie.')\n }\n sendJson(res, 200, {\n data: { token, expiresAt: new Date(grant.expiresAt).toISOString(), principal: grant.principal },\n })\n return\n }\n if (action === 'logout') {\n if (req.method !== 'POST') methodNotAllowed()\n requireRunnerRequest(req)\n bearer.revoke(cookiesOf(req)[SESSION_COOKIE])\n sendJson(res, 200, { data: { signedOut: true } }, { 'set-cookie': sessionCookie('', 0) })\n return\n }\n notFound()\n }\n\n // ------------------------------------------------------------------ issuer\n\n async function oidc(req: IncomingMessage, res: ServerResponse, url: URL, parts: string[]): Promise<void> {\n const auth = readAuth(root)\n if (!auth || auth.topology !== 'external' || !auth.issuer) {\n throw new HostError(404, 'NO_ISSUER', 'This app declares no external issuer.')\n }\n const iss = DevIssuer.issuerUrl(originOf(req), prefix)\n const route = parts.join('/')\n if (route === '.well-known/openid-configuration') {\n if (req.method !== 'GET') methodNotAllowed()\n issuer.discovery(res, iss)\n return\n }\n if (route === 'authorize') {\n if (req.method !== 'GET') methodNotAllowed()\n issuer.authorize(req, res, url, auth)\n return\n }\n if (route === 'token') {\n if (req.method !== 'POST') methodNotAllowed()\n await issuer.token(req, res, iss, auth)\n return\n }\n notFound()\n }\n\n // ----------------------------------------------------------------- records\n\n function entityOf(typeId: string): EntityDeclaration {\n const entity = readEntities(root).find((e) => e.typeId === typeId)\n if (!entity) throw new HostError(404, 'UNKNOWN_ENTITY_TYPE', `The app declares no entity type \"${typeId}\".`)\n return entity\n }\n\n async function data(req: IncomingMessage, res: ServerResponse, url: URL, parts: string[]): Promise<void> {\n const [typeId, second] = parts\n if (!typeId || parts.length > 2) notFound()\n const target: Target = { entity: entityOf(typeId), auth: readAuth(root), caller: { principal: principalOf(req) } }\n const params = url.searchParams\n if (second === undefined) {\n if (req.method === 'GET') {\n sendJson(res, 200, records.list(target, params))\n return\n }\n if (req.method === 'POST') {\n const record = records.create(target, await readJsonObject(req))\n sendJson(res, 201, { id: record.id, data: record })\n return\n }\n methodNotAllowed()\n }\n if (second === 'count' || second === 'aggregate') {\n if (req.method !== 'GET') methodNotAllowed()\n sendJson(res, 200, records.aggregate(target, params, second === 'count'))\n return\n }\n if (req.method === 'GET') {\n const record = records.read(target, second)\n sendJson(res, 200, { id: record.id, data: record })\n return\n }\n if (req.method === 'PATCH') {\n const record = records.update(target, second, await readJsonObject(req))\n sendJson(res, 200, { id: record.id, data: record })\n return\n }\n if (req.method === 'DELETE') {\n records.remove(target, second)\n sendJson(res, 200, { data: { id: second, deleted: true } })\n return\n }\n methodNotAllowed()\n }\n\n // ------------------------------------------------------------------- pages\n\n function receiptFor(key: string, base: string): Record<string, unknown> | undefined {\n const receipt = readReceipt(root, key)\n if (!receipt) return undefined\n return rewriteEntitySources(receipt, base, new Set(readEntities(root).map((e) => e.typeId)))\n }\n\n function surface(req: IncomingMessage, res: ServerResponse, parts: string[]): void {\n if (req.method !== 'GET') methodNotAllowed()\n const file = parts.length === 1 ? parts[0] : undefined\n if (!file || !file.endsWith('.receipt.json')) notFound()\n if (readAuth(root)?.required && !principalOf(req)) {\n throw new HostError(401, 'SIGN_IN_REQUIRED', 'Sign in to open this page.')\n }\n const receipt = receiptFor(file.slice(0, -'.receipt.json'.length), originOf(req) + prefix)\n if (!receipt) notFound()\n sendJson(res, 200, receipt)\n }\n\n // ------------------------------------------------------------------ router\n\n async function route(req: IncomingMessage, res: ServerResponse, url: URL, rest: string): Promise<void> {\n const [head, ...tail] = segments(rest)\n switch (head) {\n case 'login':\n case 'register':\n case 'logout':\n case 'session':\n if (tail.length > 0) notFound()\n return door(req, res, head)\n case '_auth':\n return gateway(req, res, url, tail)\n case 'oidc':\n return oidc(req, res, url, tail)\n case 'records':\n return data(req, res, url, tail)\n case 'surfaces':\n return surface(req, res, tail)\n default:\n notFound()\n }\n }\n\n return {\n envelopeEntries(origin: string): Readonly<Record<string, unknown>> {\n const base = origin.replace(/\\/+$/, '') + prefix\n const out: Record<string, unknown> = {}\n const auth = authAddresses(readAuth(root), base)\n if (auth) out['auth.json'] = auth\n for (const key of surfaceKeys(root)) {\n const receipt = receiptFor(key, base)\n if (receipt) out[`surfaces/${key}.receipt.json`] = receipt\n }\n return out\n },\n\n async handle(req: IncomingMessage, res: ServerResponse): Promise<boolean> {\n let url: URL\n try {\n url = new URL(req.url ?? '/', 'http://localhost')\n } catch {\n return false\n }\n const path = url.pathname\n if (path !== prefix && !path.startsWith(`${prefix}/`)) return false\n try {\n await route(req, res, url, path.slice(prefix.length))\n } catch (err) {\n if (res.headersSent) {\n res.end()\n } else if (err instanceof HostError) {\n sendError(res, err)\n } else {\n // A broken definition file is the developer's to fix; say which.\n sendError(res, new HostError(500, 'HOST_ERROR', err instanceof Error ? err.message : String(err)))\n }\n }\n return true\n },\n\n reset(): void {\n records.reset()\n bearer.clear()\n transactions.clear()\n issuer.reset()\n },\n }\n}\n\nfunction withAuthError(returnTo: string, code: string): string {\n const [path, hash] = splitHash(returnTo)\n return `${path}${path.includes('?') ? '&' : '?'}auth_error=${encodeURIComponent(code)}${hash}`\n}\n\nfunction splitHash(value: string): [string, string] {\n const at = value.indexOf('#')\n return at === -1 ? [value, ''] : [value.slice(0, at), value.slice(at)]\n}\n"]}
|
|
1
|
+
{"version":3,"file":"local-host.js","sourceRoot":"","sources":["../../src/host/local-host.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAGH,OAAO,EACL,SAAS,EACT,SAAS,EACT,YAAY,EACZ,cAAc,EACd,QAAQ,EACR,YAAY,EACZ,SAAS,EACT,QAAQ,GACT,MAAM,WAAW,CAAA;AAClB,OAAO,EACL,QAAQ,EACR,YAAY,EACZ,WAAW,EACX,WAAW,GAGZ,MAAM,kBAAkB,CAAA;AACzB,OAAO,EAAE,WAAW,EAAe,MAAM,c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AAA;YACpB,MAAM,CAAC,KAAK,EAAE,CAAA;QAChB,CAAC;KACF,CAAA;AACH,CAAC,CAAA;AAED,SAAS,aAAa,CAAC,QAAgB,EAAE,IAAY;IACnD,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAA;IACxC,OAAO,GAAG,IAAI,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,cAAc,kBAAkB,CAAC,IAAI,CAAC,GAAG,IAAI,EAAE,CAAA;AAChG,CAAC;AAED,SAAS,SAAS,CAAC,KAAa;IAC9B,MAAM,EAAE,GAAG,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAA;IAC7B,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAA;AACxE,CAAC","sourcesContent":["/**\n * The local host — the session protocol and the data protocol, in process,\n * for development.\n *\n * NOT A PRODUCTION SERVER. Records live in memory and vanish on restart; the\n * one development user signs in without a password; the issuer stand-in mints\n * unsigned ID tokens; there is no rate limit, no CORS, no TLS. It exists so an\n * app that declares data and sign-in runs on a laptop with no hosted service,\n * and so the runner's sign-in wall, account control, gate and data paths are\n * exercised against the same addresses and answers a session server gives.\n *\n * Everything is mounted under `prefix` (e.g. `/_host`); `<base>` below is\n * `<origin><prefix>`, which is also the app's own API base the runner derives\n * from `loginUrl` (session-protocol §2).\n *\n * App door (session-protocol §4, §8)\n * POST <base>/login, <base>/register any credentials → the development user\n * POST <base>/logout revokes the presented token\n * GET <base>/session the principal behind the token\n * GET <base>/_auth/start/<method> provider sign-in, through the same redirects\n * GET <base>/_auth/callback/<method> …ends here: HttpOnly cookie, back to returnTo\n * GET <base>/_auth/session the cookie's session (needs x-pwapp-request: 1)\n * POST <base>/_auth/logout deletes the cookie (needs x-pwapp-request: 1)\n * External issuer stand-in (session-protocol §3) — see ./oidc.ts\n * GET <base>/oidc/.well-known/openid-configuration, GET <base>/oidc/authorize,\n * POST <base>/oidc/token\n * Records (data-protocol §5) — see ./records.ts\n * GET|POST <base>/records/<T>, GET <base>/records/<T>/count, GET <base>/records/<T>/aggregate,\n * GET|PATCH|DELETE <base>/records/<T>/<id>\n * Pages\n * GET <base>/surfaces/<key>.receipt.json the receipt, entity sources rewritten to <base>,\n * refused without a session when sign-in is required\n *\n * Every credential is accepted on `x-app-session` or `Authorization: Bearer`.\n * Tokens are opaque and random, kept only as hashes, and never logged.\n */\n\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport {\n HostError,\n cookiesOf,\n credentialOf,\n readJsonObject,\n redirect,\n safeReturnTo,\n sendError,\n sendJson,\n} from './http.js'\nimport {\n readAuth,\n readEntities,\n readReceipt,\n surfaceKeys,\n type AuthDeclaration,\n type EntityDeclaration,\n} from './definitions.js'\nimport { RecordStore, type Target } from './records.js'\nimport { rewriteEntitySources } from './receipts.js'\nimport { DevIssuer, type Grant } from './oidc.js'\nimport { TokenStore, type Principal } from './tokens.js'\nimport type { CreateLocalHost, LocalHost, LocalHostOptions } from './types.js'\n\nexport const DEFAULT_DEV_USER = { id: 'dev-user', name: 'Developer', email: 'dev@localhost' } as const\n\n/** The cookie the provider round trip leaves on the app's origin. */\nexport const SESSION_COOKIE = 'pwf_dev_session'\n\nconst SESSION_TTL_MS = 8 * 3600_000\nconst TRANSACTION_TTL_MS = 5 * 60_000\n\n/** The provider buttons a session server can name (envelope `auth.json` `providers[].method`). */\nconst PROVIDER_METHODS = new Set(['phiwebs', 'google', 'github', 'microsoft'])\n\nfunction normalisePrefix(prefix: string): string {\n const trimmed = prefix.replace(/^\\/+|\\/+$/g, '')\n if (!trimmed) throw new Error('createLocalHost: prefix must name a path, e.g. \"/_host\"')\n return `/${trimmed}`\n}\n\nfunction providersOf(auth: AuthDeclaration): string[] {\n return auth.methods.filter((m) => PROVIDER_METHODS.has(m))\n}\n\n/**\n * The envelope `auth.json` for this declaration, pointed at `base` — the\n * same shape a publisher writes (session-protocol §2), or `undefined` when the\n * app has no way in.\n *\n * - `external`: `oauth2-pkce` against the local issuer stand-in, keeping the\n * declared client id, scopes (plus `offline_access`, which is what makes a\n * refresh token exist) and audience.\n * - `app`: the password door when `password` is declared; the provider\n * buttons and the start address for every declared provider method; the\n * gateway's session and logout addresses for either; `methods` as declared.\n */\nexport function authAddresses(auth: AuthDeclaration | undefined, base: string): Record<string, unknown> | undefined {\n if (!auth) return undefined\n if (auth.topology === 'external') {\n if (!auth.issuer) return undefined\n const scopes = auth.issuer.scopes.includes('offline_access')\n ? [...auth.issuer.scopes]\n : [...auth.issuer.scopes, 'offline_access']\n return {\n provider: 'oauth2-pkce',\n issuer: `${base}/oidc`,\n clientId: auth.issuer.clientId,\n scopes,\n ...(auth.issuer.audience ? { audience: auth.issuer.audience } : {}),\n }\n }\n const door: Record<string, unknown> = {}\n if (auth.methods.includes('password')) {\n door.provider = 'password'\n door.loginUrl = `${base}/login`\n door.registerUrl = `${base}/register`\n door.logoutUrl = `${base}/logout`\n door.sessionUrl = `${base}/session`\n }\n const providers = providersOf(auth)\n if (providers.length > 0) {\n door.provider = door.provider ?? 'platform'\n door.providers = providers.map((method) => ({ method }))\n door.startUrl = `${base}/_auth/start`\n door.gatewaySessionUrl = `${base}/_auth/session`\n door.gatewayLogoutUrl = `${base}/_auth/logout`\n }\n if (Object.keys(door).length === 0) return undefined\n // The runner asks the gateway on every app door, not only a provider one:\n // for a stored-nothing session on boot, and on every sign-out (it falls back\n // to `/_auth/session` and `/_auth/logout` at the page's origin, which on\n // `pwf dev` are not the host's). The host answers both under its base.\n door.gatewaySessionUrl ??= `${base}/_auth/session`\n door.gatewayLogoutUrl ??= `${base}/_auth/logout`\n door.methods = [...auth.methods]\n return door\n}\n\nfunction segments(rest: string): string[] {\n try {\n return rest.split('/').filter(Boolean).map((s) => decodeURIComponent(s))\n } catch {\n throw new HostError(400, 'INVALID_PATH', 'The path is not valid percent-encoding.')\n }\n}\n\nfunction methodNotAllowed(): never {\n throw new HostError(405, 'METHOD_NOT_ALLOWED', 'This route does not take that method.')\n}\n\nfunction notFound(): never {\n throw new HostError(404, 'NOT_FOUND', 'No such route on the local host.')\n}\n\nexport const createLocalHost: CreateLocalHost = (options: LocalHostOptions): LocalHost => {\n const root = options.root\n const prefix = normalisePrefix(options.prefix)\n const user: Principal = {\n id: options.user?.id ?? DEFAULT_DEV_USER.id,\n email: options.user?.email ?? DEFAULT_DEV_USER.email,\n displayName: options.user?.name ?? DEFAULT_DEV_USER.name,\n }\n\n const bearer = new TokenStore<Grant>()\n const transactions = new TokenStore<{ readonly returnTo: string; readonly method: string; readonly expiresAt: number }>()\n const records = new RecordStore(root, user)\n const issuer = new DevIssuer(bearer, user)\n\n const originOf = (req: IncomingMessage): string => `http://${req.headers.host ?? 'localhost'}`\n\n const principalOf = (req: IncomingMessage): Principal | undefined => bearer.get(credentialOf(req))?.principal\n\n function startSession(): { token: string; expiresAt: string; principal: Principal } {\n const expiresAt = Date.now() + SESSION_TTL_MS\n const token = bearer.issue({ principal: user, kind: 'session', expiresAt })\n return { token, expiresAt: new Date(expiresAt).toISOString(), principal: user }\n }\n\n const sessionCookie = (token: string, maxAgeS: number): string =>\n `${SESSION_COOKIE}=${encodeURIComponent(token)}; Path=${prefix}/_auth; HttpOnly; SameSite=Lax; Max-Age=${maxAgeS}`\n\n function requireRunnerRequest(req: IncomingMessage): void {\n if (req.headers['x-pwapp-request'] !== '1') {\n throw new HostError(403, 'RUNNER_REQUEST_REQUIRED', 'This address answers only the runner (x-pwapp-request: 1).')\n }\n }\n\n // ---------------------------------------------------------------- app door\n\n async function door(req: IncomingMessage, res: ServerResponse, action: string): Promise<void> {\n const auth = readAuth(root)\n if (action === 'session') {\n if (req.method !== 'GET') methodNotAllowed()\n const presented = credentialOf(req)\n const grant = bearer.get(presented)\n if (grant) {\n sendJson(res, 200, { data: { principal: grant.principal } })\n return\n }\n if (presented !== undefined || auth?.required) {\n throw new HostError(401, 'SIGN_IN_REQUIRED', 'No live session.')\n }\n sendJson(res, 200, { data: { principal: null } })\n return\n }\n if (req.method !== 'POST') methodNotAllowed()\n if (action === 'logout') {\n bearer.revoke(credentialOf(req))\n sendJson(res, 200, { data: { signedOut: true } })\n return\n }\n // login / register: the credentials are read (and must be JSON) but not\n // checked — the development user has no password.\n await readJsonObject(req)\n if (!auth || auth.topology !== 'app' || !auth.methods.includes('password')) {\n throw new HostError(404, 'NO_PASSWORD_DOOR', 'This app declares no password sign-in.')\n }\n sendJson(res, action === 'register' ? 201 : 200, { data: startSession() })\n }\n\n function gateway(req: IncomingMessage, res: ServerResponse, url: URL, parts: string[]): void {\n const [action, method] = parts\n if (action === 'start' || action === 'callback') {\n if (req.method !== 'GET') methodNotAllowed()\n if (parts.length !== 2 || !method) notFound()\n if (action === 'start') {\n const returnTo = safeReturnTo(url.searchParams.get('returnTo'))\n const auth = readAuth(root)\n if (!auth || auth.topology !== 'app' || !providersOf(auth).includes(method)) {\n redirect(res, withAuthError(returnTo, 'provider_unavailable'))\n return\n }\n // The provider's own leg is played by the callback below: the browser\n // still leaves the app, comes back to the callback, and lands on returnTo.\n const tx = transactions.issue({ returnTo, method, expiresAt: Date.now() + TRANSACTION_TTL_MS })\n redirect(res, `${prefix}/_auth/callback/${encodeURIComponent(method)}?tx=${encodeURIComponent(tx)}`)\n return\n }\n const tx = transactions.take(url.searchParams.get('tx') ?? undefined)\n if (!tx || tx.method !== method) {\n redirect(res, withAuthError('/', 'invalid_transaction'))\n return\n }\n const session = startSession()\n redirect(res, tx.returnTo, [sessionCookie(session.token, SESSION_TTL_MS / 1000)])\n return\n }\n if (parts.length !== 1) notFound()\n if (action === 'session') {\n if (req.method !== 'GET') methodNotAllowed()\n requireRunnerRequest(req)\n const token = cookiesOf(req)[SESSION_COOKIE]\n const grant = bearer.get(token)\n if (!token || !grant || grant.kind !== 'session') {\n throw new HostError(401, 'SIGN_IN_REQUIRED', 'No session cookie.')\n }\n sendJson(res, 200, {\n data: { token, expiresAt: new Date(grant.expiresAt).toISOString(), principal: grant.principal },\n })\n return\n }\n if (action === 'logout') {\n if (req.method !== 'POST') methodNotAllowed()\n requireRunnerRequest(req)\n bearer.revoke(cookiesOf(req)[SESSION_COOKIE])\n sendJson(res, 200, { data: { signedOut: true } }, { 'set-cookie': sessionCookie('', 0) })\n return\n }\n notFound()\n }\n\n // ------------------------------------------------------------------ issuer\n\n async function oidc(req: IncomingMessage, res: ServerResponse, url: URL, parts: string[]): Promise<void> {\n const auth = readAuth(root)\n if (!auth || auth.topology !== 'external' || !auth.issuer) {\n throw new HostError(404, 'NO_ISSUER', 'This app declares no external issuer.')\n }\n const iss = DevIssuer.issuerUrl(originOf(req), prefix)\n const route = parts.join('/')\n if (route === '.well-known/openid-configuration') {\n if (req.method !== 'GET') methodNotAllowed()\n issuer.discovery(res, iss)\n return\n }\n if (route === 'authorize') {\n if (req.method !== 'GET') methodNotAllowed()\n issuer.authorize(req, res, url, auth)\n return\n }\n if (route === 'token') {\n if (req.method !== 'POST') methodNotAllowed()\n await issuer.token(req, res, iss, auth)\n return\n }\n notFound()\n }\n\n // ----------------------------------------------------------------- records\n\n function entityOf(typeId: string): EntityDeclaration {\n const entity = readEntities(root).find((e) => e.typeId === typeId)\n if (!entity) throw new HostError(404, 'UNKNOWN_ENTITY_TYPE', `The app declares no entity type \"${typeId}\".`)\n return entity\n }\n\n async function data(req: IncomingMessage, res: ServerResponse, url: URL, parts: string[]): Promise<void> {\n const [typeId, second] = parts\n if (!typeId || parts.length > 2) notFound()\n const target: Target = { entity: entityOf(typeId), auth: readAuth(root), caller: { principal: principalOf(req) } }\n const params = url.searchParams\n if (second === undefined) {\n if (req.method === 'GET') {\n sendJson(res, 200, records.list(target, params))\n return\n }\n if (req.method === 'POST') {\n const record = records.create(target, await readJsonObject(req))\n sendJson(res, 201, { id: record.id, data: record })\n return\n }\n methodNotAllowed()\n }\n if (second === 'count' || second === 'aggregate') {\n if (req.method !== 'GET') methodNotAllowed()\n sendJson(res, 200, records.aggregate(target, params, second === 'count'))\n return\n }\n if (req.method === 'GET') {\n const record = records.read(target, second)\n sendJson(res, 200, { id: record.id, data: record })\n return\n }\n if (req.method === 'PATCH') {\n const record = records.update(target, second, await readJsonObject(req))\n sendJson(res, 200, { id: record.id, data: record })\n return\n }\n if (req.method === 'DELETE') {\n records.remove(target, second)\n sendJson(res, 200, { data: { id: second, deleted: true } })\n return\n }\n methodNotAllowed()\n }\n\n // ------------------------------------------------------------------- pages\n\n function receiptFor(key: string, base: string): Record<string, unknown> | undefined {\n const receipt = readReceipt(root, key)\n if (!receipt) return undefined\n return rewriteEntitySources(receipt, base, new Set(readEntities(root).map((e) => e.typeId)))\n }\n\n function surface(req: IncomingMessage, res: ServerResponse, parts: string[]): void {\n if (req.method !== 'GET') methodNotAllowed()\n const file = parts.length === 1 ? parts[0] : undefined\n if (!file || !file.endsWith('.receipt.json')) notFound()\n if (readAuth(root)?.required && !principalOf(req)) {\n throw new HostError(401, 'SIGN_IN_REQUIRED', 'Sign in to open this page.')\n }\n const receipt = receiptFor(file.slice(0, -'.receipt.json'.length), originOf(req) + prefix)\n if (!receipt) notFound()\n sendJson(res, 200, receipt)\n }\n\n // ------------------------------------------------------------------ router\n\n async function route(req: IncomingMessage, res: ServerResponse, url: URL, rest: string): Promise<void> {\n const [head, ...tail] = segments(rest)\n switch (head) {\n case 'login':\n case 'register':\n case 'logout':\n case 'session':\n if (tail.length > 0) notFound()\n return door(req, res, head)\n case '_auth':\n return gateway(req, res, url, tail)\n case 'oidc':\n return oidc(req, res, url, tail)\n case 'records':\n return data(req, res, url, tail)\n case 'surfaces':\n return surface(req, res, tail)\n default:\n notFound()\n }\n }\n\n return {\n envelopeEntries(origin: string): Readonly<Record<string, unknown>> {\n const base = origin.replace(/\\/+$/, '') + prefix\n const out: Record<string, unknown> = {}\n const auth = authAddresses(readAuth(root), base)\n if (auth) out['auth.json'] = auth\n for (const key of surfaceKeys(root)) {\n const receipt = receiptFor(key, base)\n if (receipt) out[`surfaces/${key}.receipt.json`] = receipt\n }\n return out\n },\n\n async handle(req: IncomingMessage, res: ServerResponse): Promise<boolean> {\n let url: URL\n try {\n url = new URL(req.url ?? '/', 'http://localhost')\n } catch {\n return false\n }\n const path = url.pathname\n if (path !== prefix && !path.startsWith(`${prefix}/`)) return false\n try {\n await route(req, res, url, path.slice(prefix.length))\n } catch (err) {\n if (res.headersSent) {\n res.end()\n } else if (err instanceof HostError) {\n sendError(res, err)\n } else {\n // A broken definition file is the developer's to fix; say which.\n sendError(res, new HostError(500, 'HOST_ERROR', err instanceof Error ? err.message : String(err)))\n }\n }\n return true\n },\n\n reset(): void {\n records.reset()\n bearer.clear()\n transactions.clear()\n issuer.reset()\n },\n }\n}\n\nfunction withAuthError(returnTo: string, code: string): string {\n const [path, hash] = splitHash(returnTo)\n return `${path}${path.includes('?') ? '&' : '?'}auth_error=${encodeURIComponent(code)}${hash}`\n}\n\nfunction splitHash(value: string): [string, string] {\n const at = value.indexOf('#')\n return at === -1 ? [value, ''] : [value.slice(0, at), value.slice(at)]\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pwfabric/cli",
|
|
3
|
-
"version": "1.0.0
|
|
3
|
+
"version": "1.0.0",
|
|
4
4
|
"description": "The PWFabric command line: create, develop, validate, pack and run PWFabric applications without any hosted service",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -35,13 +35,13 @@
|
|
|
35
35
|
"node": ">=22"
|
|
36
36
|
},
|
|
37
37
|
"dependencies": {
|
|
38
|
-
"@pwfabric/
|
|
39
|
-
"@pwfabric/
|
|
40
|
-
"@pwfabric/
|
|
41
|
-
"@pwfabric/
|
|
42
|
-
"@pwfabric/embed": "1.0.0
|
|
43
|
-
"@pwfabric/
|
|
44
|
-
"@pwfabric/runner": "1.0.0
|
|
38
|
+
"@pwfabric/contracts": "1.0.0",
|
|
39
|
+
"@pwfabric/core": "1.0.0",
|
|
40
|
+
"@pwfabric/compiler": "1.0.0",
|
|
41
|
+
"@pwfabric/pack": "1.0.0",
|
|
42
|
+
"@pwfabric/embed": "1.0.0",
|
|
43
|
+
"@pwfabric/authoring": "1.0.0",
|
|
44
|
+
"@pwfabric/runner": "1.0.0"
|
|
45
45
|
},
|
|
46
46
|
"devDependencies": {
|
|
47
47
|
"@types/node": "^22.0.0",
|