@realadvisor-sites/kit-react 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +210 -2
- package/bin/sites-kit-react.mjs +26 -0
- package/client/index.ts +21 -0
- package/client/islands.ts +33 -0
- package/components/ConsentBanner.tsx +25 -0
- package/components/Document.tsx +170 -0
- package/components/EnquiryForm.tsx +107 -0
- package/components/Island.tsx +39 -0
- package/components/LanguageSwitch.tsx +24 -0
- package/components/LegalContent.tsx +30 -0
- package/components/ListingsMap.tsx +76 -0
- package/components/ListingsPager.tsx +25 -0
- package/components/ListingsSearch.tsx +294 -0
- package/components/RaImage.tsx +107 -0
- package/components/SafeHtml.tsx +30 -0
- package/components/form/Button.tsx +22 -0
- package/components/form/Combobox.tsx +34 -0
- package/components/form/Input.tsx +24 -0
- package/components/form/Select.tsx +30 -0
- package/components/index.ts +15 -0
- package/env.d.ts +36 -0
- package/lib/image.ts +36 -0
- package/lib/records.ts +17 -0
- package/lib/search.ts +37 -0
- package/package.json +63 -4
- package/server/data.ts +82 -0
- package/server/enquiry.ts +9 -0
- package/server/entry.server.tsx +54 -0
- package/server/fixture-client.ts +2 -0
- package/server/kit.ts +52 -0
- package/server/security.ts +32 -0
- package/server/seo.ts +39 -0
- package/server/worker.ts +146 -0
- package/styles/consent.css +6 -0
- package/styles/kit.css +21 -0
- package/styles/map.css +58 -0
- package/styles/pager.css +14 -0
- package/styles/search.css +162 -0
- package/tools/check-deploy.mjs +280 -0
- package/tools/preview.mjs +77 -0
- package/vite.d.mts +2 -0
- package/vite.mjs +180 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** Button or link styled as a button (port of form/Button.astro). `data-*` hooks pass through. */
|
|
2
|
+
import type { ReactNode } from 'react';
|
|
3
|
+
|
|
4
|
+
export type ButtonProps = {
|
|
5
|
+
href?: string;
|
|
6
|
+
type?: 'submit' | 'button' | 'reset';
|
|
7
|
+
variant?: 'primary' | 'secondary' | 'on-photo';
|
|
8
|
+
disabled?: boolean;
|
|
9
|
+
className?: string;
|
|
10
|
+
children?: ReactNode;
|
|
11
|
+
[data: `data-${string}`]: string | boolean | undefined;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export function Button({ href, type = 'submit', variant = 'primary', disabled, className, children, ...data }: ButtonProps) {
|
|
15
|
+
const cls = ['btn', variant === 'secondary' && 'btn--secondary', variant === 'on-photo' && 'btn--on-photo', className].filter(Boolean).join(' ');
|
|
16
|
+
const attrs = Object.fromEntries(Object.entries(data).map(([k, v]) => [k, v === true ? '' : v]));
|
|
17
|
+
return href ? (
|
|
18
|
+
<a href={href} className={cls} {...attrs}>{children}</a>
|
|
19
|
+
) : (
|
|
20
|
+
<button type={type} className={cls} disabled={disabled} {...attrs}>{children}</button>
|
|
21
|
+
);
|
|
22
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Searchable select for long lists (port of form/Combobox.astro): a native
|
|
3
|
+
* select (works without JS), upgraded by @realadvisor/sites-kit/client/combobox.
|
|
4
|
+
*/
|
|
5
|
+
import type { Option } from './Select';
|
|
6
|
+
|
|
7
|
+
export type ComboboxProps = {
|
|
8
|
+
label: string;
|
|
9
|
+
name: string;
|
|
10
|
+
options: Option[];
|
|
11
|
+
value?: string | null;
|
|
12
|
+
placeholder?: string;
|
|
13
|
+
hideLabel?: boolean;
|
|
14
|
+
noResults?: string;
|
|
15
|
+
id?: string;
|
|
16
|
+
className?: string;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export function Combobox({ label, name, options, value, placeholder = '', hideLabel, noResults = '–', id, className }: ComboboxProps) {
|
|
20
|
+
const fieldId = id ?? `f-${name}`;
|
|
21
|
+
return (
|
|
22
|
+
<div className={['field', className].filter(Boolean).join(' ')}>
|
|
23
|
+
<label htmlFor={fieldId} className={hideLabel ? 'field-label sr-only' : 'field-label'}>{label}</label>
|
|
24
|
+
<div className="combobox" data-combobox="" data-no-results={noResults}>
|
|
25
|
+
<span className="select">
|
|
26
|
+
<select id={fieldId} name={name} className="control" defaultValue={value ?? ''}>
|
|
27
|
+
<option value="">{placeholder}</option>
|
|
28
|
+
{options.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
|
|
29
|
+
</select>
|
|
30
|
+
</span>
|
|
31
|
+
</div>
|
|
32
|
+
</div>
|
|
33
|
+
);
|
|
34
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** Text-like input with its label (port of form/Input.astro). `multiline` for a textarea. */
|
|
2
|
+
import type { InputHTMLAttributes } from 'react';
|
|
3
|
+
|
|
4
|
+
export type InputProps = Omit<InputHTMLAttributes<HTMLInputElement>, 'className'> & {
|
|
5
|
+
label: string;
|
|
6
|
+
name: string;
|
|
7
|
+
hideLabel?: boolean;
|
|
8
|
+
multiline?: boolean;
|
|
9
|
+
className?: string;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
export function Input({ label, hideLabel, multiline, className, id, type = 'text', value, ...rest }: InputProps) {
|
|
13
|
+
const fieldId = id ?? `f-${rest.name}`;
|
|
14
|
+
return (
|
|
15
|
+
<div className={['field', className].filter(Boolean).join(' ')}>
|
|
16
|
+
<label htmlFor={fieldId} className={hideLabel ? 'field-label sr-only' : 'field-label'}>{label}</label>
|
|
17
|
+
{multiline ? (
|
|
18
|
+
<textarea id={fieldId} className="control" defaultValue={value as string | undefined} {...(rest as object)} />
|
|
19
|
+
) : (
|
|
20
|
+
<input id={fieldId} className="control" type={type} defaultValue={value as string | undefined} {...rest} />
|
|
21
|
+
)}
|
|
22
|
+
</div>
|
|
23
|
+
);
|
|
24
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/** Styled native select (port of form/Select.astro). `placeholder` adds a first option "" (no filter). */
|
|
2
|
+
export type Option = { value: string; label: string };
|
|
3
|
+
export type SelectProps = {
|
|
4
|
+
label: string;
|
|
5
|
+
name: string;
|
|
6
|
+
options: Option[];
|
|
7
|
+
value?: string | null;
|
|
8
|
+
placeholder?: string;
|
|
9
|
+
hideLabel?: boolean;
|
|
10
|
+
disabled?: boolean;
|
|
11
|
+
required?: boolean;
|
|
12
|
+
'aria-describedby'?: string;
|
|
13
|
+
id?: string;
|
|
14
|
+
className?: string;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export function Select({ label, name, options, value, placeholder, hideLabel, disabled, required, id, className, 'aria-describedby': describedBy }: SelectProps) {
|
|
18
|
+
const fieldId = id ?? `f-${name}`;
|
|
19
|
+
return (
|
|
20
|
+
<div className={['field', className].filter(Boolean).join(' ')}>
|
|
21
|
+
<label htmlFor={fieldId} className={hideLabel ? 'field-label sr-only' : 'field-label'}>{label}</label>
|
|
22
|
+
<span className="select">
|
|
23
|
+
<select id={fieldId} name={name} className="control" disabled={disabled} required={required} aria-describedby={describedBy} defaultValue={value ?? ''}>
|
|
24
|
+
{placeholder !== undefined && <option value="">{placeholder}</option>}
|
|
25
|
+
{options.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
|
|
26
|
+
</select>
|
|
27
|
+
</span>
|
|
28
|
+
</div>
|
|
29
|
+
);
|
|
30
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export { NonceContext, useNonce, KitProvider, useKit, useHydrate, usePageLocale, useErrorStatus, useGone, KitScripts, JsonLd, Seo, type KitData, type SeoProps } from './Document';
|
|
2
|
+
export { RaImage, type RaImageProps } from './RaImage';
|
|
3
|
+
export { EnquiryForm, type EnquiryFormProps } from './EnquiryForm';
|
|
4
|
+
export { LegalContent } from './LegalContent';
|
|
5
|
+
export { ConsentBanner } from './ConsentBanner';
|
|
6
|
+
export { ListingsSearch, type ListingsSearchProps } from './ListingsSearch';
|
|
7
|
+
export { ListingsMap } from './ListingsMap';
|
|
8
|
+
export { ListingsPager } from './ListingsPager';
|
|
9
|
+
export { Island } from './Island';
|
|
10
|
+
export { LanguageSwitch } from './LanguageSwitch';
|
|
11
|
+
export { Input } from './form/Input';
|
|
12
|
+
export { Select, type Option } from './form/Select';
|
|
13
|
+
export { Combobox } from './form/Combobox';
|
|
14
|
+
export { Button } from './form/Button';
|
|
15
|
+
export { SafeHtml, sanitized, type SanitizedHtml } from './SafeHtml';
|
package/env.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Types of the kit's virtual modules and plain-JS kit files. A site's
|
|
3
|
+
* tsconfig includes it: "include": ["node_modules/@realadvisor/sites-kit-react/env.d.ts", ...].
|
|
4
|
+
*/
|
|
5
|
+
declare module 'virtual:sites-kit/site' {
|
|
6
|
+
const site: import('@realadvisor/sites-kit/site-config').SiteConfig;
|
|
7
|
+
export default site;
|
|
8
|
+
}
|
|
9
|
+
declare module 'virtual:sites-kit-react/client' {
|
|
10
|
+
/** The site's bundled browser script and its static imports. */
|
|
11
|
+
const client: { src: string; preload: string[] };
|
|
12
|
+
export default client;
|
|
13
|
+
}
|
|
14
|
+
declare module 'virtual:sites-kit-react/css' {
|
|
15
|
+
/** Built stylesheets by URL when sitesKit({ inlineCss: true }), else empty. */
|
|
16
|
+
const css: Record<string, string>;
|
|
17
|
+
export default css;
|
|
18
|
+
}
|
|
19
|
+
interface ImportMetaEnv {
|
|
20
|
+
readonly SITE_URL?: string;
|
|
21
|
+
}
|
|
22
|
+
// The Astro kit's files the React kit reads also import these (types only here).
|
|
23
|
+
declare module 'astro:env/server' {
|
|
24
|
+
export const SITES_API_URL: string | undefined;
|
|
25
|
+
export const SITES_API_KEY: string | undefined;
|
|
26
|
+
export const SITES_FIXTURE: string | undefined;
|
|
27
|
+
}
|
|
28
|
+
declare module 'virtual:sites-kit/fixtures' {
|
|
29
|
+
const fixtures: Record<string, { default: import('@realadvisor/sites-kit').SiteFixture }>;
|
|
30
|
+
export default fixtures;
|
|
31
|
+
}
|
|
32
|
+
declare module '@realadvisor/sites-kit/security' {
|
|
33
|
+
export const ALLOWED_HOSTS: { img: string[]; script: string[]; connect: string[]; frame: string[] };
|
|
34
|
+
export function csp(preview: boolean): string;
|
|
35
|
+
export function securityHeaders(preview: boolean): Record<string, string>;
|
|
36
|
+
}
|
package/lib/image.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Photo URLs: the Astro kit's `img()` / `srcset()` (imgproxy on
|
|
3
|
+
* img.realadvisor.ch, Google profile photos, other hosts unchanged) plus a
|
|
4
|
+
* crop of the original (imgproxy `c:` step), which sites had to add.
|
|
5
|
+
*/
|
|
6
|
+
import { img, srcset, type ImgOptions } from '@realadvisor/sites-kit/image';
|
|
7
|
+
|
|
8
|
+
export { img, srcset, type ImgOptions };
|
|
9
|
+
|
|
10
|
+
/** A part of the original, in fractions: [left, top, width, height] (0 = full size). */
|
|
11
|
+
export type Crop = { left: number; top: number; width: number; height: number };
|
|
12
|
+
|
|
13
|
+
const IMGPROXY = 'https://img.realadvisor.ch/';
|
|
14
|
+
|
|
15
|
+
/** `img()` with an optional crop of the original before the resize. */
|
|
16
|
+
export function imgUrl(url: string | null | undefined, o: ImgOptions & { crop?: Crop }): string {
|
|
17
|
+
const out = img(url, o);
|
|
18
|
+
if (!o.crop || !out.startsWith(IMGPROXY)) return out;
|
|
19
|
+
const c = `c:${o.crop.width}:${o.crop.height}:nowe:${o.crop.left}:${o.crop.top}`;
|
|
20
|
+
return out.replace('/rs:', `/${c}/rs:`);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** srcset with an optional crop: `ratio` = width / height of the box (fill), omitted = the photo's own ratio. */
|
|
24
|
+
export function srcsetUrl(
|
|
25
|
+
url: string | null | undefined,
|
|
26
|
+
widths: number[],
|
|
27
|
+
ratio: number | undefined,
|
|
28
|
+
opts: Pick<ImgOptions, 'format' | 'quality'> & { crop?: Crop } = {},
|
|
29
|
+
): string {
|
|
30
|
+
if (!url) return '';
|
|
31
|
+
if (!opts.crop) return srcset(url, widths, ratio, opts);
|
|
32
|
+
if (img(url, { w: 1 }) === url) return '';
|
|
33
|
+
return widths
|
|
34
|
+
.map((w) => `${imgUrl(url, { w, h: ratio ? Math.round(w / ratio) : 0, fit: ratio ? 'fill' : 'fit', ...opts })} ${w}w`)
|
|
35
|
+
.join(', ');
|
|
36
|
+
}
|
package/lib/records.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helpers over SDK records (`@realadvisor/sites-sdk`) for the React kit's
|
|
3
|
+
* pages: the agency of an organisation and its office, the price and the
|
|
4
|
+
* reference as the Astro kit words them.
|
|
5
|
+
*/
|
|
6
|
+
import type { Listing } from '@realadvisor/sites-sdk/types';
|
|
7
|
+
import { formatPrice } from '@realadvisor/sites-kit/format';
|
|
8
|
+
|
|
9
|
+
export { agencyOf } from '@realadvisor/sites-kit/agency';
|
|
10
|
+
export { listingRef } from '@realadvisor/sites-kit/seo';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* `CHF 2'850'000`, `CHF 4'200 / Monat`, "Preis auf Anfrage" (DESIGN.md 5), in
|
|
14
|
+
* the listing's currency and the page language (`locale`, default the site's).
|
|
15
|
+
*/
|
|
16
|
+
export const price = (l: Pick<Listing, 'price' | 'price_on_request' | 'offer_type'> & { currency?: string | null }, locale?: string) =>
|
|
17
|
+
formatPrice(l, { locale });
|
package/lib/search.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Astro kit's listing search (lib/search.ts: parseSearch, runSearch,
|
|
3
|
+
* searchHref, the same URLs and facets) over SDK records.
|
|
4
|
+
*
|
|
5
|
+
* const params = parseSearch(url.searchParams);
|
|
6
|
+
* const result = searchListings(await sites.allListings({ offer_type: 'buy', status: 'available' }), params, { url });
|
|
7
|
+
* <ListingsSearch result={result}>{(l, i) => <ListingCard listing={l} />}</ListingsSearch>
|
|
8
|
+
*
|
|
9
|
+
* Language: `locale`, else the locale of `url` (the page's path, site.json
|
|
10
|
+
* `locales`), else the site's. Currency: the price filter and its steps work
|
|
11
|
+
* in one currency (`currency`, else the one most of the pool is in); amounts
|
|
12
|
+
* are never converted, so a listing priced in another currency drops out of
|
|
13
|
+
* a price filter (a CHF + EUR agency: filter in one, or hide the price filter).
|
|
14
|
+
*/
|
|
15
|
+
import type { Listing } from '@realadvisor/sites-sdk/types';
|
|
16
|
+
import { poolCurrency, runSearch, type SearchOptions, type SearchParams, type SearchResult } from '@realadvisor/sites-kit/search';
|
|
17
|
+
import { LOCALE } from '@realadvisor/sites-kit/format';
|
|
18
|
+
import { localeOfPath } from '@realadvisor/sites-kit/i18n';
|
|
19
|
+
|
|
20
|
+
export { parseSearch, searchHref, mapView, type SearchParams } from '@realadvisor/sites-kit/search';
|
|
21
|
+
|
|
22
|
+
/** The kit's SearchResult and the price filter's currency. */
|
|
23
|
+
export type ListingsResult = SearchResult & { currency?: string };
|
|
24
|
+
|
|
25
|
+
export type ListingsSearchOptions = SearchOptions & {
|
|
26
|
+
/** The page (request URL or pathname): its locale when `locale` is not given. */
|
|
27
|
+
url?: Request | URL | string;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const pathOf = (u: Request | URL | string) => (typeof u === 'string' ? new URL(u, 'http://x').pathname : u instanceof URL ? u.pathname : new URL(u.url).pathname);
|
|
31
|
+
|
|
32
|
+
export function searchListings(pool: Listing[], params: SearchParams, opts: ListingsSearchOptions = {}): ListingsResult {
|
|
33
|
+
const { url, ...rest } = opts;
|
|
34
|
+
const currency = rest.currency ?? poolCurrency(pool);
|
|
35
|
+
const locale = rest.locale ?? (url ? localeOfPath(pathOf(url)) : LOCALE);
|
|
36
|
+
return { ...runSearch(pool, params, { ...rest, locale, currency }), currency };
|
|
37
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,65 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@realadvisor-sites/kit-react",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "The React Router (framework mode, SSR on Cloudflare Workers) version of the RealAdvisor sites kit: Worker with a per-request CSP nonce, data through the SDK interface, images, legal, consent, enquiry, SEO, listings search and map, and the deploy check. Reuses @realadvisor/sites-kit for every rule, string and browser script it can.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/realadvisor/sites.git",
|
|
9
|
+
"directory": "kit-react"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/realadvisor/sites/tree/main/kit-react#readme",
|
|
12
|
+
"files": [
|
|
13
|
+
"*.mjs",
|
|
14
|
+
"*.mts",
|
|
15
|
+
"env.d.ts",
|
|
16
|
+
"README.md",
|
|
17
|
+
"bin",
|
|
18
|
+
"client",
|
|
19
|
+
"components",
|
|
20
|
+
"lib",
|
|
21
|
+
"server",
|
|
22
|
+
"styles",
|
|
23
|
+
"tools",
|
|
24
|
+
"LICENSE"
|
|
25
|
+
],
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public",
|
|
28
|
+
"provenance": true
|
|
29
|
+
},
|
|
30
|
+
"type": "module",
|
|
31
|
+
"exports": {
|
|
32
|
+
"./vite": {
|
|
33
|
+
"types": "./vite.d.mts",
|
|
34
|
+
"default": "./vite.mjs"
|
|
35
|
+
},
|
|
36
|
+
"./worker": "./server/worker.ts",
|
|
37
|
+
"./entry.server": "./server/entry.server.tsx",
|
|
38
|
+
"./server/*": "./server/*.ts",
|
|
39
|
+
"./components": "./components/index.ts",
|
|
40
|
+
"./components/*": "./components/*.tsx",
|
|
41
|
+
"./client": "./client/index.ts",
|
|
42
|
+
"./client/*": "./client/*.ts",
|
|
43
|
+
"./styles/*": "./styles/*",
|
|
44
|
+
"./tools/*": "./tools/*",
|
|
45
|
+
"./package.json": "./package.json",
|
|
46
|
+
"./lib/*": "./lib/*.ts",
|
|
47
|
+
"./env.d.ts": "./env.d.ts"
|
|
48
|
+
},
|
|
49
|
+
"bin": {
|
|
50
|
+
"sites-kit-react": "./bin/sites-kit-react.mjs"
|
|
51
|
+
},
|
|
52
|
+
"peerDependencies": {
|
|
53
|
+
"@realadvisor/sites-kit": "^0.3.0",
|
|
54
|
+
"@realadvisor/sites-sdk": "^0.3.0",
|
|
55
|
+
"react": "^19.0.0",
|
|
56
|
+
"react-dom": "^19.0.0",
|
|
57
|
+
"react-router": "^7.18.0",
|
|
58
|
+
"playwright": "^1.64.1"
|
|
59
|
+
},
|
|
60
|
+
"peerDependenciesMeta": {
|
|
61
|
+
"playwright": {
|
|
62
|
+
"optional": true
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
package/server/data.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The site's data client: one `SitesClient` (the `@realadvisor/sites-sdk`
|
|
3
|
+
* interface) for every page, whatever the data source.
|
|
4
|
+
*
|
|
5
|
+
* // app/lib/data.server.ts
|
|
6
|
+
* import fixture from '../data/fixture.json';
|
|
7
|
+
* export const sites = siteClient({ fixture });
|
|
8
|
+
*
|
|
9
|
+
* - SITES_API_URL + SITES_API_KEY set (publish, CRM preview, .dev.vars):
|
|
10
|
+
* the SDK's `createClient`, live data (the API caches 60 s).
|
|
11
|
+
* - Otherwise: the fixture (`pnpm dev`, the build, check:deploy), with the
|
|
12
|
+
* same filters as the API, so a page runs unchanged on both.
|
|
13
|
+
*
|
|
14
|
+
* On a site with more than one locale, listings and developments come in the
|
|
15
|
+
* page's language (`pageLocale(request)`, set by the worker for each request)
|
|
16
|
+
* when the CRM has their texts in it; `text_locale` then says so.
|
|
17
|
+
*
|
|
18
|
+
* Server only: never import it from app/client.ts or an island.
|
|
19
|
+
*/
|
|
20
|
+
import { createClient, createFixtureClient } from '@realadvisor/sites-sdk';
|
|
21
|
+
import type { Portals, SitesClient } from '@realadvisor/sites-sdk/types';
|
|
22
|
+
import { previewApi } from '@realadvisor/sites-kit/env';
|
|
23
|
+
import { withTextLocale } from '@realadvisor/sites-kit/page-locale';
|
|
24
|
+
import type { Fixture } from './fixture-client';
|
|
25
|
+
|
|
26
|
+
export { createFixtureClient, fixtureOnly, type Fixture } from './fixture-client';
|
|
27
|
+
|
|
28
|
+
/** One live client per access and portals, so each keeps its Turnstile key. */
|
|
29
|
+
const clients = new Map<string, SitesClient>();
|
|
30
|
+
|
|
31
|
+
/** True when the Worker has data access (SITES_API_URL + SITES_API_KEY). */
|
|
32
|
+
export function hasLiveData(): boolean {
|
|
33
|
+
const { url, token } = previewApi();
|
|
34
|
+
return !!(url && token);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The SDK client on live data, or null in fixture mode. The enquiry action sends through it. Without portals: the site's own. */
|
|
38
|
+
export function liveClient(portals?: Portals): SitesClient | null {
|
|
39
|
+
const { url, token } = previewApi();
|
|
40
|
+
if (!url || !token) return null;
|
|
41
|
+
// The SDK reads process.env; a Worker's env reaches it through setRuntimeEnv + this url/key.
|
|
42
|
+
const key = `${url}\0${token}\0${JSON.stringify(portals ?? null)}`;
|
|
43
|
+
let live = clients.get(key);
|
|
44
|
+
if (!live) {
|
|
45
|
+
if (clients.size > 8) clients.clear();
|
|
46
|
+
live = createClient({ portals, url, key: token });
|
|
47
|
+
clients.set(key, live);
|
|
48
|
+
}
|
|
49
|
+
return live;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export type SiteClientOptions = {
|
|
53
|
+
/** The site's fixture (src/data/fixture.json): data in dev and build, the portals live. */
|
|
54
|
+
fixture: Fixture;
|
|
55
|
+
/** Portals by name; default the fixture's (`main` is the enquiry portal). */
|
|
56
|
+
portals?: Portals;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
export type SiteClient = SitesClient & {
|
|
60
|
+
/** Live SDK client or null (fixture mode). */
|
|
61
|
+
readonly live: () => SitesClient | null;
|
|
62
|
+
readonly portals: Portals;
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
/** One SitesClient that reads live data when the Worker has access, else the fixture. */
|
|
66
|
+
export function siteClient({ fixture, portals = fixture.portals }: SiteClientOptions): SiteClient {
|
|
67
|
+
const fx = createFixtureClient(fixture);
|
|
68
|
+
const pick = () => liveClient(portals) ?? fx;
|
|
69
|
+
return {
|
|
70
|
+
portals,
|
|
71
|
+
live: () => liveClient(portals),
|
|
72
|
+
organisation: () => pick().organisation(),
|
|
73
|
+
teams: () => pick().teams(),
|
|
74
|
+
agents: (q) => pick().agents(q),
|
|
75
|
+
listings: (q) => pick().listings(withTextLocale(q)),
|
|
76
|
+
allListings: (q) => pick().allListings(withTextLocale(q)),
|
|
77
|
+
listing: (s, q) => pick().listing(s, withTextLocale(q)),
|
|
78
|
+
developments: (q) => pick().developments(withTextLocale(q)),
|
|
79
|
+
development: (s, q) => pick().development(s, withTextLocale(q)),
|
|
80
|
+
turnstileSiteKey: () => pick().turnstileSiteKey(),
|
|
81
|
+
};
|
|
82
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The enquiry endpoint behind <EnquiryForm> (the Astro kit's, lib/enquiry.ts):
|
|
3
|
+
* app/routes/api.enquiry.ts is
|
|
4
|
+
*
|
|
5
|
+
* import { enquiryAction } from '@realadvisor/sites-kit-react/server/enquiry';
|
|
6
|
+
* import { sites } from '../lib/data.server';
|
|
7
|
+
* export const action = ({ request }: Route.ActionArgs) => enquiryAction(request, sites);
|
|
8
|
+
*/
|
|
9
|
+
export { enquiryAction, type EnquiryClient } from '@realadvisor/sites-kit/enquiry';
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The site's server entry: app/entry.server.tsx re-exports it.
|
|
3
|
+
*
|
|
4
|
+
* export { default, streamTimeout } from '@realadvisor/sites-kit-react/entry.server';
|
|
5
|
+
*
|
|
6
|
+
* Renders with the request nonce (from the Worker, `loadContext.nonce`):
|
|
7
|
+
* renderToReadableStream({ nonce }), <ServerRouter nonce> (its inline
|
|
8
|
+
* hydration data) and NonceContext for <KitScripts>, <JsonLd> and any
|
|
9
|
+
* inline script a page adds. Always waits for the whole page (allReady):
|
|
10
|
+
* the Worker answers complete pages only (a render error is a 500, never a
|
|
11
|
+
* cut 200), crawlers and Lighthouse see the final HTML.
|
|
12
|
+
*/
|
|
13
|
+
import type { AppLoadContext, EntryContext } from 'react-router';
|
|
14
|
+
import { ServerRouter } from 'react-router';
|
|
15
|
+
import { renderToReadableStream } from 'react-dom/server';
|
|
16
|
+
import { NonceContext } from '../components/Document';
|
|
17
|
+
|
|
18
|
+
export const streamTimeout = 8000;
|
|
19
|
+
|
|
20
|
+
export default async function handleRequest(
|
|
21
|
+
request: Request,
|
|
22
|
+
responseStatusCode: number,
|
|
23
|
+
responseHeaders: Headers,
|
|
24
|
+
routerContext: EntryContext,
|
|
25
|
+
loadContext: AppLoadContext,
|
|
26
|
+
) {
|
|
27
|
+
const nonce = (loadContext as { nonce?: string }).nonce;
|
|
28
|
+
let failed: unknown;
|
|
29
|
+
const controller = new AbortController();
|
|
30
|
+
const timer = setTimeout(() => controller.abort(), streamTimeout + 1000);
|
|
31
|
+
try {
|
|
32
|
+
const body = await renderToReadableStream(
|
|
33
|
+
<NonceContext.Provider value={nonce}>
|
|
34
|
+
<ServerRouter context={routerContext} url={request.url} nonce={nonce} />
|
|
35
|
+
</NonceContext.Provider>,
|
|
36
|
+
{
|
|
37
|
+
nonce,
|
|
38
|
+
signal: controller.signal,
|
|
39
|
+
onError(error: unknown) {
|
|
40
|
+
failed ??= error;
|
|
41
|
+
// Logged by the Worker's handler too; a shell error rejects below.
|
|
42
|
+
if (!controller.signal.aborted) console.error('[render]', error);
|
|
43
|
+
},
|
|
44
|
+
},
|
|
45
|
+
);
|
|
46
|
+
await body.allReady;
|
|
47
|
+
// An error inside a Suspense boundary still resolves allReady: the page is incomplete.
|
|
48
|
+
if (failed && responseStatusCode < 400) throw failed;
|
|
49
|
+
responseHeaders.set('content-type', 'text/html; charset=utf-8');
|
|
50
|
+
return new Response(body, { headers: responseHeaders, status: responseStatusCode });
|
|
51
|
+
} finally {
|
|
52
|
+
clearTimeout(timer);
|
|
53
|
+
}
|
|
54
|
+
}
|
package/server/kit.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Request-side kit settings for the root loader:
|
|
3
|
+
*
|
|
4
|
+
* export async function loader({ request }: Route.LoaderArgs) {
|
|
5
|
+
* return { kit: await kitData(), ... };
|
|
6
|
+
* }
|
|
7
|
+
*
|
|
8
|
+
* and `canonical(request)` for every page's <Seo>.
|
|
9
|
+
*/
|
|
10
|
+
import { analyticsId, siteMode } from '@realadvisor/sites-kit/env';
|
|
11
|
+
import { canonicalUrl } from '@realadvisor/sites-kit/seo';
|
|
12
|
+
import { localeOfPath } from '@realadvisor/sites-kit/i18n';
|
|
13
|
+
import { FIXTURE_TURNSTILE_SITE_KEY } from '@realadvisor/sites-sdk';
|
|
14
|
+
import { liveClient } from './data';
|
|
15
|
+
import type { KitData } from '../components/Document';
|
|
16
|
+
|
|
17
|
+
/** Public origin: SITE_URL (set at publish), else the placeholder the Astro kit uses. */
|
|
18
|
+
export function siteUrl(): string {
|
|
19
|
+
const proc = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process;
|
|
20
|
+
return proc?.env?.SITE_URL || import.meta.env.SITE_URL || 'https://example.realadvisor.site';
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Canonical URL of a request on the public origin (every active filter kept, utm & co dropped). */
|
|
24
|
+
export const canonical = (request: Request | URL | string) =>
|
|
25
|
+
canonicalUrl(new URL(typeof request === 'string' ? request : request instanceof URL ? request.href : request.url), siteUrl());
|
|
26
|
+
|
|
27
|
+
/** The locale of a request's path (site.json `locales`): what `usePageLocale()` gives the page. */
|
|
28
|
+
export const pageLocale = (request: Request | URL | string) =>
|
|
29
|
+
localeOfPath(new URL(typeof request === 'string' ? request : request instanceof URL ? request.href : request.url, 'http://x').pathname);
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Public Turnstile site key (the SDK's `turnstileSiteKey()`, kept 5 min).
|
|
33
|
+
* Fixture mode: the stand-in key (the form renders a widget that never loads
|
|
34
|
+
* Turnstile). `null`: no widget.
|
|
35
|
+
*/
|
|
36
|
+
export function turnstileSiteKey(): Promise<string | null> {
|
|
37
|
+
// The verification route needs no portal: the site's own client.
|
|
38
|
+
const live = liveClient();
|
|
39
|
+
return live ? live.turnstileSiteKey().catch(() => null) : Promise.resolve(FIXTURE_TURNSTILE_SITE_KEY);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The kit settings of this request (root loader: `{ kit: await kitData() }`). */
|
|
43
|
+
export async function kitData(): Promise<KitData> {
|
|
44
|
+
const mode = siteMode();
|
|
45
|
+
return {
|
|
46
|
+
mode,
|
|
47
|
+
analyticsId: analyticsId(),
|
|
48
|
+
// Preview sites never send: no widget there.
|
|
49
|
+
turnstileSiteKey: mode === 'preview' ? null : await turnstileSiteKey(),
|
|
50
|
+
siteUrl: siteUrl(),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Security headers of a React Router site: the Astro kit's, plus one
|
|
3
|
+
* per-request nonce in script-src (approved 2026-11-11 for React Router
|
|
4
|
+
* sites only: their hydration scripts are inline). Everything else is the
|
|
5
|
+
* kit's lib/security.mjs as it is: same hosts, same directives, no hash, no
|
|
6
|
+
* 'unsafe-inline' for scripts.
|
|
7
|
+
*/
|
|
8
|
+
import { securityHeaders } from '@realadvisor/sites-kit/security';
|
|
9
|
+
|
|
10
|
+
/** 128 random bits, base64: a new one for every HTML response. */
|
|
11
|
+
export function createNonce(): string {
|
|
12
|
+
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
|
13
|
+
let s = '';
|
|
14
|
+
for (const b of bytes) s += String.fromCharCode(b);
|
|
15
|
+
return btoa(s);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** base64 only: a nonce never carries a quote or a `;` into the header. */
|
|
19
|
+
const NONCE_RE = /^[A-Za-z0-9+/]{16,}={0,2}$/;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The kit's headers for this response. With `nonce`, script-src becomes
|
|
23
|
+
* `'self' 'nonce-…' <kit hosts>`: the only difference from an Astro site.
|
|
24
|
+
*/
|
|
25
|
+
export function siteHeaders(preview: boolean, nonce?: string): Record<string, string> {
|
|
26
|
+
const h = securityHeaders(preview);
|
|
27
|
+
if (!nonce) return h;
|
|
28
|
+
if (!NONCE_RE.test(nonce)) throw new Error('invalid CSP nonce');
|
|
29
|
+
const csp = h['content-security-policy']!.replace(/(^|; )script-src 'self'/, `$1script-src 'self' 'nonce-${nonce}'`);
|
|
30
|
+
if (!csp.includes(`'nonce-${nonce}'`)) throw new Error('kit CSP has no script-src to add the nonce to');
|
|
31
|
+
return { ...h, 'content-security-policy': csp };
|
|
32
|
+
}
|
package/server/seo.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* sitemap.xml and robots.txt resource routes.
|
|
3
|
+
*
|
|
4
|
+
* // app/routes/sitemap[.]xml.ts
|
|
5
|
+
* export const loader = async () => sitemap([...STATIC_PATHS, ...listings.map(listingUrl)]);
|
|
6
|
+
* // app/routes/robots[.]txt.ts
|
|
7
|
+
* export const loader = () => robots();
|
|
8
|
+
*
|
|
9
|
+
* Every path on the public origin (SITE_URL). Legal pages of every
|
|
10
|
+
* language: `legalPaths()`.
|
|
11
|
+
*/
|
|
12
|
+
import { LOCALES, legalPath, privacyPath } from '@realadvisor/sites-kit/i18n';
|
|
13
|
+
import { siteUrl } from './kit';
|
|
14
|
+
|
|
15
|
+
const esc = (s: string) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
16
|
+
|
|
17
|
+
/** /legal and /privacy of every language (/en/legal, ... on a multi-language site). */
|
|
18
|
+
export const legalPaths = () => LOCALES.flatMap((l) => [legalPath(l), privacyPath(l)]);
|
|
19
|
+
|
|
20
|
+
export function sitemap(paths: string[]): Response {
|
|
21
|
+
const base = siteUrl();
|
|
22
|
+
const unique = [...new Set(paths)];
|
|
23
|
+
const body = `<?xml version="1.0" encoding="UTF-8"?>
|
|
24
|
+
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
|
25
|
+
${unique.map((p) => ` <url><loc>${esc(new URL(p, base).href)}</loc></url>`).join('\n')}
|
|
26
|
+
</urlset>`;
|
|
27
|
+
return new Response(body, { headers: { 'content-type': 'application/xml; charset=utf-8' } });
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function robots(): Response {
|
|
31
|
+
return new Response(`User-agent: *\nAllow: /\nSitemap: ${new URL('/sitemap.xml', siteUrl()).href}\n`, {
|
|
32
|
+
headers: { 'content-type': 'text/plain' },
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Thrown from a loader: the site's 404 page with a real 404 (410: a listing that left the site). */
|
|
37
|
+
export function notFound(gone = false): Response {
|
|
38
|
+
return new Response(null, { status: gone ? 410 : 404, statusText: gone ? 'Gone' : 'Not Found' });
|
|
39
|
+
}
|