@foliwake/server 0.8.0 → 0.10.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.
@@ -0,0 +1,47 @@
1
+ import { ENTRY_SEGMENT, ENTRY_ROOTS, EVENT_PREFIX } from './config-parts.js';
2
+ import { FoliwakePageError } from './errors.js';
3
+ /** The response header that names the blocks module of a page's code release. */
4
+ export const BLOCKS_HEADER = 'x-foliwake-blocks';
5
+ const MEMBER = /^\s*([a-z*][a-z0-9_.*-]*)=("(?:[^"\\]|\\.)*"|-?\d{1,15})\s*$/;
6
+ const MAX_LENGTH = 512;
7
+ function invalid() {
8
+ return new FoliwakePageError('invalid', 'The origin answered an invalid X-Foliwake-Blocks.');
9
+ }
10
+ function membersOf(value) {
11
+ const members = new Map();
12
+ for (const part of value.split(',')) {
13
+ const match = MEMBER.exec(part);
14
+ if (!match)
15
+ throw invalid();
16
+ const raw = match[2];
17
+ members.set(match[1], raw.startsWith('"') ? raw.slice(1, -1).replace(/\\(.)/g, '$1') : Number(raw));
18
+ }
19
+ return members;
20
+ }
21
+ function isEntry(value) {
22
+ if (typeof value !== 'string' || !value.endsWith('.js'))
23
+ return false;
24
+ const segments = value.split('/');
25
+ if (segments.length < 2 || segments.length > 8 || !ENTRY_ROOTS.includes(segments[0]))
26
+ return false;
27
+ return segments.every((s) => ENTRY_SEGMENT.test(s) && !s.includes('..'));
28
+ }
29
+ function isContract(value) {
30
+ return typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= 999;
31
+ }
32
+ /** The parsed header; null when the answer has none (the release names no blocks module). */
33
+ export function parseBlocksHeader(value) {
34
+ if (value === null)
35
+ return null;
36
+ if (value.length > MAX_LENGTH)
37
+ throw invalid();
38
+ const members = membersOf(value);
39
+ const entry = members.get('entry');
40
+ const contract = members.get('contract');
41
+ const eventPrefix = members.get('prefix');
42
+ if (!isEntry(entry) || !isContract(contract))
43
+ throw invalid();
44
+ if (typeof eventPrefix !== 'string' || !EVENT_PREFIX.test(eventPrefix))
45
+ throw invalid();
46
+ return { entry, contract, eventPrefix };
47
+ }
@@ -0,0 +1,9 @@
1
+ import type { ParseOptions } from './config.js';
2
+ /** True for 127.x, localhost, *.localhost and ::1. */
3
+ export declare function isLoopbackName(hostname: string): boolean;
4
+ /** A site origin: https (http only for loopback), no credentials, path, query or fragment. */
5
+ export declare function parseRemoteUrl(value: unknown, where: string): string;
6
+ /** Validates an environment variable NAME (never a value). */
7
+ export declare function checkEnvName(value: unknown, where: string, extra?: ParseOptions['envNameProblem']): string;
8
+ /** Validates a Basic user name (no `:` or control characters, at most 128 characters). */
9
+ export declare function checkUsername(value: unknown, where: string): string;
@@ -0,0 +1,53 @@
1
+ // Checks of single config values shared by the v2 and v3 parsers and the discovery reader: origins and variable
2
+ // names. Re-exported by ./config (the public module).
3
+ import { FoliwakeConfigError } from './errors.js';
4
+ import { basicEnvNameProblem } from './env-names.js';
5
+ /** True for 127.x, localhost, *.localhost and ::1. */
6
+ export function isLoopbackName(hostname) {
7
+ const name = hostname.toLowerCase().replace(/\.$/, '');
8
+ if (name === 'localhost' || name.endsWith('.localhost'))
9
+ return true;
10
+ if (name === '[::1]' || name === '::1')
11
+ return true;
12
+ return /^127(?:\.\d{1,3}){3}$/.test(name);
13
+ }
14
+ function safeUrlText(value) {
15
+ return value.replace(/\/\/[^/@]*@/, '//…@').slice(0, 200);
16
+ }
17
+ /** A site origin: https (http only for loopback), no credentials, path, query or fragment. */
18
+ export function parseRemoteUrl(value, where) {
19
+ if (typeof value !== 'string' || value.trim() === '')
20
+ throw new FoliwakeConfigError(`${where}: give the URL of the deployed site, e.g. "https://preview.example.org".`);
21
+ let url;
22
+ try {
23
+ url = new URL(value);
24
+ }
25
+ catch {
26
+ throw new FoliwakeConfigError(`${where}: "${safeUrlText(value)}" is not a valid URL.`);
27
+ }
28
+ if (url.username || url.password)
29
+ throw new FoliwakeConfigError(`${where}: the URL must not contain a user name or password; name the password's environment variable in "auth" instead.`);
30
+ if (url.protocol !== 'https:' && url.protocol !== 'http:')
31
+ throw new FoliwakeConfigError(`${where}: only https URLs are supported.`);
32
+ if (url.protocol === 'http:' && !isLoopbackName(url.hostname)) {
33
+ throw new FoliwakeConfigError(`${where}: ${url.origin} uses plain http; use https (http is accepted only for loopback hosts such as 127.0.0.1).`);
34
+ }
35
+ if (url.search || url.hash || (url.pathname !== '/' && url.pathname !== '')) {
36
+ throw new FoliwakeConfigError(`${where}: give the site origin only (scheme, host and port), without a path, query or fragment: ${url.origin}`);
37
+ }
38
+ return url.origin;
39
+ }
40
+ /** Validates an environment variable NAME (never a value). */
41
+ export function checkEnvName(value, where, extra) {
42
+ const problem = basicEnvNameProblem(value, where) ?? (extra ? extra(value, where) : null);
43
+ if (problem)
44
+ throw new FoliwakeConfigError(problem);
45
+ return value;
46
+ }
47
+ /** Validates a Basic user name (no `:` or control characters, at most 128 characters). */
48
+ export function checkUsername(value, where) {
49
+ if (typeof value !== 'string' || value === '' || value.length > 128 || /[:\u0000-\u001f\u007f]/.test(value)) {
50
+ throw new FoliwakeConfigError(`${where}: give a user name without ":" or control characters.`);
51
+ }
52
+ return value;
53
+ }
@@ -0,0 +1,50 @@
1
+ import type { BasicAuth, FoliwakeAppSettings, FoliwakeEndpoint, ParseOptions, RemoteAuth, ServiceTokenAuth } from './config.js';
2
+ export declare const SECRET_KEYS: RegExp;
3
+ export declare const ISSUER: RegExp;
4
+ export declare const KID: RegExp;
5
+ export declare const SITE: RegExp;
6
+ export declare const PREFIX: RegExp;
7
+ export declare const RESERVED_PREFIXES: string[];
8
+ export declare const ENTRY_SEGMENT: RegExp;
9
+ export declare const ENTRY_ROOTS: string[];
10
+ export declare const CONTRACT: RegExp;
11
+ export declare const EVENT_PREFIX: RegExp;
12
+ export declare const DEFAULTS: {
13
+ code: string;
14
+ media: string;
15
+ contract: string;
16
+ eventPrefix: string;
17
+ revalidate: number;
18
+ };
19
+ export type Obj = Record<string, unknown>;
20
+ export declare const isObject: (value: unknown) => value is Obj;
21
+ export declare function refuseSecrets(value: unknown, at: string, file: string): void;
22
+ export declare function onlyKeys(value: Obj, allowed: readonly string[], where: string): void;
23
+ export declare function parseEndpoint(value: unknown, where: string, opts: ParseOptions): FoliwakeEndpoint;
24
+ export declare const AUTH_SHAPES: string;
25
+ export declare function parseBasicAuth(auth: Obj, where: string, opts: ParseOptions): BasicAuth;
26
+ export declare function parseServiceTokenAuth(auth: Obj, where: string, opts: ParseOptions): ServiceTokenAuth;
27
+ export declare function parseAuth(auth: unknown, where: string, opts: ParseOptions): RemoteAuth;
28
+ export declare function parsePrefix(value: unknown, fallback: string, where: string): string;
29
+ /** The proxy prefixes of a config without `proxies`: version 2, and version 3 (`/foliwake/…`, one handler). */
30
+ export declare const PROXY_DEFAULTS: {
31
+ readonly 2: {
32
+ readonly code: string;
33
+ readonly media: string;
34
+ };
35
+ readonly 3: {
36
+ readonly code: "/foliwake/code";
37
+ readonly media: "/foliwake/media";
38
+ };
39
+ };
40
+ export declare function parseProxies(value: unknown, where: string, defaults?: {
41
+ code: string;
42
+ media: string;
43
+ }): FoliwakeAppSettings['proxies'];
44
+ export declare function parseEntry(value: unknown, where: string): string | null;
45
+ export declare function parseBlocks(value: unknown, where: string): FoliwakeAppSettings['blocks'];
46
+ export declare function parseMedia(value: unknown, where: string): FoliwakeAppSettings['media'];
47
+ export declare function parsePages(value: unknown, where: string): string[];
48
+ /** `app.revalidate`: whole seconds, 1–86400; default 300. */
49
+ export declare function parseRevalidate(value: unknown, where: string): number;
50
+ export declare function parseApp(value: unknown, where: string): FoliwakeAppSettings;
@@ -0,0 +1,190 @@
1
+ // The parsers of the parts of a config file (auth, proxies, blocks, media, pages, app), shared by version 2
2
+ // (./config) and version 3 (./config-v3). Internal: not a package export.
3
+ import { FoliwakeConfigError } from './errors.js';
4
+ import { checkEnvName, checkUsername, parseRemoteUrl } from './config-checks.js';
5
+ import { globProblem, GLOB_LIMITS } from './glob.js';
6
+ export const SECRET_KEYS = /^(password|passwd|pass|secret|token|apikey|api_key|authorization|credentials?|private_?key|signing_?key|jwk|d)$/i;
7
+ export const ISSUER = /^[A-Za-z0-9._:/-]{1,256}$/;
8
+ export const KID = /^[A-Za-z0-9._-]{1,128}$/;
9
+ export const SITE = /^[a-z0-9][a-z0-9-]{0,62}$/;
10
+ export const PREFIX = /^(?:\/[a-z0-9-]+)+$/;
11
+ export const RESERVED_PREFIXES = ['/', '/_next', '/api', '/code', '/media'];
12
+ export const ENTRY_SEGMENT = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/;
13
+ export const ENTRY_ROOTS = ['scripts', 'components', '_foliwake'];
14
+ export const CONTRACT = /^foliwake-blocks\/([1-9][0-9]{0,2})$/;
15
+ export const EVENT_PREFIX = /^[a-z][a-z0-9-]{0,31}$/;
16
+ export const DEFAULTS = { code: '/foliwake-code', media: '/foliwake-media', contract: 'foliwake-blocks/2', eventPrefix: 'block', revalidate: 300 };
17
+ export const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
18
+ export function refuseSecrets(value, at, file) {
19
+ if (Array.isArray(value))
20
+ value.forEach((item, i) => refuseSecrets(item, `${at}[${i}]`, file));
21
+ if (!isObject(value))
22
+ return;
23
+ for (const [key, child] of Object.entries(value)) {
24
+ if (SECRET_KEYS.test(key)) {
25
+ throw new FoliwakeConfigError(`${file}: "${at}${key}" looks like a stored secret. This file is committed: ` +
26
+ 'keep only the NAME of an environment variable ("passwordEnv", "privateKeyEnv") ' +
27
+ 'and remove the secret (rotate it if it was committed).');
28
+ }
29
+ refuseSecrets(child, `${at}${key}.`, file);
30
+ }
31
+ }
32
+ export function onlyKeys(value, allowed, where) {
33
+ for (const key of Object.keys(value)) {
34
+ if (!allowed.includes(key))
35
+ throw new FoliwakeConfigError(`${where}: unknown key "${key}" (allowed: ${allowed.join(', ')}).`);
36
+ }
37
+ }
38
+ export function parseEndpoint(value, where, opts) {
39
+ if (!isObject(value))
40
+ throw new FoliwakeConfigError(`${where}: must be an object {"url": …, "auth": …}.`);
41
+ onlyKeys(value, ['url', 'auth'], where);
42
+ const origin = parseRemoteUrl(value.url, `${where}.url`);
43
+ if (value.auth === undefined || value.auth === null)
44
+ return { origin, auth: null };
45
+ return { origin, auth: parseAuth(value.auth, `${where}.auth`, opts) };
46
+ }
47
+ export const AUTH_SHAPES = '{"type": "basic", "username": …, "passwordEnv": …} or ' +
48
+ '{"type": "service-token", "issuer": …, "kid": …, "privateKeyEnv": …}';
49
+ export function parseBasicAuth(auth, where, opts) {
50
+ onlyKeys(auth, ['type', 'username', 'passwordEnv'], where);
51
+ return {
52
+ type: 'basic',
53
+ username: checkUsername(auth.username, `${where}.username`),
54
+ passwordEnv: checkEnvName(auth.passwordEnv, `${where}.passwordEnv`, opts.envNameProblem),
55
+ };
56
+ }
57
+ export function parseServiceTokenAuth(auth, where, opts) {
58
+ onlyKeys(auth, ['type', 'issuer', 'kid', 'privateKeyEnv'], where);
59
+ if (typeof auth.issuer !== 'string' || !ISSUER.test(auth.issuer)) {
60
+ throw new FoliwakeConfigError(`${where}.issuer: the issuer the delivery expects (its TOKEN_ISSUER), [A-Za-z0-9._:/-], such as "my-app".`);
61
+ }
62
+ if (typeof auth.kid !== 'string' || !KID.test(auth.kid)) {
63
+ throw new FoliwakeConfigError(`${where}.kid: the key id of the public key the delivery holds, [A-Za-z0-9._-], such as "my-app-2026-11".`);
64
+ }
65
+ return {
66
+ type: 'service-token',
67
+ issuer: auth.issuer,
68
+ kid: auth.kid,
69
+ privateKeyEnv: checkEnvName(auth.privateKeyEnv, `${where}.privateKeyEnv`, opts.envNameProblem),
70
+ };
71
+ }
72
+ export function parseAuth(auth, where, opts) {
73
+ if (!isObject(auth))
74
+ throw new FoliwakeConfigError(`${where}: must be ${AUTH_SHAPES}.`);
75
+ if (auth.type === 'basic')
76
+ return parseBasicAuth(auth, where, opts);
77
+ if (auth.type === 'service-token')
78
+ return parseServiceTokenAuth(auth, where, opts);
79
+ throw new FoliwakeConfigError(`${where}.type: "basic" or "service-token"; the auth must be ${AUTH_SHAPES}.`);
80
+ }
81
+ export function parsePrefix(value, fallback, where) {
82
+ if (value === undefined)
83
+ return fallback;
84
+ if (typeof value !== 'string' || !PREFIX.test(value))
85
+ throw new FoliwakeConfigError(`${where}: an absolute app path of [a-z0-9-] segments, such as "${fallback}".`);
86
+ return value;
87
+ }
88
+ /** The proxy prefixes of a config without `proxies`: version 2, and version 3 (`/foliwake/…`, one handler). */
89
+ export const PROXY_DEFAULTS = {
90
+ 2: { code: DEFAULTS.code, media: DEFAULTS.media },
91
+ 3: { code: '/foliwake/code', media: '/foliwake/media' },
92
+ };
93
+ export function parseProxies(value, where, defaults = PROXY_DEFAULTS[2]) {
94
+ if (value === undefined)
95
+ return { code: defaults.code, media: defaults.media, pages: null };
96
+ if (!isObject(value))
97
+ throw new FoliwakeConfigError(`${where}: must be an object {"code": …, "media": …, "pages": null}.`);
98
+ onlyKeys(value, ['code', 'media', 'pages'], where);
99
+ if (value.pages !== undefined && value.pages !== null)
100
+ throw new FoliwakeConfigError(`${where}.pages: must be null in this version (the pages proxy comes with client-side reads).`);
101
+ const proxies = {
102
+ code: parsePrefix(value.code, defaults.code, `${where}.code`),
103
+ media: parsePrefix(value.media, defaults.media, `${where}.media`),
104
+ pages: null,
105
+ };
106
+ const list = [proxies.code, proxies.media];
107
+ for (const prefix of list) {
108
+ const reserved = RESERVED_PREFIXES.find((r) => prefix === r || (r !== '/' && prefix.startsWith(`${r}/`)));
109
+ if (reserved)
110
+ throw new FoliwakeConfigError(`${where}: "${prefix}" collides with the reserved app path ${reserved}.`);
111
+ }
112
+ if (proxies.code === proxies.media || proxies.code.startsWith(`${proxies.media}/`) || proxies.media.startsWith(`${proxies.code}/`)) {
113
+ throw new FoliwakeConfigError(`${where}: "code" and "media" must be different prefixes, neither inside the other.`);
114
+ }
115
+ return proxies;
116
+ }
117
+ export function parseEntry(value, where) {
118
+ if (value === undefined || value === null)
119
+ return null;
120
+ const problem = 'a path inside a code release, such as "scripts/blocks.js": 1–8 segments of [A-Za-z0-9_.-], the first one scripts, components or _foliwake, ending in .js';
121
+ if (typeof value !== 'string')
122
+ throw new FoliwakeConfigError(`${where}: ${problem}.`);
123
+ const segments = value.split('/');
124
+ if (segments.length < 2 || segments.length > 8 || !ENTRY_ROOTS.includes(segments[0]) || !value.endsWith('.js')
125
+ || segments.some((s) => !ENTRY_SEGMENT.test(s) || s === '.' || s === '..' || s.includes('..'))) {
126
+ throw new FoliwakeConfigError(`${where}: ${problem}.`);
127
+ }
128
+ return value;
129
+ }
130
+ export function parseBlocks(value, where) {
131
+ const blocks = value === undefined ? {} : value;
132
+ if (!isObject(blocks))
133
+ throw new FoliwakeConfigError(`${where}: must be an object {"entry": …, "contract": …, "eventPrefix": …}.`);
134
+ onlyKeys(blocks, ['entry', 'contract', 'eventPrefix'], where);
135
+ const contract = blocks.contract === undefined ? DEFAULTS.contract : blocks.contract;
136
+ const match = typeof contract === 'string' ? CONTRACT.exec(contract) : null;
137
+ if (!match)
138
+ throw new FoliwakeConfigError(`${where}.contract: "foliwake-blocks/<major>", such as "foliwake-blocks/2".`);
139
+ const eventPrefix = blocks.eventPrefix === undefined ? DEFAULTS.eventPrefix : blocks.eventPrefix;
140
+ if (typeof eventPrefix !== 'string' || !EVENT_PREFIX.test(eventPrefix))
141
+ throw new FoliwakeConfigError(`${where}.eventPrefix: [a-z][a-z0-9-], at most 32 characters.`);
142
+ const entry = parseEntry(blocks.entry, `${where}.entry`);
143
+ return { entry, contract: contract, major: Number(match[1]), eventPrefix, fromRelease: false };
144
+ }
145
+ export function parseMedia(value, where) {
146
+ if (value === undefined || value === null)
147
+ return null;
148
+ if (!isObject(value))
149
+ throw new FoliwakeConfigError(`${where}: must be an object {"base": "https://…", "transform": "cloudflare-images"}.`);
150
+ onlyKeys(value, ['base', 'transform'], where);
151
+ const base = parseRemoteUrl(value.base, `${where}.base`);
152
+ if (!base.startsWith('https:'))
153
+ throw new FoliwakeConfigError(`${where}.base: must be https.`);
154
+ if (value.transform !== undefined && value.transform !== null && value.transform !== 'cloudflare-images') {
155
+ throw new FoliwakeConfigError(`${where}.transform: only "cloudflare-images" (or null) is supported.`);
156
+ }
157
+ return { base, transform: value.transform === 'cloudflare-images' ? 'cloudflare-images' : null };
158
+ }
159
+ export function parsePages(value, where) {
160
+ if (!Array.isArray(value) || value.length === 0 || value.length > GLOB_LIMITS.globsPerList) {
161
+ throw new FoliwakeConfigError(`${where}: a list of 1–${GLOB_LIMITS.globsPerList} page globs, such as ["/lessons/**"].`);
162
+ }
163
+ return value.map((glob, i) => {
164
+ const problem = typeof glob === 'string' ? globProblem(glob) : 'must be a string';
165
+ if (problem)
166
+ throw new FoliwakeConfigError(`${where}[${i}]: ${problem}.`);
167
+ return glob;
168
+ });
169
+ }
170
+ /** `app.revalidate`: whole seconds, 1–86400; default 300. */
171
+ export function parseRevalidate(value, where) {
172
+ const revalidate = value === undefined ? DEFAULTS.revalidate : value;
173
+ if (typeof revalidate !== 'number' || !Number.isInteger(revalidate) || revalidate < 1 || revalidate > 86_400) {
174
+ throw new FoliwakeConfigError(`${where}: whole seconds between 1 and 86400.`);
175
+ }
176
+ return revalidate;
177
+ }
178
+ export function parseApp(value, where) {
179
+ if (!isObject(value))
180
+ throw new FoliwakeConfigError(`${where}: must be an object {"pages": […], …}.`);
181
+ onlyKeys(value, ['pages', 'proxies', 'blocks', 'media', 'revalidate'], where);
182
+ const revalidate = parseRevalidate(value.revalidate, `${where}.revalidate`);
183
+ return {
184
+ pages: Object.freeze(parsePages(value.pages, `${where}.pages`)),
185
+ proxies: parseProxies(value.proxies, `${where}.proxies`),
186
+ blocks: parseBlocks(value.blocks, `${where}.blocks`),
187
+ media: parseMedia(value.media, `${where}.media`),
188
+ revalidate,
189
+ };
190
+ }
@@ -0,0 +1,22 @@
1
+ import { type FoliwakeAppConfig, type RemoteAuth } from './config.js';
2
+ import { type Obj } from './config-parts.js';
3
+ import type { FoliwakeDiscovery } from './discovery.js';
4
+ /** The variable the default preview credential reads: Basic `preview:<site preview token>`. */
5
+ export declare const PREVIEW_TOKEN_ENV = "FOLIWAKE_PREVIEW_TOKEN";
6
+ /** A parsed version 3 file: every part optional. */
7
+ export interface FoliwakeOverrides {
8
+ site: string | null;
9
+ liveAuth: RemoteAuth | null;
10
+ previewAuth: RemoteAuth | null;
11
+ app: Obj;
12
+ from: string;
13
+ }
14
+ /** Parses the text of a version 3 file. Throws FoliwakeConfigError naming the field. */
15
+ export declare function parseOverrides(text: string, file?: string): FoliwakeOverrides;
16
+ /** No file: the overrides of an empty version 3 file. */
17
+ export declare function emptyOverrides(): FoliwakeOverrides;
18
+ /**
19
+ * The app config of a site: its discovery document, with the version 3 file's overrides. Preview, when the site
20
+ * has it, is read with Basic `preview` and the token in FOLIWAKE_PREVIEW_TOKEN unless the file names another auth.
21
+ */
22
+ export declare function resolveConfig(discovery: FoliwakeDiscovery, overrides?: FoliwakeOverrides): FoliwakeAppConfig;
@@ -0,0 +1,104 @@
1
+ // Version 3: the app is configured by FOLIWAKE_URL. The site's discovery document gives the origins and the media
2
+ // CDN; `foliwake.remote.json` version 3 is optional and holds only the app's own decisions (overrides): pages,
3
+ // revalidate, proxies, media transform, blocks, and the credentials of each channel by variable NAME.
4
+ // Without FOLIWAKE_URL a version 2 file is read as before (./config).
5
+ import { CONFIG_FILE } from './config.js';
6
+ import { DEFAULTS, isObject, onlyKeys, parseAuth, parseBlocks, parseMedia, parsePages, parseProxies, parseRevalidate, PROXY_DEFAULTS, refuseSecrets, } from './config-parts.js';
7
+ import { FoliwakeConfigError } from './errors.js';
8
+ /** The variable the default preview credential reads: Basic `preview:<site preview token>`. */
9
+ export const PREVIEW_TOKEN_ENV = 'FOLIWAKE_PREVIEW_TOKEN';
10
+ const APP_KEYS = ['pages', 'proxies', 'blocks', 'media', 'revalidate'];
11
+ function channelAuth(value, where) {
12
+ if (value === undefined)
13
+ return null;
14
+ if (!isObject(value))
15
+ throw new FoliwakeConfigError(`${where}: must be an object {"auth": …}.`);
16
+ onlyKeys(value, ['auth'], where);
17
+ return value.auth === undefined || value.auth === null ? null : parseAuth(value.auth, `${where}.auth`, {});
18
+ }
19
+ function parsedObject(text, file) {
20
+ let parsed;
21
+ try {
22
+ parsed = JSON.parse(text);
23
+ }
24
+ catch (error) {
25
+ throw new FoliwakeConfigError(`${file} is not valid JSON: ${error.message}`);
26
+ }
27
+ if (!isObject(parsed))
28
+ throw new FoliwakeConfigError(`${file} must be a JSON object {"version": 3, …}.`);
29
+ refuseSecrets(parsed, '', file);
30
+ return parsed;
31
+ }
32
+ /** Parses the text of a version 3 file. Throws FoliwakeConfigError naming the field. */
33
+ export function parseOverrides(text, file = CONFIG_FILE) {
34
+ const parsed = parsedObject(text, file);
35
+ onlyKeys(parsed, ['$schema', '$comment', 'version', 'site', 'live', 'preview', 'app'], file);
36
+ if (parsed.version !== 3)
37
+ throw new FoliwakeConfigError(`${file}: "version" must be 3 here.`);
38
+ const app = parsed.app === undefined ? {} : parsed.app;
39
+ if (!isObject(app))
40
+ throw new FoliwakeConfigError(`${file} "app": must be an object.`);
41
+ onlyKeys(app, APP_KEYS, `${file} "app"`);
42
+ if (parsed.site !== undefined && typeof parsed.site !== 'string') {
43
+ throw new FoliwakeConfigError(`${file} "site": the site name, such as "my-site".`);
44
+ }
45
+ return {
46
+ site: parsed.site ?? null,
47
+ liveAuth: channelAuth(parsed.live, `${file} "live"`),
48
+ previewAuth: channelAuth(parsed.preview, `${file} "preview"`),
49
+ app,
50
+ from: file,
51
+ };
52
+ }
53
+ function defaultPreviewAuth() {
54
+ return { type: 'basic', username: 'preview', passwordEnv: PREVIEW_TOKEN_ENV };
55
+ }
56
+ /** No `app.blocks`: the code release of each page names its blocks module (`X-Foliwake-Blocks`). */
57
+ function releaseBlocks() {
58
+ return { entry: null, contract: DEFAULTS.contract, major: 2, eventPrefix: DEFAULTS.eventPrefix, fromRelease: true };
59
+ }
60
+ // `/**` is safe while live is read anonymously (the site's access rules decide). With a service token the app
61
+ // could read closed pages, so it must say which ones.
62
+ function pagesOf(app, liveAuth, where) {
63
+ if (app.pages !== undefined)
64
+ return Object.freeze(parsePages(app.pages, `${where}.pages`));
65
+ if (liveAuth?.type === 'service-token') {
66
+ throw new FoliwakeConfigError(`${where}.pages: required when "live" uses a service token (list the pages).`);
67
+ }
68
+ return Object.freeze(['/**']);
69
+ }
70
+ function mediaOf(app, discovery, where) {
71
+ if (app.media !== undefined)
72
+ return parseMedia(app.media, `${where}.media`);
73
+ return discovery.media ? { base: discovery.media.cdn, transform: null } : null;
74
+ }
75
+ function appSettings(overrides, discovery) {
76
+ const { app } = overrides;
77
+ const where = `${overrides.from} "app"`;
78
+ return {
79
+ pages: pagesOf(app, overrides.liveAuth, where),
80
+ proxies: parseProxies(app.proxies, `${where}.proxies`, PROXY_DEFAULTS[3]),
81
+ blocks: app.blocks === undefined ? releaseBlocks() : parseBlocks(app.blocks, `${where}.blocks`),
82
+ media: mediaOf(app, discovery, where),
83
+ revalidate: parseRevalidate(app.revalidate, `${where}.revalidate`),
84
+ };
85
+ }
86
+ /** No file: the overrides of an empty version 3 file. */
87
+ export function emptyOverrides() {
88
+ return { site: null, liveAuth: null, previewAuth: null, app: {}, from: 'FOLIWAKE_URL' };
89
+ }
90
+ /**
91
+ * The app config of a site: its discovery document, with the version 3 file's overrides. Preview, when the site
92
+ * has it, is read with Basic `preview` and the token in FOLIWAKE_PREVIEW_TOKEN unless the file names another auth.
93
+ */
94
+ export function resolveConfig(discovery, overrides = emptyOverrides()) {
95
+ if (overrides.site !== null && overrides.site !== discovery.site) {
96
+ const text = `"site" is ${overrides.site}, but ${discovery.live.url} serves the site ${discovery.site}.`;
97
+ throw new FoliwakeConfigError(`${overrides.from}: ${text}`);
98
+ }
99
+ const live = { origin: discovery.live.url, auth: overrides.liveAuth };
100
+ const previewAuth = overrides.previewAuth ?? defaultPreviewAuth();
101
+ const preview = discovery.preview ? { origin: discovery.preview.url, auth: previewAuth } : null;
102
+ const app = appSettings(overrides, discovery);
103
+ return Object.freeze({ version: 3, site: discovery.site, live, preview, app, from: overrides.from });
104
+ }
package/dist/config.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { ChannelName, ClientSettings } from '@foliwake/blocks-contract/page';
2
2
  export { FoliwakeConfigError } from './errors.js';
3
+ export { checkEnvName, checkUsername, isLoopbackName, parseRemoteUrl } from './config-checks.js';
3
4
  export type { ClientSettings } from '@foliwake/blocks-contract/page';
4
5
  /** The default config file name, looked up in the current directory. */
5
6
  export declare const CONFIG_FILE = "foliwake.remote.json";
@@ -44,12 +45,16 @@ export interface FoliwakeAppSettings {
44
45
  media: string;
45
46
  pages: null;
46
47
  };
47
- /** Where `mountBlocks` lives in a code release; null: bodies stay static. */
48
+ /**
49
+ * Where `mountBlocks` lives in a code release; null: bodies stay static. `fromRelease`: the config names no
50
+ * blocks (version 3), so each page's code release names them (`X-Foliwake-Blocks`); false for version 2.
51
+ */
48
52
  blocks: {
49
53
  entry: string | null;
50
54
  contract: string;
51
55
  major: number;
52
56
  eventPrefix: string;
57
+ fromRelease: boolean;
53
58
  };
54
59
  /** Live media through a transforming host; null: media through the proxy. */
55
60
  media: {
@@ -59,9 +64,12 @@ export interface FoliwakeAppSettings {
59
64
  /** Seconds before a cached envelope is stale (stale-while-revalidate). */
60
65
  revalidate: number;
61
66
  }
62
- /** A parsed and validated `foliwake.remote.json` (version 2). It holds credential variable names, never secrets. */
67
+ /**
68
+ * A validated app config: a `foliwake.remote.json` version 2, or (version 3) the site's discovery document merged
69
+ * with the optional version 3 file. It holds credential variable names, never secrets.
70
+ */
63
71
  export interface FoliwakeAppConfig {
64
- version: 2;
72
+ version: 2 | 3;
65
73
  site: string;
66
74
  live: FoliwakeEndpoint | null;
67
75
  preview: FoliwakeEndpoint | null;
@@ -79,14 +87,6 @@ export interface ParseOptions {
79
87
  /** An additional rule for credential variable names (the engine CLI passes its own). */
80
88
  envNameProblem?: (name: string, what: string) => string | null;
81
89
  }
82
- /** True for 127.x, localhost, *.localhost and ::1. */
83
- export declare function isLoopbackName(hostname: string): boolean;
84
- /** A site origin: https (http only for loopback), no credentials, path, query or fragment. */
85
- export declare function parseRemoteUrl(value: unknown, where: string): string;
86
- /** Validates an environment variable NAME (never a value). */
87
- export declare function checkEnvName(value: unknown, where: string, extra?: ParseOptions['envNameProblem']): string;
88
- /** Validates a Basic user name (no `:` or control characters, at most 128 characters). */
89
- export declare function checkUsername(value: unknown, where: string): string;
90
90
  /** Parses the text of a version 2 config. Throws FoliwakeConfigError with a message that names the field. */
91
91
  export declare function parseFoliwakeConfig(text: string, opts?: ParseOptions): FoliwakeAppConfig;
92
92
  /** The endpoint of a channel; a missing one is an error, never replaced by the other channel. */