@realadvisor-sites/kit-react 0.0.0-stage → 0.4.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.
Files changed (43) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +211 -2
  3. package/bin/sites-kit-react.mjs +26 -0
  4. package/client/index.ts +21 -0
  5. package/client/islands.ts +33 -0
  6. package/components/ConsentBanner.tsx +25 -0
  7. package/components/Document.tsx +170 -0
  8. package/components/EnquiryForm.tsx +107 -0
  9. package/components/Island.tsx +39 -0
  10. package/components/LanguageSwitch.tsx +24 -0
  11. package/components/LegalContent.tsx +30 -0
  12. package/components/ListingsMap.tsx +76 -0
  13. package/components/ListingsPager.tsx +25 -0
  14. package/components/ListingsSearch.tsx +294 -0
  15. package/components/RaImage.tsx +107 -0
  16. package/components/SafeHtml.tsx +30 -0
  17. package/components/form/Button.tsx +22 -0
  18. package/components/form/Combobox.tsx +34 -0
  19. package/components/form/Input.tsx +24 -0
  20. package/components/form/Select.tsx +30 -0
  21. package/components/index.ts +15 -0
  22. package/env.d.ts +36 -0
  23. package/lib/image.ts +36 -0
  24. package/lib/records.ts +17 -0
  25. package/lib/search.ts +37 -0
  26. package/package.json +63 -4
  27. package/server/data.ts +82 -0
  28. package/server/enquiry.ts +9 -0
  29. package/server/entry.server.tsx +54 -0
  30. package/server/fixture-client.ts +2 -0
  31. package/server/kit.ts +52 -0
  32. package/server/security.ts +32 -0
  33. package/server/seo.ts +39 -0
  34. package/server/worker.ts +146 -0
  35. package/styles/consent.css +6 -0
  36. package/styles/kit.css +21 -0
  37. package/styles/map.css +58 -0
  38. package/styles/pager.css +14 -0
  39. package/styles/search.css +162 -0
  40. package/tools/check-deploy.mjs +280 -0
  41. package/tools/preview.mjs +77 -0
  42. package/vite.d.mts +2 -0
  43. package/vite.mjs +180 -0
