Skip to content

refactor: deduplicate shared utils, add registry extensibility APIs - #13

Merged
vibe-dex merged 1 commit into
mainfrom
vibe-dex/check-knowledge
Mar 16, 2026
Merged

vibe-dex merged 1 commit into
mainfrom
vibe-dex/check-knowledge

Conversation

@vibe-dex

@vibe-dex vibe-dex commented Mar 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • DJB2 hash deduplication: Extracted into src/sdk/djb2.ts, replacing 4 duplicate implementations across loader.ts, meta.ts, sectionLoaders.ts, and DecoPageRenderer.tsx
  • HTML shell deduplication: Extracted into src/sdk/htmlShell.ts, replacing duplicate implementations in workerEntry.ts and admin/render.ts
  • WELL_KNOWN_TYPES constants: Replaced ~15 scattered __resolveType string literals in resolve.ts with a single constant object
  • Registry extensibility APIs: Added register* functions for bot patterns, admin CORS origins, cache profiles, tracking params, redirect resolve types, country mappings, and sitemap options — allowing consumers to extend framework behavior without forking
  • Matcher registry unification: Built-in matchers (always, never, device, random, date) now self-register through the same registerMatcher() API as custom matchers, replacing the hardcoded switch
  • UA regex unification: MOBILE_RE/TABLET_RE/isMobileUA() consolidated in useDevice.ts, imported by requestContext.ts and workerEntry.ts
  • Neutral defaults: setup.ts defaults changed from pt-BR/light/bg-base-100 to en/empty — site-specific values belong in site config

Test plan

  • Verify npm run typecheck passes (only pre-existing peer dep errors)
  • Verify admin preview renders correctly (HTML shell changes)
  • Verify edge caching still works (cache profile changes are additive)
  • Verify matchers work in CMS page resolution (registry unification)
  • Verify DJB2 ETag hashing matches previous behavior (same algorithm, just moved)

🤖 Generated with Claude Code


Summary by cubic

Refactored shared utils (DJB2, HTML shell) and introduced extensibility APIs for bots, CORS, cache, tracking, redirects, country mapping, and sitemap. Unified matcher registration and device detection, and exported well-known resolve types for safer CMS resolution.

  • New Features

    • Extensibility: registerBotPattern, registerAdminOrigin(s), setCacheProfileConfig, setRouteCacheDefaults, registerTrackingParam(s), registerRedirectResolveType, registerCountryMapping(s)
    • Configurable sitemap defaults via CMSSitemapOptions
    • Built-in matchers now self-register through registerMatcher; exported WELL_KNOWN_TYPES
  • Refactors

    • Deduplicated DJB2 hashing (src/sdk/djb2.ts) and HTML shell builder (src/sdk/htmlShell.ts)
    • Unified UA handling in useDevice (MOBILE_RE, TABLET_RE, isMobileUA) and adopted in requestContext and workerEntry
    • Replaced scattered __resolveType literals with WELL_KNOWN_TYPES; neutral defaults in admin/setup.ts; added preload error warnings in registry

Written for commit 1e5eb05. Summary will update on new commits.

- Extract DJB2 hash into shared src/sdk/djb2.ts (was duplicated in 4 files)
- Extract HTML shell builder into src/sdk/htmlShell.ts (was duplicated in workerEntry + render)
- Add WELL_KNOWN_TYPES constants for __resolveType string literals in resolve.ts
- Convert built-in matchers from hardcoded switch to self-registering registry
- Add registerBotPattern() for extensible bot detection
- Add registerAdminOrigin(s)() for extensible CORS origins
- Add setCacheProfileConfig/setRouteCacheDefaults for extensible cache profiles
- Add registerTrackingParam(s)() for extensible URL tracking param stripping
- Add registerRedirectResolveType() for extensible redirect resolution
- Add registerCountryMapping(s)() for extensible country name→code mapping
- Add CMSSitemapOptions for configurable sitemap generation
- Unify MOBILE_RE/TABLET_RE/isMobileUA across useDevice, requestContext, workerEntry
- Neutralize setup.ts defaults (lang="en", no theme/bodyClass hardcoded)
- Add console.warn to silent catches in registry.ts preload functions

Co-Authored-By: Claude Opus 4.6 <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

6 issues found across 22 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/admin/cors.ts">

<violation number="1" location="src/admin/cors.ts:35">
P1: Match the parsed request origin exactly; `startsWith()` lets attacker-controlled domains like `https://admin.deco.cx.evil.com` pass the admin allowlist.</violation>
</file>

