@realadvisor-sites/kit-core 0.5.0 → 0.5.3

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/AGENTS.md CHANGED
@@ -134,7 +134,7 @@ Field reference (the API's snake_case): `node_modules/@realadvisor/sites-sdk/src
134
134
 
135
135
  Where data comes from (you never configure it): production uses
136
136
  `SITES_API_URL` + `SITES_API_KEY`, set at publish (live, cached 60 s by the
137
- RealAdvisor API); the CRM preview uses the same two from `.dev.vars` (a
137
+ RealAdvisor API and 60 s in the colo by the kit; add no cache of your own); the CRM preview uses the same two from `.dev.vars` (a
138
138
  placeholder key: never print, log or send it anywhere else); everything
139
139
  else reads the fixture (`pnpm dev`, `pnpm check` copy the CRM's data or the
140
140
  kit's Demo Agency there when it is empty): `app/data/fixture.json` on
package/CHANGELOG.md CHANGED
@@ -11,6 +11,54 @@ the versions is enough.
11
11
  To upgrade a site, read every entry newer than the site's current version,
12
12
  oldest first, and apply each Upgrade step in order.
13
13
 
14
+ ## 0.5.3
15
+
16
+ - A published production site (`SITE_MODE=production`) keeps its data reads
17
+ in the colo's Cache API. A page served again makes no request to the data
18
+ API for 60 seconds. After that the stale copy answers at once and refreshes
19
+ in the background, for up to 24 hours. A listing or development not found
20
+ is kept 60 seconds. Previews and dev read live.
21
+ - When the data API times out or answers a 5xx, the stale copy answers
22
+ instead of the 500 page.
23
+ - A data read gives up after 3 seconds, down from 8. An enquiry keeps 8.
24
+ - SDK: `createClient({ cache })` turns the cache on (`true`, or
25
+ `{ waitUntil, store }`). It is off by default.
26
+ - kit-core: `withRequestContext(ctx, fn)` and `dataCache(prodBuild)` in
27
+ `env`. The Astro middleware and the React Worker call the first.
28
+
29
+ ## 0.5.2
30
+
31
+ - Every page that fails to render, and every enquiry refused for its site
32
+ key, writes one JSON line to the Worker logs with `"event": "site_error"`,
33
+ `source` (`page` or `enquiry`), `code` (`site_key` when the data API refused
34
+ the key, else the API's code or `render`), `status`, `api_status`, `site`
35
+ and `worker` (from `SITE_SLUG` and `SITE_WORKER` when the publish sets
36
+ them), `host` and `path`. A monitor matches `event`. The site key never
37
+ appears in it.
38
+ - The kit's 500 page answers in the language of the path (`/en/...` on a
39
+ multilingual site), else the site's (`site.json` `locale`), else English.
40
+ - kit-react: `handleError` in `entry.server` logs a failed loader or render
41
+ as that line. Without it, the Worker still logs each 500 answer, with less
42
+ detail.
43
+ - The examples' `ServerError` pages take their text from `serverErrorText()`
44
+ instead of copy written in one language.
45
+
46
+ ### Upgrade
47
+
48
+ - React Router site: in `app/entry.server.tsx`, export `handleError` too:
49
+ `export { default, handleError, streamTimeout } from '@realadvisor/sites-kit-react/entry.server';`
50
+ - React Router site: if `ServerError` in `app/routes/404.tsx` has its text
51
+ written out, take it from
52
+ `serverErrorText(lang(usePageLocale()))` (`@realadvisor/sites-kit-core/render-error`).
53
+
54
+ ## 0.5.1
55
+
56
+ - kit-react: the dev server can always be framed by the CRM preview, whatever
57
+ `SITE_MODE` says. The CRM sandbox runs dev with `SITE_MODE=production` (so
58
+ preview enquiries send), which made the React kit send
59
+ `X-Frame-Options: DENY` and the preview stayed blank. Published sites keep
60
+ their headers unchanged.
61
+
14
62
  ## 0.5.0
15
63
 
16
64
  - React Router is the default: `template/` is now a React Router 7 starter,
package/DESIGN.md CHANGED
@@ -90,7 +90,7 @@ import lato900 from '@fontsource/lato/files/lato-latin-900-normal.woff2?url';
90
90
  other side `auto`: no fixed box, no `object-fit: cover`, no
91
91
  `aspect-ratio`. Size it by its shape: a wide wordmark at 1440 at least
92
92
  100px wide and 32px tall (140–180px wide for a script or detailed logo),
93
- at most 72px tall; a tall or square mark (a monogram, 3³) 40–72px tall.
93
+ at most 72px tall; a tall or square mark (a monogram, a stacked numeral) 40–72px tall.
94
94
  At 390 at least 28px tall. The header stays slim: at most 12% of the
95
95
  screen. `pnpm screenshot` flags a logo off its file's ratio or outside
96
96
  these sizes.
package/README.md CHANGED
@@ -16,7 +16,7 @@ In this repo the template and examples use paths instead (`file:../kit-core`).
16
16
  | Import | What |
17
17
  | --- | --- |
18
18
  | `@realadvisor/sites-kit-core` | The data SDK re-exported (`@realadvisor/sites-sdk`, a peer: `createClient`, `createFixtureClient`, `handleEnquiry`, the snake_case types), `Agency`, `SiteFixture`, `sanitizeHtml` and the other HTML helpers (`lib/html.ts`), `listingIdFromSlug`. |
19
- | `@realadvisor/sites-kit-core/<module>` | `agency`, `enquiry`, `fixture`, `env`, `format`, `i18n`, `image`, `legal`, `search`, `seo`, `developments`, `page-locale`, `render-error`, `security` (`lib/`). |
19
+ | `@realadvisor/sites-kit-core/<module>` | `agency`, `enquiry`, `fixture`, `env`, `format`, `i18n`, `image`, `legal`, `search`, `seo`, `developments`, `page-locale`, `render-error`, `site-error`, `security` (`lib/`). |
20
20
  | `@realadvisor/sites-kit-core/client/<name>` | Browser scripts behind the listing search and map, the enquiry form, consent and the combobox. |
21
21
  | `@realadvisor/sites-kit-core/styles/form.css` | The form controls' shared look. |
22
22
  | `@realadvisor/sites-kit-core/site-config` | `site.json`: read and validate. |
package/lib/enquiry.ts CHANGED
@@ -28,7 +28,7 @@ import type { SitesClient } from '@realadvisor/sites-sdk/types';
28
28
  import { siteMode } from './env';
29
29
  import { lang, t } from './i18n';
30
30
  import { LOCALE } from './format';
31
- import { SITE_KEY_REJECTED } from './render-error';
31
+ import { logSiteError } from './site-error';
32
32
 
33
33
  /** What the endpoint reads: the site's client (`ra`, or the React kit's `sites`). */
34
34
  export type EnquiryClient = Pick<SitesClient, 'development'> & { live(): SitesClient | null };
@@ -153,7 +153,11 @@ export async function enquiryAction(request: Request, sites: EnquiryClient): Pro
153
153
  case 'rate_limited':
154
154
  return respond(429, { error: 'rate_limited' }, 'error');
155
155
  case 'site_key':
156
- console.error(JSON.stringify({ level: 'error', msg: `[enquiry] ${SITE_KEY_REJECTED}` }));
156
+ logSiteError('enquiry', Object.assign(new Error('the data API refused the site key'), { name: 'SitesApiError', code: 'site_key' }), {
157
+ status: 503,
158
+ path: new URL(request.url).pathname,
159
+ host: new URL(request.url).host,
160
+ });
157
161
  return respond(503, { error: 'unavailable', reason: 'site_key' }, 'error');
158
162
  default:
159
163
  return respond(502, { error: 'unavailable' }, 'error');
package/lib/env.ts CHANGED
@@ -6,11 +6,16 @@
6
6
  * site falls back to fixtures (`pnpm dev`, build time).
7
7
  * - `SITE_MODE`: `production` or `preview`, set at publish. Preview sites never send enquiries.
8
8
  * - `ANALYTICS_ID`: GA4 measurement id. The consent banner shows only when set.
9
+ * - `SITE_SLUG`, `SITE_WORKER`: the site's slug and Worker name, when the
10
+ * publish sets them. Error log lines carry them (lib/site-error.ts).
9
11
  *
10
12
  * Prerendered pages are built without a request, so they see only
11
13
  * process.env at build time. Never read the API key from a prerendered page.
12
14
  */
13
15
 
16
+ import { AsyncLocalStorage } from 'node:async_hooks';
17
+ import type { CacheOptions } from '@realadvisor/sites-sdk/types';
18
+
14
19
  export type SiteEnv = {
15
20
  SITE_MODE?: string;
16
21
  ANALYTICS_ID?: string;
@@ -21,6 +26,8 @@ export type SiteEnv = {
21
26
  */
22
27
  SITES_API_URL?: string;
23
28
  SITES_API_KEY?: string;
29
+ SITE_SLUG?: string;
30
+ SITE_WORKER?: string;
24
31
  };
25
32
 
26
33
  let runtime: SiteEnv = {};
@@ -45,6 +52,37 @@ const read = (name: keyof SiteEnv): string | undefined =>
45
52
  export const siteMode = (): 'production' | 'preview' =>
46
53
  read('SITE_MODE') === 'production' ? 'production' : 'preview';
47
54
  export const analyticsId = () => read('ANALYTICS_ID');
55
+ /** Who the site is, for log lines: slug and Worker name, null when the publish did not set them. */
56
+ export const siteIdentity = () => ({
57
+ site: read('SITE_SLUG') ?? null,
58
+ worker: read('SITE_WORKER') ?? null,
59
+ });
60
+ /** The part of a Worker's ExecutionContext the data cache needs. */
61
+ export type WaitUntil = { waitUntil(p: Promise<unknown>): void };
62
+
63
+ const request = new AsyncLocalStorage<WaitUntil | undefined>();
64
+
65
+ /** Runs `fn` with this request's ExecutionContext: the data cache refreshes a stale copy through its waitUntil. */
66
+ export const withRequestContext = <T>(ctx: WaitUntil | undefined, fn: () => T): T => request.run(ctx, fn);
67
+
68
+ /**
69
+ * The SDK's `cache` option: on for a published production site (SITE_MODE
70
+ * production and a production build), off for previews and dev, so they
71
+ * show each CRM change at once. A stale copy refreshes after the answer
72
+ * (the request's waitUntil), or before it outside a request.
73
+ */
74
+ export const dataCache = (prodBuild: boolean): CacheOptions | false =>
75
+ prodBuild && siteMode() === 'production'
76
+ ? {
77
+ waitUntil: (p) => {
78
+ const ctx = request.getStore();
79
+ if (!ctx) return false;
80
+ ctx.waitUntil(p);
81
+ return true;
82
+ },
83
+ }
84
+ : false;
85
+
48
86
  export const previewApi = () => ({
49
87
  url: read('SITES_API_URL'),
50
88
  token: read('SITES_API_KEY'),
@@ -1,17 +1,18 @@
1
1
  /**
2
2
  * The answer when a page fails to render (the kit middleware): the error goes
3
- * to the Worker logs (observability), the visitor gets a short 500 page in
4
- * the site language that no cache keeps. Never an empty 200.
3
+ * to the Worker logs as one `site_error` line (lib/site-error.ts), the
4
+ * visitor gets a short 500 page that no cache keeps, never an empty 200. The
5
+ * page is in the language of the path (`/en/...` on a multilingual site),
6
+ * else the site's (site.json `locale`), else English.
5
7
  * `notFoundPage` is the last-resort 404/410 when even the site's /404 page
6
8
  * cannot render: a missing page is never reported as a 500.
7
- * A rejected site key (`site_key`: the key was
8
- * revoked or replaced) is logged as such: only a republish fixes it.
9
+ * A rejected site key (`code: 'site_key'`: the key was revoked or replaced)
10
+ * is logged as such: only a republish fixes it.
9
11
  */
10
- import { SitesApiError } from '@realadvisor/sites-sdk';
11
12
  import { lang, localeOfPath, t } from './i18n';
13
+ import { logSiteError } from './site-error';
12
14
 
13
- /** What a `site_key` error means for a site: its key was revoked or replaced. Only a republish mints a new one. */
14
- export const SITE_KEY_REJECTED = 'site key rejected (401): republish the site to mint a new key';
15
+ export { SITE_ERROR_EVENT, SITE_KEY_REJECTED } from './site-error';
15
16
 
16
17
  const TEXT = {
17
18
  de: ['Seite vorübergehend nicht verfügbar', 'Bitte versuchen Sie es in einigen Minuten erneut.', 'Zur Startseite'],
@@ -27,11 +28,13 @@ export const serverErrorText = (l: keyof typeof TEXT = lang()) => {
27
28
  return { title, body, home };
28
29
  };
29
30
 
30
- export function renderFailed(path: string, err: unknown): Response {
31
- const e = err instanceof Error ? err : new Error(String(err));
32
- const msg = err instanceof SitesApiError && err.code === 'site_key' ? `page render failed: ${SITE_KEY_REJECTED}` : 'page render failed';
33
- console.error(JSON.stringify({ level: 'error', msg, path, error: e.message, stack: e.stack?.slice(0, 2000) }));
34
- const l = lang();
31
+ /**
32
+ * Logs the failure and answers the 500 page. `host`: the request's host, for
33
+ * the log line.
34
+ */
35
+ export function renderFailed(path: string, err: unknown, host?: string): Response {
36
+ logSiteError('page', err, { status: 500, path, host });
37
+ const l = lang(localeOfPath(path));
35
38
  const [title, body, home] = TEXT[l];
36
39
  return new Response(page(l, title, body, home), {
37
40
  status: 500,
@@ -0,0 +1,81 @@
1
+ /**
2
+ * One JSON log line per failure, for a monitor to match: a page that failed
3
+ * to render (`source: 'page'`, answered with the 500 page) and an enquiry the
4
+ * data API refused (`source: 'enquiry'`). Every line has the same `event`
5
+ * (`site_error`), so one Workers Logs query or Logpush filter finds them all;
6
+ * `code` says why (`site_key`: the API answered 401/403 to the site key, it
7
+ * was revoked or replaced and only a republish mints a new one; another
8
+ * SitesApiError code; `render` for any other error).
9
+ *
10
+ * {"level":"error","event":"site_error","source":"page","code":"site_key",
11
+ * "status":500,"api_status":401,"site":"milestone-properties",
12
+ * "worker":"ra-site-milestone-properties-5845","host":"www.example.es",
13
+ * "path":"/","msg":"page render failed: site key rejected (401): …","error":"…"}
14
+ *
15
+ * `site` and `worker` come from SITE_SLUG and SITE_WORKER (lib/env.ts), null
16
+ * when the publish did not set them; Workers Logs tag each line with the
17
+ * script name as well. Never logs the key or the request's headers.
18
+ */
19
+ import { siteIdentity } from './env';
20
+
21
+ export const SITE_ERROR_EVENT = 'site_error';
22
+
23
+ /** What a `site_key` error means for a site: its key was revoked or replaced. Only a republish mints a new one. */
24
+ export const SITE_KEY_REJECTED = 'site key rejected (401): republish the site to mint a new key';
25
+
26
+ export type SiteErrorLine = {
27
+ level: 'error';
28
+ event: typeof SITE_ERROR_EVENT;
29
+ source: 'page' | 'enquiry';
30
+ /** `site_key`, another SitesApiError code, or `render`. */
31
+ code: string;
32
+ /** The status the visitor got. */
33
+ status: number;
34
+ /** The status the data API answered, null when the error is not the API's. */
35
+ api_status: number | null;
36
+ site: string | null;
37
+ worker: string | null;
38
+ host: string | null;
39
+ path: string | null;
40
+ msg: string;
41
+ error: string;
42
+ stack?: string;
43
+ };
44
+
45
+ /** A SitesApiError, also one from another copy of the SDK (a second bundle): matched by shape. */
46
+ const apiError = (err: unknown): { code: string; status: number } | null => {
47
+ const e = err as { name?: unknown; code?: unknown; status?: unknown } | null;
48
+ return e && e.name === 'SitesApiError' && typeof e.code === 'string'
49
+ ? { code: e.code, status: typeof e.status === 'number' ? e.status : 0 }
50
+ : null;
51
+ };
52
+
53
+ export function siteErrorLine(
54
+ source: SiteErrorLine['source'],
55
+ err: unknown,
56
+ opts: { status: number; path?: string | null; host?: string | null },
57
+ ): SiteErrorLine {
58
+ const e = err instanceof Error ? err : new Error(String(err));
59
+ const api = apiError(err);
60
+ const code = api?.code ?? 'render';
61
+ const what = source === 'page' ? 'page render failed' : '[enquiry] refused';
62
+ return {
63
+ level: 'error',
64
+ event: SITE_ERROR_EVENT,
65
+ source,
66
+ code,
67
+ status: opts.status,
68
+ api_status: api ? api.status || null : null,
69
+ ...siteIdentity(),
70
+ host: opts.host ?? null,
71
+ path: opts.path ?? null,
72
+ msg: code === 'site_key' ? `${what}: ${SITE_KEY_REJECTED}` : what,
73
+ error: e.message,
74
+ ...(e.stack && !api ? { stack: e.stack.slice(0, 2000) } : {}),
75
+ };
76
+ }
77
+
78
+ /** Writes the line to the Worker logs (console.error, one JSON object). */
79
+ export function logSiteError(...args: Parameters<typeof siteErrorLine>): void {
80
+ console.error(JSON.stringify(siteErrorLine(...args)));
81
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@realadvisor-sites/kit-core",
3
- "version": "0.5.0",
3
+ "version": "0.5.3",
4
4
  "description": "The framework-neutral core of a RealAdvisor site, shared by the Astro kit and the React kit: data helpers over @realadvisor/sites-sdk (a peer), i18n, formatting, legal texts, SEO, search, images, security headers, the browser scripts (listing search and map, enquiry, consent), the sites-kit tools (fixture, screenshot, deploy check) and the rules the coding agent follows (AGENTS.md, DESIGN.md).",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -55,7 +55,7 @@
55
55
  "test": "node --experimental-strip-types --no-warnings=ExperimentalWarning --test \"test/*.test.mjs\" \"test/*.test.ts\""
56
56
  },
57
57
  "peerDependencies": {
58
- "@realadvisor/sites-sdk": "^0.5.0",
58
+ "@realadvisor/sites-sdk": "^0.5.3",
59
59
  "playwright": "^1.64.1"
60
60
  },
61
61
  "peerDependenciesMeta": {
@@ -557,7 +557,7 @@ async function shoot({ path, vp, i }) {
557
557
  const lg = checks.logo;
558
558
  if (lg) {
559
559
  if (!lg.contain && (lg.dev > 1.05 || lg.dev < 0.95)) entry.problems.push(`[${vp.name}] logo "${lg.name}" ${lg.fit === 'fill' ? 'stretched' : 'cropped'} (box ratio ${(lg.dev * 100 - 100).toFixed(0)}% off the file): set only height (width: auto), no fixed box, no object-fit: cover`);
560
- // A wide wordmark is sized by width, a tall or square mark (3³, a monogram) by height.
560
+ // A wide wordmark is sized by width, a tall or square mark (a monogram, a stacked numeral) by height.
561
561
  const wide = lg.drawnW / lg.drawnH >= 1.3;
562
562
  if (vp.name === '1440' && wide && (lg.drawnW < 100 || lg.drawnH < 32)) entry.problems.push(`[1440] logo "${lg.name}" drawn ${Math.round(lg.drawnW)}x${Math.round(lg.drawnH)}px: at least 100px wide and 32px tall (140–180px wide for a detailed logo)`);
563
563
  if (vp.name === '1440' && !wide && (lg.drawnH < 40 || lg.drawnH > 72)) entry.problems.push(`[1440] logo "${lg.name}" (a tall or square mark) drawn ${Math.round(lg.drawnH)}px tall: 40–72px tall`);