@@ -0,0 +1,280 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Deploy gate of a React Router site: the Astro kit's check:deploy rules
4
+ * (kit/tools/check-deploy.mjs, imported, not copied) run against the
5
+ * built Worker, plus the nonce rules of the React kit.
6
+ *
7
+ * pnpm check:deploy # build, then check
8
+ * pnpm check:deploy --no-build # check the build/ that is there
9
+ *
10
+ * Serves build/ with `wrangler dev` (build/server/wrangler.json, what
11
+ * publish deploys) and requests: one page of every route in the sitemap,
12
+ * `?view=map` of every search page, legal and privacy of every language,
13
+ * an unknown path, an unknown listing and a listing that left (404/410).
14
+ *
15
+ * FAIL (exit 1) on, per page:
16
+ * - the Astro kit's rules: security headers, CSP hosts only from
17
+ * ALLOWED_HOSTS, no 'unsafe-inline' in script-src, no inline handlers,
18
+ * iframes, off-site or non-enquiry POST forms, form services, external
19
+ * hosts, broken same-origin assets, legal links per language, empty or
20
+ * cut 200 bodies, missing pages that do not answer 404/410 with a page;
21
+ * - nonce: script-src has exactly one 'nonce-…' (>= 128 bits, base64) and
22
+ * otherwise equals the kit's CSP; a second request gets another nonce;
23
+ * every <script> (inline, src, JSON-LD) carries the response's nonce;
24
+ * - static files: build/client/_headers gives assets the kit's headers
25
+ * (no nonce) and an asset answers with them;
26
+ * - the enquiry endpoint: an invalid POST is a 400 `invalid`, a valid one
27
+ * `{ preview: true }` (the gate runs as a preview: nothing is sent);
28
+ * - source: `dangerouslySetInnerHTML` in app/ only as `{{ __html: sanitizeHtml(...) }}`
29
+ * or `safeJsonLd(...)`; HTML sanitized earlier (in the loader) goes
30
+ * through the kit's `sanitized()` + `<SafeHtml>` (typed: tsc checks it);
31
+ * - secrets in build/ (the kit's secret-leaks).
32
+ *
33
+ * Output: "FAIL <page>: <reason>" lines, then a JSON summary as the last line.
34
+ */
35
+ import { spawn, spawnSync } from 'node:child_process';
36
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
37
+ import { join, relative } from 'node:path';
38
+ import { pathToFileURL } from 'node:url';
39
+ import {
40
+ allowedHosts,
41
+ checkAssets,
42
+ checkPage,
43
+ freePort,
44
+ legalLanguageProblems,
45
+ loadedUrls,
46
+ offHosts,
47
+ pageAssets,
48
+ parseTags,
49
+ } from '@realadvisor/sites-kit-core/tools/check-deploy.mjs';
50
+ import { buildLeaks } from '@realadvisor/sites-kit-core/tools/secret-leaks.mjs';
51
+ import { csp as kitCsp } from '@realadvisor/sites-kit-core/security';
52
+
53
+ const JS_TYPES = new Set(['', 'module', 'text/javascript', 'application/javascript']);
54
+ const LISTING_PATH = /^\/[^/]+\/[^/]+-[0-9a-f]{8}-[0-9a-f]{4}-/i;
55
+ const NONCE_SRC = /'nonce-([^']*)'/g;
56
+
57
+ /** The nonce of a CSP header and the problems with it (one nonce, base64, >= 16 bytes, rest = kit CSP). */
58
+ export function nonceOf(csp, preview) {
59
+ const problems = [];
60
+ const script = csp.split(';').map((d) => d.trim()).find((d) => d.startsWith('script-src ')) ?? '';
61
+ const nonces = [...script.matchAll(NONCE_SRC)].map((m) => m[1]);
62
+ if (nonces.length !== 1) problems.push(`script-src has ${nonces.length} nonces (want exactly one per response)`);
63
+ const nonce = nonces[0] ?? '';
64
+ if (nonce && (!/^[A-Za-z0-9+/]+={0,2}$/.test(nonce) || Buffer.from(nonce, 'base64').length < 16)) problems.push(`nonce "${nonce}" is not 128+ random bits in base64`);
65
+ if ([...csp.matchAll(NONCE_SRC)].length !== nonces.length) problems.push('a nonce outside script-src');
66
+ if (/'strict-dynamic'|'unsafe-hashes'|'sha(256|384|512)-/.test(csp)) problems.push("CSP has a hash or 'strict-dynamic': only the kit's sources and one nonce are allowed");
67
+ const without = csp.replace(/ 'nonce-[^']*'/g, '');
68
+ for (const mode of [preview, !preview]) if (without === kitCsp(mode)) return { nonce, problems };
69
+ problems.push(`CSP (without its nonce) differs from the kit's: ${without}`);
70
+ return { nonce, problems };
71
+ }
72
+
73
+ /** <script> tags of a page without the response's nonce: [{ what }]. */
74
+ export function scriptsWithoutNonce(tags, nonce) {
75
+ const out = [];
76
+ for (const t of tags.filter((x) => x.name === 'script')) {
77
+ if (t.attrs.get('nonce') === nonce && nonce) continue;
78
+ const type = (t.attrs.get('type') ?? '').toLowerCase();
79
+ const what = t.attrs.get('src') ? `<script src="${t.attrs.get('src').slice(0, 60)}">` : JS_TYPES.has(type) ? `inline <script> (${(t.body ?? '').trim().slice(0, 40)}…)` : `<script type="${type}">`;
80
+ out.push({ what, inline: !t.attrs.get('src') && JS_TYPES.has(type) && !!t.body?.trim() });
81
+ }
82
+ return out;
83
+ }
84
+
85
+ /** The page with its nonce'd inline scripts taken out: what the Astro rules see (they allow none). */
86
+ const withoutNoncedInline = (html, nonce) =>
87
+ nonce ? html.replace(/<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi, (m, attrs) => (new RegExp(`\\bnonce=["']?${nonce.replace(/[+/=]/g, '\\$&')}["']?`).test(attrs) ? '' : m)) : html;
88
+
89
+ /** dangerouslySetInnerHTML in the site's source only through sanitizeHtml(...) or safeJsonLd(...); <SafeHtml> for HTML sanitized in the loader. */
90
+ export function unsafeHtml(root) {
91
+ const out = [];
92
+ const walk = (d) =>
93
+ existsSync(d)
94
+ ? readdirSync(d).flatMap((f) => {
95
+ const p = join(d, f);
96
+ return statSync(p).isDirectory() ? walk(p) : /\.(tsx?|jsx?)$/.test(f) ? [p] : [];
97
+ })
98
+ : [];
99
+ for (const file of walk(join(root, 'app'))) {
100
+ for (const m of readFileSync(file, 'utf8').matchAll(/dangerouslySetInnerHTML=\{\{\s*__html:\s*([^}]*)\}\}/g)) {
101
+ const expr = m[1].trim();
102
+ if (/^(sanitizeHtml|safeJsonLd)\([^()]*(\([^()]*\))?[^()]*\)$/.test(expr)) continue;
103
+ out.push({ page: relative(root, file), message: `dangerouslySetInnerHTML={{ __html: ${expr.slice(0, 40)} }} renders unescaped HTML: use sanitizeHtml(…) from @realadvisor/sites-kit-core, or sanitized() in the loader + <SafeHtml> from @realadvisor/sites-kit-react (or <JsonLd>)` });
104
+ }
105
+ // Any other form (a variable, a spread object) cannot be read here: <SafeHtml> is the typed way.
106
+ for (const m of readFileSync(file, 'utf8').matchAll(/dangerouslySetInnerHTML=\{(?!\{)\s*([^}]{0,60})/g)) {
107
+ out.push({ page: relative(root, file), message: `dangerouslySetInnerHTML={${m[1].trim().slice(0, 40)}} cannot be checked: use sanitized() in the loader + <SafeHtml html={…}> from @realadvisor/sites-kit-react` });
108
+ }
109
+ }
110
+ return out;
111
+ }
112
+
113
+ /** One sample path per route pattern of the sitemap (first segment + depth), legal pages all. */
114
+ export function samplePages(locs) {
115
+ const paths = locs.map((l) => { try { return new URL(l).pathname; } catch { return ''; } }).filter(Boolean);
116
+ const seen = new Set();
117
+ const pick = [];
118
+ for (const p of paths) {
119
+ const segs = p.split('/').filter(Boolean);
120
+ const key = segs.length <= 1 ? p : `${segs[0]}/*${segs.length}`;
121
+ if (/\/(legal|privacy)$/.test(p) || !seen.has(key)) pick.push(p);
122
+ seen.add(key);
123
+ }
124
+ // A second listing (a sold one may render differently).
125
+ const listings = paths.filter((p) => LISTING_PATH.test(p));
126
+ if (listings[1] && !pick.includes(listings[1])) pick.push(listings[1]);
127
+ return pick;
128
+ }
129
+
130
+ export function missingPages(locs) {
131
+ const paths = locs.map((l) => { try { return new URL(l).pathname; } catch { return ''; } });
132
+ const listing = paths.find((p) => LISTING_PATH.test(p));
133
+ const dir = listing ? listing.slice(0, listing.lastIndexOf('/')) : '/listings';
134
+ return ['/__ra-check-deploy-404', `${dir}/ra-check-missing`, `${dir}/ra-check-gone-00000000-0000-4000-8000-000000000000`];
135
+ }
136
+
137
+ async function serve(root) {
138
+ const port = Number(process.env.CHECK_PORT ?? (await freePort()));
139
+ const inspector = await freePort();
140
+ const base = `http://127.0.0.1:${port}`;
141
+ const server = spawn(
142
+ 'pnpm',
143
+ ['exec', 'wrangler', 'dev', '--config', 'build/server/wrangler.json', '--port', String(port), '--inspector-port', String(inspector), '--ip', '127.0.0.1', '--log-level', 'error', '--show-interactive-dev-session=false', '--persist-to', join(root, '.wrangler/check-deploy')],
144
+ { cwd: root, stdio: ['ignore', 'ignore', 'inherit'], detached: true },
145
+ );
146
+ const stop = () => { try { process.kill(-server.pid); } catch {} };
147
+ process.on('exit', stop);
148
+ let exited = false;
149
+ server.on('exit', () => (exited = true));
150
+ const up = async () => { try { return (await fetch(`${base}/robots.txt`)).status < 500; } catch { return false; } };
151
+ for (let i = 0; i < 120 && !exited && !(await up()); i++) await new Promise((r) => setTimeout(r, 500));
152
+ if (exited || !(await up())) { stop(); throw new Error('wrangler dev did not start'); }
153
+ return { base, stop };
154
+ }
155
+
156
+ async function main() {
157
+ const t0 = Date.now();
158
+ const root = process.cwd();
159
+ const args = process.argv.slice(2);
160
+ const problems = [];
161
+ const pages = [];
162
+ const fail = (page, rule, message) => problems.push({ page, rule, message: String(message) });
163
+ const finish = () => {
164
+ const grouped = new Map();
165
+ for (const p of problems) {
166
+ const key = `${p.rule}\0${p.message}`;
167
+ const g = grouped.get(key);
168
+ if (g) g.n++;
169
+ else grouped.set(key, { ...p, n: 1 });
170
+ }
171
+ const list = [...grouped.values()].map(({ n, ...p }) => ({ ...p, page: n > 1 ? `${p.page} (+${n - 1} more)` : p.page }));
172
+ for (const p of list) console.log(`FAIL ${p.page}: ${p.message}`);
173
+ console.log(list.length ? `\ncheck:deploy FAILED (${list.length})` : `\ncheck:deploy OK (${pages.length} requests)`);
174
+ console.log(JSON.stringify({ ok: !list.length, problems: list, pages, ms: Date.now() - t0 }));
175
+ process.exit(list.length ? 1 : 0);
176
+ };
177
+
178
+ for (const u of unsafeHtml(root)) fail(u.page, 'unsafe-html', u.message);
179
+ if (!args.includes('--no-build')) {
180
+ console.log('Building (pnpm build)…');
181
+ if (spawnSync('pnpm', ['build'], { cwd: root, stdio: 'inherit' }).status !== 0) {
182
+ fail('build', 'build', '`pnpm build` failed');
183
+ return finish();
184
+ }
185
+ }
186
+ if (!existsSync(join(root, 'build/server/wrangler.json'))) {
187
+ fail('build', 'build', 'no build/server/wrangler.json: build the site first');
188
+ return finish();
189
+ }
190
+ const leaks = buildLeaks(join(root, 'build'));
191
+ for (const l of leaks.slice(0, 10)) fail(`build/${l.file}`, 'secret-leak', l.message);
192
+ if (leaks.length) return finish();
193
+ const headersFile = join(root, 'build/client/_headers');
194
+ if (!existsSync(headersFile) || !/content-security-policy:/.test(readFileSync(headersFile, 'utf8'))) {
195
+ fail('build/client/_headers', 'security-headers', 'no _headers with the CSP for static files: keep sitesKit() in vite.config.ts');
196
+ }
197
+
198
+ let server;
199
+ try {
200
+ server = await serve(root);
201
+ } catch (e) {
202
+ fail('server', 'http', e.message);
203
+ return finish();
204
+ }
205
+ const { base } = server;
206
+ try {
207
+ const sm = await fetch(`${base}/sitemap.xml`).catch(() => null);
208
+ const locs = sm?.ok ? [...(await sm.text()).matchAll(/<loc>([^<]+)<\/loc>/g)].map((m) => m[1].trim()) : [];
209
+ if (!locs.length) fail('/sitemap.xml', 'http', 'no sitemap.xml with <loc> entries');
210
+ const self = new Set(locs.slice(0, 1).map((l) => new URL(l).origin));
211
+ const ctx = { base, self, allowed: allowedHosts() };
212
+ const assetsSeen = new Set();
213
+ const pageHtml = new Map();
214
+ const missing = missingPages(locs);
215
+ const queue = [...samplePages(locs), ...missing];
216
+ const nonces = new Set();
217
+ for (let qi = 0; qi < queue.length; qi++) {
218
+ const path = queue[qi];
219
+ const res = await fetch(`${base}${path}`, { redirect: 'manual' }).catch((e) => e);
220
+ if (res instanceof Error) { fail(path, 'http', `no answer: ${res.message}`); continue; }
221
+ pages.push(path);
222
+ const isMissing = missing.includes(path);
223
+ if (res.status >= 500) { fail(path, 'http', `HTTP ${res.status}`); continue; }
224
+ if (isMissing && res.status !== 404 && res.status !== 410) fail(path, 'not-found', `HTTP ${res.status} for a page that does not exist (want 404, or 410 for a listing that left)`);
225
+ if (!isMissing && res.status !== 200) fail(path, 'http', `HTTP ${res.status} for a page of the sitemap`);
226
+ if (res.status >= 300 && res.status < 400) continue;
227
+ const html = await res.text().catch(() => '');
228
+ const isHtml = /text\/html/.test(res.headers.get('content-type') ?? '');
229
+ if (isHtml && !/<\/html>/i.test(html)) fail(path, 'empty-page', `HTTP ${res.status} with an empty or cut body`);
230
+ if (!isHtml) continue;
231
+ const csp = res.headers.get('content-security-policy') ?? '';
232
+ const { nonce, problems: np } = nonceOf(csp, true);
233
+ for (const m of np) fail(path, 'nonce', m);
234
+ if (nonce && nonces.has(nonce)) fail(path, 'nonce', 'the same nonce on two responses: it must be new for every request');
235
+ nonces.add(nonce);
236
+ const tags = parseTags(html);
237
+ for (const s of scriptsWithoutNonce(tags, nonce).slice(0, 3)) fail(path, s.inline ? 'inline-script' : 'nonce', `${s.what} without the response's nonce`);
238
+ // The Astro kit's page rules, on the page without its (allowed) nonce'd inline scripts.
239
+ checkPage({ path, headers: res.headers, html: withoutNoncedInline(html, nonce), ...ctx }, (rule, m) => fail(path, rule, m));
240
+ for (const h of offHosts(loadedUrls(tags), ctx).slice(0, 5)) fail(path, 'hosts', `loads from external host ${h}`);
241
+ for (const m of (await checkAssets(pageAssets(tags, `${base}${path}`, base, self), { base, seen: assetsSeen })).slice(0, 5)) fail(path, 'assets', m);
242
+ if (res.status === 200) pageHtml.set(path, { html, tags });
243
+ // Search pages: their map view too.
244
+ if (/data-rs-root/.test(html) && !path.includes('view=map')) queue.splice(qi + 1, 0, `${path}${path.includes('?') ? '&' : '?'}view=map`);
245
+ // First page: a second request must get another nonce.
246
+ if (qi === 0) {
247
+ const again = await fetch(`${base}${path}`).catch(() => null);
248
+ const n2 = again ? nonceOf(again.headers.get('content-security-policy') ?? '', true).nonce : '';
249
+ await again?.body?.cancel();
250
+ if (!n2 || n2 === nonce) fail(path, 'nonce', 'two requests got the same nonce');
251
+ }
252
+ }
253
+ for (const p of await legalLanguageProblems({ base, pages: pageHtml, locs })) fail(p.page, 'legal-language', p.message);
254
+
255
+ // Static files carry the kit's headers (no nonce: they have no inline script).
256
+ const asset = [...assetsSeen].find((u) => /\.js$/.test(u));
257
+ if (asset) {
258
+ const r = await fetch(asset);
259
+ await r.body?.cancel();
260
+ const c = r.headers.get('content-security-policy') ?? '';
261
+ if (!/frame-ancestors/.test(c) || /'nonce-/.test(c)) fail(asset.slice(base.length), 'security-headers', 'a static file without the kit CSP (build/client/_headers)');
262
+ if ((r.headers.get('x-content-type-options') ?? '') !== 'nosniff') fail(asset.slice(base.length), 'security-headers', 'a static file without X-Content-Type-Options: nosniff');
263
+ }
264
+
265
+ // The enquiry endpoint: same contract as the Astro kit's /api/enquiry.
266
+ const post = (body) => fetch(`${base}/api/enquiry`, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json' }, body: JSON.stringify(body) });
267
+ const bad = await post({ name: '', email: 'x', message: '' }).catch(() => null);
268
+ const badBody = bad ? await bad.json().catch(() => ({})) : {};
269
+ if (bad?.status !== 400 || badBody.error !== 'invalid' || !badBody.fields?.email) fail('/api/enquiry', 'enquiry', `an invalid enquiry answered HTTP ${bad?.status} ${JSON.stringify(badBody).slice(0, 80)} (want 400 {error:'invalid', fields})`);
270
+ const ok = await post({ name: 'Check Deploy', email: 'check@example.com', message: 'check:deploy', contactReason: 'other' }).catch(() => null);
271
+ const okBody = ok ? await ok.json().catch(() => ({})) : {};
272
+ if (ok?.status !== 200 || okBody.preview !== true) fail('/api/enquiry', 'enquiry', `a valid enquiry on the preview answered HTTP ${ok?.status} ${JSON.stringify(okBody).slice(0, 80)} (want 200 {preview:true})`);
273
+ pages.push('POST /api/enquiry (x2)');
274
+ } finally {
275
+ server.stop();
276
+ }
277
+ finish();
278
+ }
279
+
280
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) await main();
@@ -0,0 +1,77 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `pnpm preview`: serves build/ with `wrangler dev` (build/server/wrangler.json)
4
+ * and restarts it when a new build lands. Plain `wrangler dev --config
5
+ * build/server/wrangler.json` keeps serving the build it started with:
6
+ * `react-router build` replaces build/ and wrangler does not see it.
7
+ *
8
+ * sites-kit-react preview [--port 4522] [other wrangler dev flags]
9
+ */
10
+ import { spawn } from 'node:child_process';
11
+ import { existsSync, statSync, watchFile } from 'node:fs';
12
+ import { join } from 'node:path';
13
+
14
+ const root = process.cwd();
15
+ const args = process.argv.slice(2);
16
+ const config = join(root, 'build/server/wrangler.json');
17
+ const stamp = () => {
18
+ try {
19
+ return [config, join(root, 'build/server/index.js')].map((f) => statSync(f).mtimeMs).join(':');
20
+ } catch {
21
+ return '';
22
+ }
23
+ };
24
+ if (!existsSync(config)) {
25
+ console.error('sites-kit-react preview: no build/server/wrangler.json: run `pnpm build` first');
26
+ process.exit(1);
27
+ }
28
+
29
+ const wrangler = join(root, 'node_modules/.bin/wrangler');
30
+ const kill = () => {
31
+ try {
32
+ process.kill(-child.pid, 'SIGTERM');
33
+ } catch {
34
+ child.kill('SIGTERM');
35
+ }
36
+ };
37
+ let child;
38
+ let last = stamp();
39
+ let stopping = false;
40
+ const start = () => {
41
+ // Its own process group: a restart or a stop takes wrangler and workerd down with it.
42
+ child = spawn(wrangler, ['dev', '--config', 'build/server/wrangler.json', ...args], { stdio: 'inherit', cwd: root, detached: true });
43
+ child.on('exit', (code) => {
44
+ if (!stopping && !restarting) process.exit(code ?? 0);
45
+ });
46
+ };
47
+ let restarting = false;
48
+ let timer;
49
+ const check = () => {
50
+ const now = stamp();
51
+ if (!now || now === last) return;
52
+ // Wait for the build to finish writing (the server build comes last).
53
+ clearTimeout(timer);
54
+ timer = setTimeout(() => {
55
+ if (stamp() !== now) return check();
56
+ last = now;
57
+ console.log('\n[sites-kit-react preview] new build: restarting wrangler');
58
+ restarting = true;
59
+ child.once('exit', () => {
60
+ restarting = false;
61
+ start();
62
+ });
63
+ kill();
64
+ }, 800);
65
+ };
66
+ for (const f of [config, join(root, 'build/server/index.js')]) watchFile(f, { interval: 500 }, check);
67
+ const stop = () => {
68
+ stopping = true;
69
+ if (!child || child.exitCode != null) process.exit(0);
70
+ child.once('exit', () => process.exit(0));
71
+ kill();
72
+ setTimeout(() => process.exit(0), 3000).unref();
73
+ };
74
+ process.on('SIGINT', stop);
75
+ process.on('SIGTERM', stop);
76
+ process.on('SIGHUP', stop);
77
+ start();
package/vite.d.mts ADDED
@@ -0,0 +1,2 @@
1
+ import type { Plugin } from 'vite';
2
+ export default function sitesKit(opts?: { client?: string; inlineCss?: boolean }): Plugin;
package/vite.mjs ADDED
@@ -0,0 +1,180 @@
1
+ /**
2
+ * The kit's Vite plugin for a React Router site: everything the site's
3
+ * vite.config.ts needs from the kit, so it stays three plugins.
4
+ *
5
+ * import { reactRouter } from '@react-router/dev/vite';
6
+ * import { cloudflare } from '@cloudflare/vite-plugin';
7
+ * import sitesKit from '@realadvisor/sites-kit-react/vite';
8
+ * export default defineConfig({
9
+ * plugins: [cloudflare({ viteEnvironment: { name: 'ssr' } }), reactRouter(), sitesKit()],
10
+ * });
11
+ *
12
+ * It adds:
13
+ * - `virtual:sites-kit/site` (site.json with its defaults), the module the
14
+ * Astro kit's lib/ (format, i18n, legal, search, developments) reads: the
15
+ * React kit reuses those files as they are;
16
+ * - `virtual:sites-kit-react/client`: the URL of the site's one browser
17
+ * script (`app/client.ts`: the kit's behaviours and the site's islands),
18
+ * bundled as its own chunk; `<KitScripts>` loads it (never inline);
19
+ * - `inlineCss: true` (opt-in): the Worker inlines the page's stylesheets
20
+ * (`<style>`, allowed by the kit's style-src) instead of linking them, so
21
+ * the first paint waits for no CSS request (`virtual:sites-kit-react/css`);
22
+ * - the kit's ~300-byte preload helper in place of Vite's ~2 KB one (PRELOAD);
23
+ * - `import '…/styles/kit.css'` from JS = one import per part (KIT_CSS):
24
+ * the kit's CSS sits exactly where root.tsx imports it, as in Astro;
25
+ * - build/client/_headers: security headers for static files (no nonce:
26
+ * static files have no inline script);
27
+ * - the settings the CSP and the CRM preview depend on (no inlined JS, every
28
+ * host for the sandbox preview, the kit sources compiled like the site's).
29
+ *
30
+ * Plain JS on purpose: vite.config loads it natively.
31
+ */
32
+ import { existsSync, writeFileSync } from 'node:fs';
33
+ import { join, relative, resolve } from 'node:path';
34
+ import { fileURLToPath } from 'node:url';
35
+ import { readSiteConfig, SITE_CONFIG_FILE } from '@realadvisor/sites-kit-core/site-config';
36
+ import { securityHeaders } from '@realadvisor/sites-kit-core/security';
37
+
38
+ const SITE_ID = 'virtual:sites-kit/site';
39
+ const CLIENT_ID = 'virtual:sites-kit-react/client';
40
+ const CSS_ID = 'virtual:sites-kit-react/css';
41
+ const resolved = (id) => `\0${id}`;
42
+ const KIT_PACKAGES = ['@realadvisor/sites-kit-core', '@realadvisor/sites-kit-react', '@realadvisor/sites-sdk'];
43
+
44
+ /**
45
+ * PRELOAD: Vite wraps every dynamic `import()` of the browser build in its
46
+ * preload helper (~2 KB: link bookkeeping, CSP nonce lookup, error events),
47
+ * and `build.modulePreload: false` does not remove it. Astro pages without a
48
+ * kit part ship ~0 KB; so the kit loads this one under Vite's own virtual
49
+ * module id instead: the same contract (the chunk's CSS loads before it runs,
50
+ * its JS imports preload in parallel), about 350 bytes.
51
+ */
52
+ const PRELOAD_ID = '\0vite/preload-helper.js';
53
+
54
+ /**
55
+ * KIT_CSS: `import '@realadvisor/sites-kit-react/styles/kit.css'` from a JS
56
+ * module becomes one JS import per part (the Astro kit's form.css, then
57
+ * search, pager, map, consent): no `@import` for the CSS bundler to hoist,
58
+ * so the kit's rules sit exactly where root.tsx imports kit.css (Astro: where
59
+ * the layout imports ConsentBanner), and a site that imports a part itself
60
+ * gets it once.
61
+ */
62
+ const KIT_CSS_ID = '\0sites-kit-react/kit.css.js';
63
+ const KIT_DIR = fileURLToPath(new URL('.', import.meta.url));
64
+ const KIT_PARTS = ['search', 'pager', 'map', 'consent'].map((p) => join(KIT_DIR, 'styles', `${p}.css`));
65
+ const isKitCss = (id) => id === '@realadvisor/sites-kit-react/styles/kit.css' || resolve(id) === join(KIT_DIR, 'styles', 'kit.css');
66
+ const preloadHelper = (base) => `const base = ${JSON.stringify(base)};
67
+ export const __vitePreload = (load, deps) => {
68
+ if (!deps || !deps.length) return load();
69
+ return Promise.all(deps.map((dep) => {
70
+ const href = base + dep;
71
+ const css = dep.endsWith('.css');
72
+ if (document.querySelector('link[href="' + href + '"]')) return;
73
+ const link = document.createElement('link');
74
+ link.rel = css ? 'stylesheet' : 'modulepreload';
75
+ link.href = href;
76
+ document.head.append(link);
77
+ if (css) return new Promise((done) => { link.onload = link.onerror = done; });
78
+ })).then(load);
79
+ };
80
+ `;
81
+
82
+ /**
83
+ * @param {{ client?: string; inlineCss?: boolean }} [opts] `client`: the site's browser entry, relative to the root (default `app/client.ts`).
84
+ * `inlineCss`: inline every stylesheet of a page into it (default false).
85
+ * @returns {import('vite').Plugin}
86
+ */
87
+ export default function sitesKit(opts = {}) {
88
+ const clientEntry = opts.client ?? 'app/client.ts';
89
+ let root = process.cwd();
90
+ let base = '/';
91
+ let command = 'serve';
92
+ /** The built client entry, set by the client build (React Router builds it before the server). */
93
+ const built = { src: '', preload: /** @type {string[]} */ ([]) };
94
+ /** Built stylesheets by URL (inlineCss). */
95
+ const css = /** @type {Record<string, string>} */ ({});
96
+ let clientId = '';
97
+
98
+ return {
99
+ name: 'sites-kit-react',
100
+ // Before Vite's resolver: kit.css (KIT_CSS) and the preload helper (PRELOAD) are the kit's.
101
+ enforce: 'pre',
102
+ config() {
103
+ return {
104
+ // Sandbox previews are served on *.vercel.run; host: every interface.
105
+ server: { host: true, allowedHosts: true },
106
+ // The kits ship TypeScript sources: Vite compiles them like the site's own.
107
+ ssr: { noExternal: KIT_PACKAGES },
108
+ optimizeDeps: { exclude: KIT_PACKAGES },
109
+ build: {
110
+ // Never inline a script as a data: URL: every script is a file of this site ('self').
111
+ assetsInlineLimit: (file) => (file.endsWith('.js') || file.endsWith('.ts') ? false : undefined),
112
+ },
113
+ };
114
+ },
115
+ configResolved(c) {
116
+ root = c.root;
117
+ base = c.base || '/';
118
+ command = c.command;
119
+ // Fails the build early on a broken site.json, naming the field.
120
+ readSiteConfig(root);
121
+ },
122
+ configureServer(server) {
123
+ server.watcher.add(join(root, SITE_CONFIG_FILE));
124
+ server.watcher.on('change', (f) => {
125
+ if (resolve(f) === resolve(root, SITE_CONFIG_FILE)) server.restart();
126
+ });
127
+ },
128
+ async buildStart() {
129
+ if (command !== 'build' || this.environment?.name !== 'client') return;
130
+ const file = resolve(root, clientEntry);
131
+ if (!existsSync(file)) return;
132
+ clientId = file;
133
+ this.emitFile({ type: 'chunk', id: file, name: 'site' });
134
+ },
135
+ resolveId(id, importer) {
136
+ if (id === SITE_ID || id === CLIENT_ID || id === CSS_ID) return resolved(id);
137
+ // From JS only: an @import inside a stylesheet stays plain CSS.
138
+ if (importer && !/\.(css|scss|sass|less)(\?|$)/.test(importer) && isKitCss(id.split('?')[0])) return KIT_CSS_ID;
139
+ return undefined;
140
+ },
141
+ async load(id) {
142
+ if (id === KIT_CSS_ID) {
143
+ const form = await this.resolve('@realadvisor/sites-kit-core/styles/form.css', join(KIT_DIR, 'components', 'EnquiryForm.tsx'));
144
+ return [form?.id ?? '@realadvisor/sites-kit-core/styles/form.css', ...KIT_PARTS].map((f) => `import ${JSON.stringify(f)};`).join('\n');
145
+ }
146
+ // The browser build: the kit's small preload helper instead of Vite's (see PRELOAD).
147
+ if (id === PRELOAD_ID && command === 'build' && this.environment?.config.consumer === 'client' && base.startsWith('/')) return preloadHelper(base);
148
+ if (id === resolved(SITE_ID)) return `export default ${JSON.stringify(readSiteConfig(root))};`;
149
+ if (id === resolved(CSS_ID)) return `export default ${JSON.stringify(command === 'build' && opts.inlineCss ? css : {})};`;
150
+ if (id === resolved(CLIENT_ID)) {
151
+ if (command === 'serve') {
152
+ const file = resolve(root, clientEntry);
153
+ const src = existsSync(file) ? `${base}${relative(root, file).split('\\').join('/')}` : '';
154
+ return `export default ${JSON.stringify({ src, preload: [] })};`;
155
+ }
156
+ return `export default ${JSON.stringify(built)};`;
157
+ }
158
+ return undefined;
159
+ },
160
+ generateBundle(_out, bundle) {
161
+ if (this.environment?.name !== 'client') return;
162
+ if (opts.inlineCss) {
163
+ for (const f of Object.values(bundle)) {
164
+ if (f.type === 'asset' && f.fileName.endsWith('.css')) css[`${base}${f.fileName}`] = String(typeof f.source === 'string' ? f.source : new TextDecoder().decode(f.source));
165
+ }
166
+ }
167
+ if (!clientId) return;
168
+ const chunk = Object.values(bundle).find((c) => c.type === 'chunk' && c.facadeModuleId === clientId);
169
+ if (!chunk || chunk.type !== 'chunk') return;
170
+ built.src = `${base}${chunk.fileName}`;
171
+ built.preload = chunk.imports.map((f) => `${base}${f}`);
172
+ },
173
+ writeBundle(out) {
174
+ if (this.environment?.name !== 'client' || !out.dir) return;
175
+ // Static files (assets, favicon): preview-safe frame-ancestors, as the Astro kit writes them.
176
+ const lines = Object.entries(securityHeaders(true)).map(([k, v]) => ` ${k}: ${v}`);
177
+ writeFileSync(join(out.dir, '_headers'), `/*\n${lines.join('\n')}\n strict-transport-security: max-age=31536000; includeSubDomains\n`);
178
+ },
179
+ };
180
+ }