<file name="src/sdk/cacheHeaders.ts">

<violation number="1" location="src/sdk/cacheHeaders.ts:198">
P2: `setRouteCacheDefaults()` is ineffective in development because `routeCacheDefaults()` returns hardcoded dev values instead of the overridden profile.</violation>
</file>

<file name="src/cms/index.ts">

<violation number="1" location="src/cms/index.ts:51">
P3: Avoid re-exporting `WELL_KNOWN_TYPES` from the public CMS barrel; it is marked internal in `resolve.ts` and would become a supported public API here.</violation>
</file>

<file name="src/sdk/htmlShell.ts">

<violation number="1" location="src/sdk/htmlShell.ts:25">
P1: Always emit a fallback `data-theme="light"` for the preview shell. Omitting the attribute breaks DaisyUI v4 color variables when no site theme is configured.</violation>
</file>

<file name="src/matchers/countryNames.ts">

<violation number="1" location="src/matchers/countryNames.ts:103">
P2: Normalize each code in bulk registration; otherwise `resolveCountryCode()` can start returning invalid lowercase/padded ISO codes for custom entries.</violation>
</file>

<file name="src/cms/resolve.ts">

<violation number="1" location="src/cms/resolve.ts:114">
P1: Store custom bot patterns on `globalThis`; the current module-local array can lose registrations across split server modules.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

Comment thread src/admin/cors.ts
}

