Repository navigation
feat: lightweight site template — framework extractions - #66
Conversation
buildHead() only emitted a robots meta tag when noIndexing was true, leaving indexable pages without any robots directive. Crawlers default to index,follow but the explicit tag is expected for SEO tooling and ensures rich-result directives (max-image-preview, max-snippet, max-video-preview) are present on every page. Made-with: Cursor
Exports createDecoRouter(), decoParseSearch, decoStringifySearch from @decocms/start/sdk/router. Uses standard URLSearchParams serialization instead of TanStack's JSON-based format — required for commerce filter URLs like ?filter.brand=Nike&filter.brand=Adidas to round-trip correctly. Defaults: scrollRestoration=true, defaultPreload="intent". Part of lightweight-template initiative. Made-with: Cursor
New components exported from @decocms/start/hooks: - DecoRootLayout: full root layout with QueryClient, NavigationProgress, StableOutlet, LiveControls, DECO.events bootstrap, analytics script, and deco:ready hydration signal. Accepts lang, siteName, account, bodyClassName, staleTime, decoReadyDelay, and children. - NavigationProgress: top-of-page loading bar during SPA navigation - StableOutlet: height-preserving Outlet wrapper to prevent footer jump Sites compose their __root.tsx from DecoRootLayout, passing only site-specific meta/links in head() and extras (Toast, etc.) as children. Adds @tanstack/react-query as peerDependency. Part of lightweight-template initiative. Made-with: Cursor
Replace dangerouslySetInnerHTML with TanStack Router's ScriptOnce component for both the DECO.events bootstrap and the analytics script. ScriptOnce is the idiomatic TanStack way to inject inline scripts that must run before hydration — it renders once during SSR, executes immediately when the browser parses the HTML, then self-removes from the DOM. No duplicate execution on SPA navigation. Made-with: Cursor
…correct types - createDecoRouter: add Wrap and context options per TanStack RouterOptions docs. QueryClientProvider should be configured via Wrap (non-DOM provider pattern), not inside the root layout component. - createDecoRouter: add "render" to defaultPreload union (was missing from type). - DecoRootLayout: remove manual QueryClientProvider — providers belong on the router's Wrap option per TanStack docs. Layout is now pure DOM rendering. - DecoRootLayout: already uses ScriptOnce (fixed in prior commit). Verified against tanstack search-docs for RouterOptions, scrollRestoration, ScriptOnce, Document Head Management, and TanStack Query Integration guides. Made-with: Cursor
Composes section registration, matchers, blocks, meta, render shell, preview wrapper, error handlers, and platform init hooks into a single function. Sites pass their Vite-resolved globs and config instead of calling 10+ individual registration functions. Eliminates ~30 lines of identical boilerplate per site. Made-with: Cursor
- Recursively unwrap `as unknown as Type` chains instead of single-level - Use `.inputValidator()` (current TanStack API) instead of bare `.handler()` - Add `: Promise<any>` return type annotation to satisfy TS strict mode - Export vtexActions map separately for site-level composition - Re-export OrderForm type for convenience - Log warnings for actions that couldn't be auto-parsed Made-with: Cursor
Adds withABTesting() wrapper that provides KV-driven traffic splitting between TanStack worker and legacy fallback origin. Includes FNV-1a IP hashing, sticky bucket cookies, circuit breaker, fallback proxy with hostname rewriting, and configurable path bypass. Sites replace ~200 lines of hand-written A/B code with a 15-line config. Made-with: Cursor
… options createDecoWorkerEntry now automatically: - Appends security headers (HSTS, X-Frame-Options, etc.) to HTML responses - Injects CF geo data as cookies for location matchers - Accepts site-specific CSP directives via the `csp` option Sites no longer need to manually wire these — just pass `csp: [...]` for their third-party scripts and everything else is handled. Made-with: Cursor
There was a problem hiding this comment.
5 issues found across 12 files
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="src/sdk/workerEntry.ts">
<violation number="1" location="src/sdk/workerEntry.ts:974">
P1: Applying security headers globally adds `X-Frame-Options: SAMEORIGIN` to `/live/previews` HTML, which can block cross-origin admin iframe previews.</violation>
</file>
<file name="src/setup.ts">
<violation number="1" location="src/setup.ts:175">
P2: Unhandled promise rejection — `options.meta().then(…)` has no `.catch()`. If the dynamic import fails, this surfaces as an unhandled rejection rather than a graceful degradation.</violation>
</file>
<file name="src/hooks/StableOutlet.tsx">
<violation number="1" location="src/hooks/StableOutlet.tsx:11">
P2: `savedHeight` is stored in a ref but used for rendering; updating it won’t re-render, so `minHeight` may not be applied when loading starts. Use state for the rendered height value.</violation>
</file>
<file name="src/sdk/abTesting.ts">
<violation number="1" location="src/sdk/abTesting.ts:204">
P2: A/B bucket cookie is missing the `Secure` flag. Since this runs on Cloudflare Workers (HTTPS-only), add `Secure` to prevent the cookie from leaking over a non-HTTPS connection in edge cases (redirect chains, mixed-content, etc.).</violation>
<violation number="2" location="src/sdk/abTesting.ts:253">
P1: Stale `Content-Length` after body rewriting. When `fallbackOrigin` and `url.hostname` differ in length, `replaceAll` changes the body size but the original `Content-Length` header is copied verbatim into the new `Response`. This can cause clients to truncate or reject the response. Delete the header after construction so the runtime can recalculate it (or omit it for streaming).</violation>
</file>
Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.
| return dressResponse(origin, "MISS"); | ||
| }); // end RequestContext.run() | ||
|
|
||
| return applySecurityHeaders(response); |
There was a problem hiding this comment.
P1: Applying security headers globally adds X-Frame-Options: SAMEORIGIN to /live/previews HTML, which can block cross-origin admin iframe previews.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/sdk/workerEntry.ts, line 974:
<comment>Applying security headers globally adds `X-Frame-Options: SAMEORIGIN` to `/live/previews` HTML, which can block cross-origin admin iframe previews.</comment>
<file context>
@@ -885,6 +970,8 @@ export function createDecoWorkerEntry(
return dressResponse(origin, "MISS");
}); // end RequestContext.run()
+
+ return applySecurityHeaders(response);
},
};
</file context>
| return applySecurityHeaders(response); | |
| if (new URL(request.url).pathname.startsWith("/live/previews")) { | |
| return response; | |
| } | |
| return applySecurityHeaders(response); |
| body = text.replaceAll(fallbackOrigin, url.hostname); | ||
| } | ||
|
|
||
| const rewritten = new Response(body, response); |
There was a problem hiding this comment.
P1: Stale Content-Length after body rewriting. When fallbackOrigin and url.hostname differ in length, replaceAll changes the body size but the original Content-Length header is copied verbatim into the new Response. This can cause clients to truncate or reject the response. Delete the header after construction so the runtime can recalculate it (or omit it for streaming).
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/sdk/abTesting.ts, line 253:
<comment>Stale `Content-Length` after body rewriting. When `fallbackOrigin` and `url.hostname` differ in length, `replaceAll` changes the body size but the original `Content-Length` header is copied verbatim into the new `Response`. This can cause clients to truncate or reject the response. Delete the header after construction so the runtime can recalculate it (or omit it for streaming).</comment>
<file context>
@@ -0,0 +1,398 @@
+ body = text.replaceAll(fallbackOrigin, url.hostname);
+ }
+
+ const rewritten = new Response(body, response);
+
+ const setCookies = response.headers.getSetCookie?.() ?? [];
</file context>
| } | ||
|
|
||
| // 7. Admin meta schema (lazy) | ||
| options.meta().then((data) => setMetaData(data)); |
There was a problem hiding this comment.
P2: Unhandled promise rejection — options.meta().then(…) has no .catch(). If the dynamic import fails, this surfaces as an unhandled rejection rather than a graceful degradation.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/setup.ts, line 175:
<comment>Unhandled promise rejection — `options.meta().then(…)` has no `.catch()`. If the dynamic import fails, this surfaces as an unhandled rejection rather than a graceful degradation.</comment>
<file context>
@@ -0,0 +1,192 @@
+ }
+
+ // 7. Admin meta schema (lazy)
+ options.meta().then((data) => setMetaData(data));
+
+ // 8. Render shell
</file context>
| export function StableOutlet() { | ||
| const isLoading = useRouterState({ select: (s) => s.isLoading }); | ||
| const ref = useRef<HTMLDivElement>(null); | ||
| const savedHeight = useRef<number | undefined>(undefined); |
There was a problem hiding this comment.
P2: savedHeight is stored in a ref but used for rendering; updating it won’t re-render, so minHeight may not be applied when loading starts. Use state for the rendered height value.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/hooks/StableOutlet.tsx, line 11:
<comment>`savedHeight` is stored in a ref but used for rendering; updating it won’t re-render, so `minHeight` may not be applied when loading starts. Use state for the rendered height value.</comment>
<file context>
@@ -0,0 +1,30 @@
+export function StableOutlet() {
+ const isLoading = useRouterState({ select: (s) => s.isLoading });
+ const ref = useRef<HTMLDivElement>(null);
+ const savedHeight = useRef<number | undefined>(undefined);
+
+ useEffect(() => {
</file context>
| if (needsSet) { | ||
| res.headers.append( | ||
| "set-cookie", | ||
| `${cookieName}=${bucket}:${now}; Path=/; Max-Age=${maxAge}; Domain=${hostname}; SameSite=Lax`, |
There was a problem hiding this comment.
P2: A/B bucket cookie is missing the Secure flag. Since this runs on Cloudflare Workers (HTTPS-only), add Secure to prevent the cookie from leaking over a non-HTTPS connection in edge cases (redirect chains, mixed-content, etc.).
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/sdk/abTesting.ts, line 204:
<comment>A/B bucket cookie is missing the `Secure` flag. Since this runs on Cloudflare Workers (HTTPS-only), add `Secure` to prevent the cookie from leaking over a non-HTTPS connection in edge cases (redirect chains, mixed-content, etc.).</comment>
<file context>
@@ -0,0 +1,398 @@
+ if (needsSet) {
+ res.headers.append(
+ "set-cookie",
+ `${cookieName}=${bucket}:${now}; Path=/; Max-Age=${maxAge}; Domain=${hostname}; SameSite=Lax`,
+ );
+ }
</file context>
BREAKING CHANGE: First stable release of @decocms/start. All existing 0.x APIs remain compatible, but the major version bump signals production readiness and a commitment to semver going forward. New in this release: - createSiteSetup, createDecoRouter, DecoRootLayout - withABTesting (KV-driven traffic split) - Security headers + geo cookie injection in createDecoWorkerEntry - generate-invoke script for automated server function generation Made-with: Cursor
Made-with: Cursor
|
🎉 This PR is included in version 1.0.0 🎉 The release is available on:
Your semantic-release bot 📦🚀 |
- #52: ctx is no longer always undefined (framework fixed via issue #305, landed before this PR); reframe Fix as ctx-free alternative, not mandatory - #61: discovery rg command had unbalanced parens and didn't compile; split into two valid rg calls - #63: filter checked "@type" (always "UnitPriceSpecification") instead of priceComponentType, so the trim silently matched nothing; fixed the field - #65: discovery step was prose, not a runnable command; added grep+jq pair - #66: v5-only gotcha wasn't flagged as such in an otherwise v4 file; added an applicability note - #72: fix had no code example unlike every other BLOCKER/HIGH gotcha; added one, correcting the import path typo present in the source JSDoc itself (@decocms/apps/vtex/... -> @decocms/apps-vtex/...) Co-Authored-By: Claude Sonnet 5 <[email protected]>
…rnings-staging convention (#457) ## Summary Consolidates the farmrio-storefront Fresh→TanStack migration's staged learnings (`migration/learnings/`, ~69 completed targets, coverage-verified against the live ledger) into this skill's reference docs, per the epic's own consolidation target (`T40`). 22 new numbered gotchas (**#52–#73**), each carrying Severity, Symptom, Root cause, Fix (with code), a discovery `rg`/`grep` command, and empirical farmrio evidence (file counts, byte deltas, before/after numbers, cross-refs). Distributed into the existing topic files rather than one new dump file, matching this repo's own index-per-topic convention: | File | New gotchas | Headline finding | |---|---|---| | `async-rendering.md` | #52–54, #73 | Dead 3-arg `ctx` section loaders — 28-file sweep, one was a site-wide dead cookie-consent banner | | `hydration-fixes.md` | #55–58 | `DeferredSectionWrapper` skeleton remount/CLS (cross-ref #448) + a content-refresh-safe `Lazy.tsx` unwrap pattern | | `vtex-commerce.md` | #59–64 | CMS multivariate-flag resolver only recognizes 2 of 7 real resolveTypes — silently drops content (blocker) | | `css-styling.md` | #65–67 | Theme-conversion DaisyUI slot mismapping + v5's silent dark-theme bundling | | `worker-cloudflare.md` | #68–71 | Device-segmented edge-cache poisoning via SWR revalidation (novel); server-only secrets reachable from client bundle via the invoke dispatch table (security) | | `storefront-patterns.md` | #72 | `sitemap.xml` not auto-wired | `references/migration-learnings-staging.md` (new file) proposes the index-per-target-file learnings convention as the **starting** pattern for the next migration's own staging area — citing this epic's own flat `LEARNINGS.md` (282,249 bytes / 3,875 lines / 103 entries, costing target sessions 60k+ tokens just to search before it was restructured mid-epic on 2026-07-30) as the empirical case for adopting it from day one instead. Linked from `SKILL.md`'s reference index. Two gotchas (#55, #59) reference upstream PRs/issues already filed from this same migration: **[#448](#448 (`DeferredSectionWrapper` fix, open) and **[#391](#391 (URL param coercion, referenced by #61). ## Codemod / audit-rule proposals for `packages/blocks-cli` Proposal only (per this migration's own DoD, implementation is a bonus, not required) — each was hit ≥3 times independently across the farmrio migration: 1. **Dead-arity section-loader detector** — AST walk for 3-arg `(props, req, ctx)` loader exports, cross-referenced against `registerSectionLoaders` calls and each file's real `__resolveType` (not its file path) in `blocks.gen.json`. Would have caught all 28 candidate files in gotcha #52 at migration time. 2. **`typeof X === "function"` guard sweep** — flag this pattern on any value that originates from CMS section resolution (gotcha #54); recurred independently in 6+ files across the epic. 3. **Controlled-input-missing-`onChange` sweep** — `checked={...}` JSX prop with no sibling `onChange` (gotcha #58); found and fixed independently 3 separate times. 4. **`LoadingFallback` wrapper-function → literal-alias codemod** — rewrite `export function LoadingFallback(props) { return <X {...props}/>; }` to `export const LoadingFallback = X;` (gotcha #56). 5. **Redirect self-loop lint rule** — flag any `blocks.gen.json` redirect block where `normalize(from) === normalize(to)` after case-folding (gotcha #60); found 3 live instances across 2 targets once the check existed as an ad-hoc script. 6. **Image-dimension backfill from source headers** — generic migration-time step parsing real JPEG/PNG dimensions from each unique image URL's own file header and writing `width`/`height` back into CMS content, instead of leaving every un-dimensioned image to hit the CLS-safety-net fallback one page at a time (gotcha #67). 7. **`deco-post-cleanup --strict` comment/string-literal awareness** — several existing audit rules (`deco-cx-runtime-api`, `style-string-props`, `htmx-residue`) are literal-substring scans with no AST/JSX awareness, so they false-positive on matches inside comments or inside a `dangerouslySetInnerHTML` HTML string. Farmrio counts: 7 comment-only false positives on one rule, 4 on another, 4-of-6 on a third. ## Parity-destined findings Filed separately against `decocms/parity` (issue, cross-linked from `migration/learnings/INDEX.md` in farmrio-storefront) rather than bundled into this PR — covers `--fail-on` requiring `--ci`, `--pages` not scoping `flows`, a `banner-aspect-ratio` check double-counting infinite-carousel clones, a `lazy-section-presence` heuristic incompatible with TanStack's transport, and LLM visual-diff hallucination on downscaled full-page screenshots. ## Test plan - [x] Docs-only change — no code paths affected, nothing to typecheck or build - [x] Every new gotcha cross-checked against the current `gotchas.md` numbering (#51 was the prior max, confirmed via `grep -rn "^## #\?[0-9]" *.md`) - [x] Every code snippet reproduced from the source learnings files, not invented — cross-checked against the cited `migration/learnings/T<ID>.md` file in `deco-sites/farmrio-storefront` 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated description by cubic. --> --- ## Summary by cubic Consolidates Farm Rio Fresh→TanStack migration learnings into this skill and adds 22 numbered gotchas (#52–#73). Also documents an index-per-target-file staging convention to keep future migrations fast and cheap. - Adds gotchas across async/rendering, hydration, VTEX commerce, CSS/DaisyUI, Worker/Cloudflare, and storefront patterns, covering issues like pre-`#305` 3‑arg loader pitfalls, `DeferredSectionWrapper` CLS, multivariate resolver gaps, sitemap wiring, cache behavior, and a client-bundle secret leak. Cross‑refs: `#448` and `#391`. - Introduces `references/migration-learnings-staging.md` and links it from `SKILL.md` to replace flat learnings with an index-per-target approach. **Doc updates since review** - #52: Clarifies that `@decocms/blocks` now supports an optional 3rd `ctx` arg when registered; positions the fix as a ctx‑free alternative for pre‑`#305` or unregistered loaders. - #61: Splits discovery into two valid `rg` commands. - #63: Corrects variant‑trim filter to use `priceComponentType` (not `@type`), ensuring installment entries are removed. - #65: Adds runnable discovery steps (`grep` + `jq`) for DaisyUI slot mapping. - #66: Flags the dark‑theme auto‑bundling gotcha as DaisyUI v5‑only. - #72: Adds a `worker-entry.ts` wiring example for `/sitemap.xml` and fixes the import path to `@decocms/apps-vtex`. <sup>Written for commit 919eb12. Summary will update on new commits.</sup> <a href="https://cubic.dev/pr/decocms/blocks/pull/457?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> --------- Co-authored-by: hugo-ccabral <[email protected]> Co-authored-by: Claude Sonnet 5 <[email protected]>
Summary
Extracts reusable framework infrastructure from casaevideo-storefront into
@decocms/startso that site repos can be lightweight (< 3,000 lines). Part of the Lightweight Site Template initiative (13 plans, 5 phases).What's new in this PR (9 commits):
createDecoRouter— URLSearchParams-based router factory replacing per-site boilerplateDecoRootLayout— composable root layout with theme, CSS, fonts, scripts, and SEOcreateSiteSetup— one-call site bootstrap (section registry, blocks, meta, fonts, platform init)generate-invokefix — handles double AsExpression + inputValidator, eliminates hand-written invoke.tswithABTesting— KV-driven traffic split wrapper with stable bucket assignment (FNV-1a), sticky cookies, circuit breaker, and fallback proxyingsecurityHeaders,csp, andautoInjectGeoCookiesoptions oncreateDecoWorkerEntry<meta name="robots">fixImpact
Test plan
npx tsc --noEmitpasses (0 new errors; 29 pre-existing in migration scripts)Made with Cursor
Summary by cubic
Extracted reusable framework pieces into
@decocms/startto power the lightweight site template, cutting ~1,600 lines of per-site boilerplate. Declares a stable 1.0 API with defaults for routing, layout, setup, A/B testing, and security.New Features
createDecoRouter: URLSearchParams-based search (keeps multi-value filters likefilter.brand), plusWrapandcontextsupport.DecoRootLayout: composable root layout withScriptOnce,LiveControls, analytics,NavigationProgress, andStableOutlet.createSiteSetup: one-call bootstrap for sections, blocks, meta, matchers, render shell, preview wrapper, and platform init.withABTesting: KV-driven traffic split with sticky cookies, FNV-1a hashing, circuit breaker, fallback proxy/rewrites, and path bypass.createDecoWorkerEntryoptions:securityHeaders,csp, andautoInjectGeoCookiesfor safer, geo-aware HTML responses.scripts/generate-invokeunwraps chainedasexpressions, uses.inputValidator(), exportsvtexActions, and re-exportsOrderForm.NavigationProgress,StableOutlet; added peer/peerDev for@tanstack/react-query.Bug Fixes
<meta name="robots">with index/follow defaults and rich-result directives.Written for commit e5a9e50. Summary will update on new commits.