@usethrottle/builder-react 0.0.0-stage → 0.2.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/CLAUDE.md ADDED
@@ -0,0 +1,228 @@
1
+ # @usethrottle/builder-react
2
+
3
+ Renders a published Throttle Builder page document as React in a merchant's
4
+ store, and gives the store its header, footer, slots and site design.
5
+ `"private": true` in `package.json` keeps release-publish from publishing
6
+ `0.0.0`; the release task (Task 16) removes it together with adding the
7
+ changeset. There is no changeset on this branch on purpose.
8
+
9
+ Dependency direction: `@usethrottle/ui` <- this package <- `storefront-react/builder`;
10
+ `builder-schema` <- `builder` <- this package. Nothing in `ui` or the storefront
11
+ core imports this package.
12
+
13
+ ## Entries
14
+
15
+ | Entry | Directive | Holds |
16
+ |---|---|---|
17
+ | `.` | `"use client"` banner on the whole output | `BuilderRenderer`, `compileResponsiveCss`, `BuilderProvider`, `BuilderHeader`, `BuilderFooter`, `BuilderSlot`, `BuilderPage`, `BuilderPageView`, `AssetImage`, `WidgetStyle`, registry, data helpers, types, `BuilderUnavailableError` (re-exported from `@usethrottle/builder`, never redefined) |
18
+ | `./server` | none | `loadSite`, `loadBuilderPage`, `builderSitemap`, `getBundle` |
19
+ | `./next` | none | `createBuilderPage` -> `{ Page, generateMetadata }` |
20
+
21
+ esbuild cannot keep a per-module directive in a bundle, so the client entry is
22
+ one bundle with the directive on the output. `./next` holds only a *reference* to
23
+ `BuilderPageView`: it imports `@usethrottle/builder-react` by name (kept external
24
+ by `tsup.config.ts`, aliased to `src/index.ts` in vitest and in `tsconfig` paths).
25
+
26
+ ## The flow in a store
27
+
28
+ ```tsx
29
+ // app/layout.tsx (server): one read for the request
30
+ const site = await loadSite({ builderKey, locale, slots: ['product.above', 'product.below', 'shop.above', 'shop.below'], packs });
31
+ // a client module of the store, where the packs are created
32
+ <BuilderProvider builderKey={builderKey} packs={packs} site={site}>
33
+ <BuilderHeader />{children}<BuilderFooter />
34
+ </BuilderProvider>
35
+ // app/pages/[handle]/page.tsx
36
+ const { Page, generateMetadata } = createBuilderPage({ fromParams: 'handle', builderKey, packs });
37
+ export default Page;
38
+ export { generateMetadata };
39
+ ```
40
+
41
+ `BuilderProvider` is a client component: a pack holds components and functions,
42
+ which a server component cannot pass down, so the store creates its packs in a
43
+ client module. `site` is plain data (what `loadSite` returned).
44
+
45
+ ## Rules (do not break)
46
+
47
+ - **No time-based revalidation, ever.** Every read goes through the
48
+ `@usethrottle/builder` client, which is `until-changed`. This package never
49
+ calls `revalidatePath`, `revalidateTag` or `unstable_cache`, and sets no
50
+ `revalidate` time; `server.test.ts` scans `src` for them.
51
+ - **One read per request (R8).** `getBundle` shares one `client.bundle()` per
52
+ request through `react.cache`: an ask that an earlier read covers (same client
53
+ and locale, same page or none, every slot) reuses it, and asks in the same tick
54
+ merge into one read. A read that nothing covers is a second read: a layout does
55
+ not know the page, so on a Builder page route the layout read and the page read
56
+ are two reads per request unless `loadSite({ page })` names the page (a provider
57
+ placed in the route can). Metadata and page share one.
58
+ - **The Builder being down never blanks the store.** `loadSite` answers
59
+ `{ status: 'unavailable' }` for a `BuilderUnavailableError` with no last good
60
+ answer (logged once per process); header, footer and slots then render nothing
61
+ and the provider fills no design. A page throws `BuilderUnavailableError` and
62
+ lets the store's error boundary answer. A part or slot whose widget throws is
63
+ caught by `PartBoundary` and renders nothing.
64
+ - **Media `src` is on the media origin.** `loadSite({ mediaOrigin })` puts it in
65
+ `LoadedSite`; the provider, the renderer (`mediaOrigin` prop, `WidgetRenderProps.mediaOrigin`),
66
+ `AssetImage`, the background images in `css-compiler.ts` and the logo, favicon and
67
+ share image all use `safeUrl(url, 'src', { mediaOrigin })`: https, exactly that
68
+ origin. No origin means no image. Widgets pass `mediaOrigin` to `AssetImage`.
69
+ - **Redirects are site paths** (`safe-path.ts` `sitePath`): one leading `/` then not
70
+ `/` or `\`, no control character or whitespace, and still a path once decoded.
71
+ - **Own properties only** (`Object.hasOwn`) for every lookup keyed by document or
72
+ settings data (assets, slots, locales, data keys, alignments, fonts).
73
+ - **Anchors** are re-checked against `ANCHOR_RE` in `NodeWrapper`; a `resolveLink`
74
+ result is re-checked with `safeUrl`.
75
+ - **A part that throws during SSR** is caught by the `Suspense` inside its
76
+ `PartBoundary` (boundaries do not catch on the server; `ssr.test.tsx`).
77
+ - **Never raw HTML.** No `dangerouslySetInnerHTML`, `innerHTML` and the like in
78
+ `src` (`security.test.tsx` scans for them). Template values go through React.
79
+ Widget CSS goes in only through `WidgetStyle`, as the text of a `<style>`.
80
+ - **Every custom widget is boxed in** by `NodeWrapper`: inline
81
+ `contain: layout paint; isolation: isolate; overflow: clip` and `data-b-w`
82
+ (the scope of its sanitised CSS, `[data-b-w="<type>"] .x`, so its CSS can never
83
+ restyle the box). `containment.test.ts` proves in Chromium, at the three
84
+ breakpoints, that a widget using `transform: translate(-9999px) scale(50)` or
85
+ negative margins cannot paint over or take clicks from a sibling button, with a
86
+ negative control that fails without the box.
87
+ - **Node cap.** `RenderBudget` / `MAX_RENDERED_NODES` equal `MAX_TEMPLATE_WEIGHT`
88
+ (20 000). The renderer hands a fresh budget to each custom widget; the template
89
+ interpreter (`src/custom/`) calls `fitsBudget(ast)` first and `budget.take()` per node.
90
+ - **Custom widgets (`src/custom/`).** `customWidgetFactory` (the registry's default
91
+ `CustomWidgetFactory`, now `(snapshot, registry)`) builds the component of a frozen
92
+ `custom.*` widget, or null (an empty box) for a snapshot that does not pass the validator. A
93
+ `status: 'disabled'` snapshot gets a component that renders nothing in a store and a
94
+ placeholder in `editMode`.
95
+ - *Template:* only the snapshot's `template` source is read (an `ast` field is
96
+ ignored). `compileTemplate` runs `parseTemplate`, `validateTemplate` against the
97
+ snapshot's settings, data inputs and the registry's sources, `fitsBudget` and
98
+ `sanitizeWidgetCss` once per snapshot and registry; any failure refuses the whole
99
+ widget. `interpreter.tsx` is a switch over the closed AST that returns React
100
+ elements: own-property lookups that refuse `__proto__`, `constructor`, `prototype`
101
+ and inherited names and never read into arrays, `#each` at most 100 items,
102
+ `budget.take()` per node, a 1 000 000 character cap on text, element/attribute/class/
103
+ role allow-lists re-checked, `safeUrl` on every `href` and `src`. CSS is `WidgetStyle`
104
+ text inside the containment box.
105
+ - *Composite:* the body goes through `pageDocumentSchema` (as the validator wraps it),
106
+ each binding writes the setting's prepared value into the inner prop (checked with
107
+ `validateSettingValue`, same control only), data inputs reach inner nodes as
108
+ `composite.<name>` data, inner anchors are dropped, another composite in the body is
109
+ cut, and the inner template weights are taken from the widget's budget. Inner nodes
110
+ render with `BuilderRenderer` and the same registry, each node under an id hashed from
111
+ the composite's node id (so `data-b-id` is unique per instance). Links in a body resolve
112
+ through `WidgetRenderProps.resolveLink` (the page's resolver), and the inner renderer
113
+ runs `safeUrl` on the result.
114
+ - Both render inside `PartBoundary` + `Suspense`, so a throw (browser or SSR) blanks
115
+ only that widget.
116
+ - **The renderer is a pure function of its props**: no state, effects or
117
+ context, so it renders the same in a server component, in SSR of a client
118
+ tree and in the editor canvas. Interactivity (the perShopper data after mount,
119
+ the part boundary, the page read) is in `part-view.tsx`, `page.tsx`, `shopper-data.ts`.
120
+ - **perShopper data is never in SSR.** `loadBuilderPage`/`loadSite` resolve
121
+ `staticDataFor` (non-perShopper) only; `useResolvedData` resolves perShopper
122
+ sources in the browser after mount.
123
+ - **Settings reach CSS as custom properties only.** A `css` setting becomes
124
+ `--b-<key>` (`--w-<key>` for a custom widget, what its sanitised CSS reads) in
125
+ rules scoped by `[data-b-id="<id>"]`: desktop in a plain rule, tablet and phone
126
+ changes in `@media (max-width:1024px)` and `@media (max-width:767px)`. Layout
127
+ of sections and columns is `--tb-*`. A value is built from a validated token,
128
+ number, colour or enum, and dropped when it holds anything outside
129
+ `[A-Za-z0-9#%.,()-+*/_: ]`. Every widget stylesheet must read
130
+ `var(--b-<key>, <default>)` (defaults are emitted for desktop too).
131
+ - **Markup variants.** A `markup` setting that differs per device renders each
132
+ distinct variant once with `tb-v` and `tb-only-desktop|tablet|phone` classes;
133
+ a `css` setting never splits a widget. Only the first variant carries the anchor id.
134
+ - **Styles** are `@layer throttle` with the `tb-` prefix (`styles.ts`), emitted
135
+ once through `<style href="tb-base" precedence="throttle">` (React 19 hoists
136
+ and dedupes it). The host defines `--tb-color-<token>` and `--tb-scale`;
137
+ `BuilderProvider` does, from the site theme. Preset tokens apply while
138
+ `theme.customized` is false.
139
+ - **Bundle size** of the client entry, minified and gzipped, dependencies
140
+ external: at most 35 KB (`pnpm --filter @usethrottle/builder-react size`, the
141
+ limit is in `size-limit.json`).
142
+
143
+ ## SEO (`src/next/seo.ts`)
144
+
145
+ `createBuilderPage().generateMetadata` is `metadataOf(page, ...)`: the page's own `seo` over the
146
+ site's defaults. The read API (and a build-mode release) answers `page.seo` as
147
+ `{ title?, description?, shareImage: FrozenAsset | null, noindex }`, already in the requested
148
+ locale; the site's `seo` is `{ titleTemplate, defaultDescription, shareImage }`. Never read
149
+ `page.description` (it does not exist).
150
+
151
+ - Title is `seo.title ?? page.title` through `titleTemplate` (`{page}`, `{store}`), with replacer
152
+ functions so a `$&` in a title is text.
153
+ - Share image: the page's, else the site's, through `safeUrl(url, 'src', { mediaOrigin })`
154
+ (`createBuilderPage({ mediaOrigin })`, the same value as `loadSite`). Off-origin, http or no
155
+ origin means no image, never a guessed one.
156
+ - Canonical needs an origin: `createBuilderPage({ storeUrl })`, an explicit app option checked against
157
+ `http(s)://host` (`originOf`, shared with the sitemap). The Builder deliberately strips `storeUrl` from
158
+ published settings (`resolve.ts`), so there is no settings fallback; without a valid one a page has no
159
+ canonical and the sitemap is empty, each with one warning.
160
+ - Page path (`pagePathOf`, shared by canonical and sitemap): the store's `pagePath(page)` answer when it
161
+ is a valid site path, else `routes.page` + slug, else the Builder's default `/pages/{handle}`; never the
162
+ answered `page.path`, so home is `/pages/home` (the Builder says `/`; a store may serve the shop there)
163
+ even when a read failed. A store that serves home at `/` passes `pagePath` to both
164
+ `createBuilderPage` and `builderSitemap`.
165
+ - A route with a `[locale]` segment (and no `locale` option) prefixes `/<locale>` in the canonical and
166
+ gets `alternates.languages` for every site locale plus `x-default`. `builderSitemap({ localeRoute: true })`
167
+ lists each page once per site locale under the same prefix (`localized`). Any other URL scheme for
168
+ locales is not known to this package.
169
+ - `builderSitemap({ storeUrl, locale?, localeRoute?, pagePath? })` takes noindex from the page list
170
+ (`BuilderPageSummary.noindex`, sent by the Builder's `/v1/pages`) and reads no page. Only a list entry
171
+ with no boolean there (an older Builder, a release) is read, with `pages.get(slug, { locale })`, 8 at a
172
+ time; a failed read keeps the page, a missing page, a redirect and a noindex page are skipped. The page
173
+ route and locales come from one `site({ locale })` read.
174
+ - No structured data: the spec has no JSON-LD setting. It is the merchant's own choice.
175
+
176
+ ## Shared files (Task 12 owns them; Tasks 13 and 14 edit marked sections only)
177
+
178
+ - `src/index.ts`: `// <task-13>` ... `// </task-13>`, `// <task-14>` ... `// </task-14>`.
179
+ - `src/registry.ts`: `BUILTIN_PACKS` (`basicPack` goes in `<task-13>`) and
180
+ `DEFAULT_CUSTOM_WIDGET` (the template and composite runtime goes in `<task-14>`).
181
+
182
+ ## Basic widgets (`src/basics`, Task 13)
183
+
184
+ `basicPack` (`id: 'basic'`, v1 each) pairs builder-schema's `BASIC_WIDGET_DEFINITIONS`
185
+ with a component; it is in `BUILTIN_PACKS`, so every renderer has it and a pack
186
+ cannot replace a `basic.*` type. Definitions are never re-declared here.
187
+
188
+ - **Site parts** (`logo`, `menu`, `announcement`, `copyright`) read `useSiteDesign()`
189
+ (`@usethrottle/ui`), which `BuilderProvider` fills. Without one they render nothing
190
+ (a hint in the editor). Menus are looked up by own name; every href is `safeUrl` again.
191
+ - **Images** (`basic.image`, `basic.logo`) are `https` on `mediaOrigin` only (fail-closed).
192
+ - **Rich text** (`basic.text`): `basics/rich-text.tsx` tokenizes the string and builds React
193
+ elements (p, br, strong, em, u, s, a, ul, ol, li, h2-h4, blockquote, code); `href` only
194
+ on `a`, through `safeUrl`. Never an HTML string. Word paste reduces to p/strong/em/a.
195
+ - **Video**: YouTube/Vimeo only (`parseVideoUrl`), poster drawn locally, the iframe
196
+ (`youtube-nocookie.com` / `player.vimeo.com`, built from the id) loads on click.
197
+ - **`select` settings that need a mapping** (image radius/fit, divider style, video ratio)
198
+ cannot be read from the compiled `--b-<key>: <option>`, so `enumCss` emits `--bx-<key>`
199
+ per device from a closed table. Other settings are read as `var(--b-<key>, default)`.
200
+ - Stylesheet: `basics/styles.ts`, `@layer throttle`, `tb-b-*`, hoisted like the base CSS.
201
+ - `pnpm --filter @usethrottle/builder-react dev` serves `playground/main.tsx` (every basic,
202
+ port 5192) for looking at 390, 768 and 1280 px. Media there is a fake https origin that
203
+ the browser check answers itself.
204
+
205
+ ## Tests
206
+
207
+ `pnpm --filter @usethrottle/builder-react test` (build `ui`, `builder-schema` and
208
+ `builder` first: they are read from `dist`). `containment.test.ts` and
209
+ `layout.test.ts` launch Chromium through `playwright`
210
+ (`pnpm exec playwright install chromium`). Tests stand in for a request with
211
+ `__tests__/request-cache.ts` (a `react.cache` that memoizes per `newRequest()`).
212
+
213
+ ## Build mode (Task 18c)
214
+
215
+ A client made with `createBuilderClient({ mode: 'build' })` makes the loaders (`loadSite`, `createBuilderPage`,
216
+ `builderSitemap`) render from the frozen release with zero network. In build mode an unreadable release throws (the
217
+ R8 "render nothing" fallbacks are for live clients only: `client.mode !== 'build'`). `builderStaticParams` (server
218
+ entry) lists every release page for `generateStaticParams` and refuses a live client: a live store keeps its pages
219
+ dynamic (cost rule), a build store generates them all on purpose. `src/budget.ts` exports `Budget`, the structural
220
+ type renderers take, so the two server entries' copies of `RenderBudget` stay interchangeable.
221
+
222
+ ## RSC build check
223
+
224
+ `pnpm --filter @usethrottle/builder-react test:rsc` (CI job "builder-react in a Next App Router build") runs a real
225
+ `next build` of a minimal App Router app that imports `./next` and `./server` from the built dist, installed as copies under
226
+ `node_modules` the way an app has them. Vitest never uses the `react-server` condition, so only this catches a server entry
227
+ that evaluates something React's `react-server` build lacks (`PartBoundary extends Component` crashed 0.1.0). Build the
228
+ package first. Do not point it at a link into the workspace: Next only skips its client-hook check for code under node_modules.