return ADMIN_ORIGINS.some((domain) => origin.startsWith(domain));
for (const domain of ADMIN_ORIGINS) {

@cubic-dev-ai cubic-dev-ai Bot Mar 16, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: Match the parsed request origin exactly; startsWith() lets attacker-controlled domains like https://admin.deco.cx.evil.com pass the admin allowlist.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/admin/cors.ts, line 35:

<comment>Match the parsed request origin exactly; `startsWith()` lets attacker-controlled domains like `https://admin.deco.cx.evil.com` pass the admin allowlist.</comment>

<file context>
@@ -15,7 +32,10 @@ export function isAdminOrLocalhost(request: Request): boolean {
   }
 
-  return ADMIN_ORIGINS.some((domain) => origin.startsWith(domain));
+  for (const domain of ADMIN_ORIGINS) {
+    if (origin.startsWith(domain)) return true;
+  }
</file context>
Fix with Cubic

Comment thread src/sdk/htmlShell.ts
export function buildHtmlShell(options: HtmlShellOptions = {}): string {
const { cssHref, fontHrefs, themeName, bodyClass, htmlLang } = getRenderShellConfig();

const themeAttr = themeName ? ` data-theme="${themeName}"` : "";

@cubic-dev-ai cubic-dev-ai Bot Mar 16, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: Always emit a fallback data-theme="light" for the preview shell. Omitting the attribute breaks DaisyUI v4 color variables when no site theme is configured.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/sdk/htmlShell.ts, line 25:

<comment>Always emit a fallback `data-theme="light"` for the preview shell. Omitting the attribute breaks DaisyUI v4 color variables when no site theme is configured.</comment>

<file context>
@@ -0,0 +1,55 @@
+export function buildHtmlShell(options: HtmlShellOptions = {}): string {
+  const { cssHref, fontHrefs, themeName, bodyClass, htmlLang } = getRenderShellConfig();
+
+  const themeAttr = themeName ? ` data-theme="${themeName}"` : "";
+  const langAttr = htmlLang ? ` lang="${htmlLang}"` : "";
+  const bodyAttr = bodyClass ? ` class="${bodyClass}"` : "";
</file context>
Fix with Cubic

Comment thread src/cms/resolve.ts
Comment on lines +114 to +116
const botPatterns: RegExp[] = [
/bot|crawl|spider|slurp|facebookexternalhit|mediapartners|google|bing|yandex|baidu|duckduck|teoma|ia_archiver|semrush|ahrefs|lighthouse/i,
];

@cubic-dev-ai cubic-dev-ai Bot Mar 16, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: Store custom bot patterns on globalThis; the current module-local array can lose registrations across split server modules.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/cms/resolve.ts, line 114:

<comment>Store custom bot patterns on `globalThis`; the current module-local array can lose registrations across split server modules.</comment>

<file context>
@@ -93,12 +111,21 @@ export function getAsyncRenderingConfig(): AsyncRenderingConfig | null {
 
-const BOT_UA_RE =
-  /bot|crawl|spider|slurp|facebookexternalhit|mediapartners|google|bing|yandex|baidu|duckduck|teoma|ia_archiver|semrush|ahrefs|lighthouse/i;
+const botPatterns: RegExp[] = [
+  /bot|crawl|spider|slurp|facebookexternalhit|mediapartners|google|bing|yandex|baidu|duckduck|teoma|ia_archiver|semrush|ahrefs|lighthouse/i,
+];
</file context>
Suggested change
const botPatterns: RegExp[] = [
/bot|crawl|spider|slurp|facebookexternalhit|mediapartners|google|bing|yandex|baidu|duckduck|teoma|ia_archiver|semrush|ahrefs|lighthouse/i,
];
const botPatterns: RegExp[] = G.__deco.botPatterns ??= [
/bot|crawl|spider|slurp|facebookexternalhit|mediapartners|google|bing|yandex|baidu|duckduck|teoma|ia_archiver|semrush|ahrefs|lighthouse/i,
];
Fix with Cubic

Comment thread src/sdk/cacheHeaders.ts
* setRouteCacheDefaults("product", { staleTime: 120_000, gcTime: 10 * 60_000 });
* ```
*/
export function setRouteCacheDefaults(profile: CacheProfile, defaults: RouteCacheDefaults): void {

@cubic-dev-ai cubic-dev-ai Bot Mar 16, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: setRouteCacheDefaults() is ineffective in development because routeCacheDefaults() returns hardcoded dev values instead of the overridden profile.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/sdk/cacheHeaders.ts, line 198:

<comment>`setRouteCacheDefaults()` is ineffective in development because `routeCacheDefaults()` returns hardcoded dev values instead of the overridden profile.</comment>

<file context>
@@ -173,6 +187,18 @@ export function routeCacheDefaults(profile: CacheProfile): RouteCacheDefaults {
+ * setRouteCacheDefaults("product", { staleTime: 120_000, gcTime: 10 * 60_000 });
+ * ```
+ */
+export function setRouteCacheDefaults(profile: CacheProfile, defaults: RouteCacheDefaults): void {
+  ROUTE_CACHE[profile] = defaults;
+}
</file context>
Fix with Cubic

* Register multiple country name → ISO code mappings at once.
*/
export function registerCountryMappings(mappings: Record<string, string>): void {
Object.assign(COUNTRY_NAME_TO_CODE, mappings);

@cubic-dev-ai cubic-dev-ai Bot Mar 16, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Normalize each code in bulk registration; otherwise resolveCountryCode() can start returning invalid lowercase/padded ISO codes for custom entries.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/matchers/countryNames.ts, line 103:

<comment>Normalize each code in bulk registration; otherwise `resolveCountryCode()` can start returning invalid lowercase/padded ISO codes for custom entries.</comment>

<file context>
@@ -87,3 +87,18 @@ export function resolveCountryCode(name: string): string {
+ * Register multiple country name → ISO code mappings at once.
+ */
+export function registerCountryMappings(mappings: Record<string, string>): void {
+  Object.assign(COUNTRY_NAME_TO_CODE, mappings);
+}
</file context>
Suggested change
Object.assign(COUNTRY_NAME_TO_CODE, mappings);
Object.assign(
COUNTRY_NAME_TO_CODE,
Object.fromEntries(
Object.entries(mappings).map(([name, value]) => [name, value.trim().toUpperCase()]),
),
);
Fix with Cubic

Comment thread src/cms/index.ts
setAsyncRenderingConfig,
setDanglingReferenceHandler,
setResolveErrorHandler,
WELL_KNOWN_TYPES,

@cubic-dev-ai cubic-dev-ai Bot Mar 16, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: Avoid re-exporting WELL_KNOWN_TYPES from the public CMS barrel; it is marked internal in resolve.ts and would become a supported public API here.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/cms/index.ts, line 51:

<comment>Avoid re-exporting `WELL_KNOWN_TYPES` from the public CMS barrel; it is marked internal in `resolve.ts` and would become a supported public API here.</comment>

<file context>
@@ -47,6 +48,7 @@ export {
   setAsyncRenderingConfig,
   setDanglingReferenceHandler,
   setResolveErrorHandler,
+  WELL_KNOWN_TYPES,
 } from "./resolve";
 export type { SectionLoaderFn } from "./sectionLoaders";
</file context>
Fix with Cubic

@vibe-dex
vibe-dex merged commit e528749 into main Mar 16, 2026
1 check passed
@github-actions

Copy link
Copy Markdown

🎉 This PR is included in version 0.23.1 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant