@oktis-works/web 0.17.1 → 1.0.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/dist/rendering.js CHANGED
@@ -1,40 +1,14 @@
1
1
  // @oktis-works/web - Runtime Rendering (catch-all SSR com hierarquia de templates)
2
- import { existsSync, realpathSync } from 'node:fs';
2
+ import { realpathSync } from 'node:fs';
3
3
  import { createHash } from 'node:crypto';
4
- import { join, relative, resolve, sep } from 'node:path';
4
+ import { relative, resolve, sep } from 'node:path';
5
5
  import { pathToFileURL } from 'node:url';
6
6
  import { createRequire } from 'node:module';
7
7
  import { getConnection } from '@oktis-works/database';
8
8
  import { normalizeLogicalValues } from '@oktis-works/validation';
9
9
  import { getHookRegistry } from '@oktis-works/plugin-runtime';
10
10
  import { postTypeRegistry, HOOK_POINTS } from '@oktis-works/core';
11
- import { TemplateHierarchyResolver, RuntimeRouter, ThemeRenderer, createProjectTemplateResolver, resolveProjectThemeChain, loadThemeCatalog, findTemplateProvider, templateKeyFromFile, renderCompiledTheme, } from '@oktis-works/theme-runtime';
12
- import { CMS_VERSION } from '@oktis-works/validation';
13
- /**
14
- * B1/Unificação (FEAT-095): a cadeia de templates do projeto
15
- * (tema ativo → `_shared` → `default`), o saneamento dos nomes de tema e o
16
- * guard contra traversal vivem **apenas** no `@oktis-works/theme-runtime` —
17
- * este app só consome a fonte única, sem reimplementação local.
18
- */
19
- function projectTemplates(themesRoot, activeTheme) {
20
- return createProjectTemplateResolver(themesRoot, activeTheme);
21
- }
22
- /** Adaptador do checker do TemplateHierarchyResolver sobre o resolver único. */
23
- export function createTemplateChecker(themesRoot, activeTheme) {
24
- const resolver = projectTemplates(themesRoot, activeTheme);
25
- return {
26
- exists(file) {
27
- return resolver.exists(file);
28
- },
29
- };
30
- }
31
- /**
32
- * B1 — carrega o ARQUIVO do template do tema ativo (fallback _shared → default).
33
- * Retorna null quando nenhum candidato existe (rota cai no 404 do tema).
34
- */
35
- export function loadTemplateSource(themesRoot, activeTheme, file) {
36
- return projectTemplates(themesRoot, activeTheme).read(file);
37
- }
11
+ import { ThemeTemplateResolver, RuntimeRouter, loadThemeCatalog, findTemplateProvider, renderCompiledTheme, } from '@oktis-works/theme-runtime';
38
12
  export function toSiteSettings(raw) {
39
13
  return {
40
14
  siteTitle: toText(raw['siteTitle']) || 'OkCMS',
@@ -100,7 +74,6 @@ function toText(value) {
100
74
  return String(value);
101
75
  return '';
102
76
  }
103
- export const themeRenderer = new ThemeRenderer();
104
77
  /**
105
78
  * Deep merge two objects, with source overriding target.
106
79
  * Arrays are replaced, not merged.
@@ -141,13 +114,18 @@ function extractDefaults(settings) {
141
114
  * admin (exposto como `settings.theme` no contexto do template).
142
115
  * Suporta herança parent/child: parent defaults → child defaults → child config
143
116
  */
144
- export function buildThemeSettings(manifest, config, parentManifest) {
117
+ export function buildThemeSettings(manifest, config, parentManifest, parentConfigs) {
145
118
  let settings = {};
146
119
  // 1. Parent defaults (if parent theme exists)
147
120
  if (parentManifest) {
148
121
  const parents = Array.isArray(parentManifest) ? [...parentManifest].reverse() : [parentManifest];
149
- for (const parent of parents) {
122
+ for (let index = 0; index < parents.length; index += 1) {
123
+ const parent = parents[index];
150
124
  settings = deepMerge(settings, extractDefaults(parent['settings']));
125
+ const configForParent = parentConfigs?.[parents.length - 1 - index];
126
+ if (configForParent && typeof configForParent === 'object' && !Array.isArray(configForParent)) {
127
+ settings = deepMerge(settings, configForParent);
128
+ }
151
129
  }
152
130
  }
153
131
  // 2. Child theme defaults
@@ -165,7 +143,8 @@ export function buildThemeSettings(manifest, config, parentManifest) {
165
143
  */
166
144
  function prepareContentPage(input, file) {
167
145
  const row = input.contentRow ?? {};
168
- const logicalRecord = normalizeLogicalValues({ body: row['body'], data: row['data'], native: row });
146
+ const publicRow = publicContentRecord(row);
147
+ const logicalRecord = normalizeLogicalValues({ body: publicRow['body'], data: publicRow['data'], native: publicRow });
169
148
  const title = toText(row['title']) || input.settings.siteTitle;
170
149
  // E5 (FEAT-100): render/save hook surface for plugin-built editors.
171
150
  // `theme:before:render` filters the render data right before templating —
@@ -181,13 +160,14 @@ function prepareContentPage(input, file) {
181
160
  slug: input.resolution.slug ?? '',
182
161
  activeTheme: input.activeTheme,
183
162
  settings: input.settings,
184
- contentRow: { ...row, ...logicalRecord },
163
+ contentRow: { ...publicRow, ...logicalRecord },
185
164
  };
186
- const renderData = registry.applyFilters(HOOK_POINTS.THEME_BEFORE_RENDER, { ...input.data }, hookContext) ?? input.data;
165
+ const renderData = registry.applyFilters(HOOK_POINTS.THEME_BEFORE_RENDER, { ...logicalRecord, ...input.data }, hookContext) ?? input.data;
166
+ const publicRenderData = sanitizePublicValue(renderData);
187
167
  const themeRecord = normalizeLogicalValues({
188
- body: renderData,
189
- data: row['data'],
190
- native: row,
168
+ body: publicRenderData,
169
+ data: publicRow['data'],
170
+ native: publicRow,
191
171
  });
192
172
  const context = {
193
173
  site: {
@@ -210,8 +190,8 @@ function prepareContentPage(input, file) {
210
190
  isPageForPosts: input.resolution.isPageForPosts ?? false,
211
191
  isFrontPage: input.resolution.isFrontPage ?? false,
212
192
  },
213
- content: { ...plainColumns(row), ...renderData },
214
- fields: renderData,
193
+ content: { ...plainColumns(publicRow), ...publicRenderData },
194
+ fields: publicRenderData,
215
195
  record: themeRecord,
216
196
  items: input.items ?? [],
217
197
  pagination: input.pagination ?? { page: 1, perPage: 0, total: 0, pages: 0, hasPrevious: false, hasNext: false },
@@ -222,11 +202,13 @@ function prepareContentPage(input, file) {
222
202
  settings: { ...(input.themeData?.settings ?? {}), ...input.settings },
223
203
  themeData: input.themeData ?? { menus: { all: [], bySlug: {} }, contentTypes: [], taxonomies: [], terms: {}, settings: input.settings },
224
204
  };
225
- return { file, row, logicalRecord, title, registry, hookContext, renderData, themeRecord, context };
205
+ return { file, row: publicRow, logicalRecord, title, registry, hookContext, renderData: publicRenderData, themeRecord, context };
226
206
  }
227
207
  /** Wraps a rendered body in the document and runs the post-render hook. */
228
208
  function finalizeContentPage(input, prepared, body, themeAssets) {
229
- const stylesheet = themeAssets?.themeName ?? resolveThemeStylesheet(input.themesRoot, input.activeTheme);
209
+ // Compiled artifacts carry their own versioned stylesheet list. Linking the
210
+ // unversioned stable path as well would defeat cache versioning and may load a
211
+ // stale CSS generation.
230
212
  // Build canonical URL for SEO
231
213
  const canonicalPath = input.resolution.canonicalPath ?? '';
232
214
  const siteUrl = input.settings['siteUrl'] || '';
@@ -239,76 +221,66 @@ function finalizeContentPage(input, prepared, body, themeAssets) {
239
221
  const pageRobots = input.contentRow?.['seo_robots'] ?? undefined;
240
222
  const pageCanonical = input.contentRow?.['seo_canonical_url'] ?? undefined;
241
223
  const pageOgImage = input.contentRow?.['seo_og_image'] ?? undefined;
242
- const html = wrapDocument(body, prepared.title, input.settings, input.activeTheme, stylesheet, input.pluginAssets, {
224
+ const configuredOgImage = toText(input.settings['ogImage']) || undefined;
225
+ const html = wrapDocument(body, prepared.title, input.settings, input.activeTheme, input.pluginAssets, {
243
226
  canonicalUrl: pageCanonical ?? canonicalUrl,
244
227
  pageDescription,
245
228
  ogTitle: prepared.title,
246
229
  ogDescription: pageDescription,
247
- ogImage: pageOgImage ?? undefined,
230
+ ogImage: pageOgImage ?? configuredOgImage,
248
231
  ogType: input.settings['ogType'] ?? 'website',
249
232
  ogSiteName: input.settings.siteTitle,
250
233
  ogLocale: input.settings.language ?? 'pt-BR',
251
234
  twitterCard: input.settings['twitterCard'] ?? 'summary_large_image',
252
235
  twitterTitle: prepared.title,
253
236
  twitterDescription: pageDescription,
254
- twitterImage: pageOgImage ?? undefined,
237
+ twitterImage: pageOgImage ?? configuredOgImage,
255
238
  robots: pageRobots ?? input.settings['defaultRobots'] ?? 'index,follow',
256
239
  }, themeAssets);
257
240
  return prepared.registry.applyFilters(HOOK_POINTS.THEME_AFTER_RENDER, html, prepared.hookContext);
258
241
  }
259
- export function renderContentPage(input) {
260
- const file = input.resolution.template ?? 'index.astro';
261
- const template = loadTemplateSource(input.themesRoot, input.activeTheme, file);
262
- if (!template) {
263
- return renderFallbackPage(input, input.pluginAssets);
264
- }
265
- const prepared = prepareContentPage(input, file);
266
- const body = themeRenderer.wrapWithThemeScope(themeRenderer.renderString(template, prepared.context, { ...prepared.row, ...prepared.themeRecord }), input.activeTheme);
267
- return finalizeContentPage(input, prepared, body);
268
- }
269
242
  /**
270
- * Engine-aware render entry point. Template themes keep the synchronous
271
- * implementation above; React/Solid themes are imported from their build
272
- * artifact and rendered through the compiled adapter.
243
+ * Engine-aware render entry point. All themes are compiled React/Solid
244
+ * modules and are rendered through the explicit SDK bridge.
273
245
  */
274
246
  export async function renderContentPageAsync(input) {
275
247
  const catalog = loadThemeCatalog(input.themesRoot, input.activeTheme);
276
248
  const active = catalog.entries[0] ?? null;
277
- // No manifest or legacy template theme: preserve the existing path exactly.
278
- if (!active || active.engine === 'template') {
279
- return renderContentPage(input);
280
- }
249
+ if (!active)
250
+ throw new Error(`Active theme "${input.activeTheme}" was not found`);
281
251
  if (active.problems.length > 0) {
282
- throw new Error(`Theme "${active.name}" cannot render: ${active.problems.join('; ')}`);
252
+ throw new Error(`Active theme "${input.activeTheme}" is invalid: ${active.problems.join('; ')}`);
283
253
  }
284
- const file = input.resolution.template ?? 'index.astro';
285
- const requestedKey = templateKeyFromFile(file);
254
+ const requestedKey = input.resolution.template ?? 'index';
286
255
  const provider = findTemplateProvider(catalog, requestedKey, active.engine) ??
287
256
  findTemplateProvider(catalog, '404', active.engine);
288
- if (!provider?.build) {
289
- return renderFallbackPage(input, input.pluginAssets);
290
- }
257
+ if (!provider?.build)
258
+ throw new Error(`No compiled theme provides render key "${requestedKey}"`);
291
259
  if (provider.build.engine !== active.engine) {
292
260
  throw new Error(`Theme "${provider.name}" engine mismatch: theme.json says ${active.engine}, artifact says ${provider.build.engine}.`);
293
261
  }
294
262
  const templateKey = provider.build.templates.includes(requestedKey) ? requestedKey : '404';
295
- const prepared = prepareContentPage(input, file);
263
+ const prepared = prepareContentPage(input, requestedKey);
264
+ const styleAssets = catalog.entries
265
+ .filter((entry) => entry.problems.length === 0)
266
+ .flatMap((entry) => entry.build
267
+ ? [{ themeName: entry.name, styles: entry.build.styles, buildId: entry.build.buildId }]
268
+ : []);
296
269
  const output = await renderCompiledTheme({
297
270
  themeDir: provider.dir,
298
271
  build: provider.build,
299
272
  templateKey,
300
273
  data: prepared.context,
301
- // `getField()` (ALS) must see the same `theme:before:render` output as
302
- // the component props, not the pre-hook row.
274
+ // The bridge and component props must see the same post-hook public record,
275
+ // not the pre-hook storage row.
303
276
  record: {
304
- ...prepared.row,
305
277
  ...prepared.themeRecord,
306
278
  body: {
307
- ...(prepared.row['body'] ?? {}),
279
+ ...(prepared.themeRecord['body'] ?? {}),
308
280
  ...prepared.renderData,
309
281
  },
310
282
  data: {
311
- ...(prepared.row['data'] ?? {}),
283
+ ...(prepared.themeRecord['data'] ?? {}),
312
284
  ...prepared.renderData,
313
285
  },
314
286
  },
@@ -319,8 +291,10 @@ export async function renderContentPageAsync(input) {
319
291
  templateKey,
320
292
  buildId: provider.build.buildId,
321
293
  },
294
+ sdk: input.themeSdk,
295
+ automaticAssets: provider.build.hydration === 'islands' || styleAssets.some((asset) => asset.styles.length > 0),
322
296
  });
323
- const body = themeRenderer.wrapWithThemeScope(output.html, provider.name);
297
+ const body = output.html;
324
298
  const outputScripts = output.scripts ?? [];
325
299
  const scripts = outputScripts.length > 0
326
300
  ? outputScripts
@@ -329,7 +303,9 @@ export async function renderContentPageAsync(input) {
329
303
  : [];
330
304
  return finalizeContentPage(input, prepared, body, {
331
305
  themeName: provider.name,
306
+ buildId: provider.build.buildId,
332
307
  styles: output.styles,
308
+ styleAssets,
333
309
  head: output.head,
334
310
  scripts,
335
311
  hydration: provider.build.hydration === 'islands'
@@ -488,20 +464,6 @@ export async function renderPluginBlocks(blocks, catalog, pluginsRoot, patterns
488
464
  }
489
465
  return output.join('\n');
490
466
  }
491
- /**
492
- * Primeiro fornecedor real de `dist/theme.css` na cadeia (tema ativo →
493
- * _shared → default). `null` quando ninguém compilou estilos — o documento
494
- * sai sem <link> quebrado (nada de 404 silencioso no console).
495
- */
496
- export function resolveThemeStylesheet(themesRoot, activeTheme) {
497
- for (const theme of resolveProjectThemeChain(themesRoot, activeTheme)) {
498
- if (!theme)
499
- continue;
500
- if (existsSync(join(themesRoot, theme, 'dist', 'theme.css')))
501
- return theme;
502
- }
503
- return null;
504
- }
505
467
  /** Escapes JSON for an application/json script (never executable HTML). */
506
468
  export function serializeThemeHydration(payload) {
507
469
  return JSON.stringify(payload)
@@ -509,26 +471,34 @@ export function serializeThemeHydration(payload) {
509
471
  .replace(/>/g, '\\u003e')
510
472
  .replace(/&/g, '\\u0026');
511
473
  }
512
- export function wrapDocument(body, pageTitle, settings, activeTheme, stylesheetTheme = null, pluginAssets, seo, themeAssets) {
474
+ export function wrapDocument(body, pageTitle, settings, activeTheme, pluginAssets, seo, themeAssets) {
513
475
  if (body.includes('<html') || body.includes('<!DOCTYPE')) {
514
476
  return body;
515
477
  }
516
478
  const title = pageTitle && pageTitle !== settings.siteTitle ? `${pageTitle} | ${settings.siteTitle}` : settings.siteTitle;
517
479
  const lang = escapeHtml(settings.language || 'pt-BR');
518
- const stylesheet = stylesheetTheme
519
- ? ` <link rel="stylesheet" href="/themes/${escapeHtml(stylesheetTheme)}/dist/theme.css" data-theme-style="${escapeHtml(stylesheetTheme)}" />\n`
520
- : '';
521
480
  // Compiled themes may emit extra styles/scripts/head from their artifact.
522
- const extraStyles = themeAssets
523
- ? (themeAssets.styles ?? [])
524
- .filter((style) => style !== 'dist/theme.css')
525
- .map((style) => ` <link rel="stylesheet" href="/themes/${escapeHtml(themeAssets.themeName)}/${escapeHtml(style)}" data-theme-style="${escapeHtml(themeAssets.themeName)}" />`)
526
- .join('\n')
527
- : '';
481
+ const styleAssets = themeAssets
482
+ ? themeAssets.styleAssets ?? [{ themeName: themeAssets.themeName, styles: themeAssets.styles ?? [], buildId: themeAssets.buildId }]
483
+ : [];
484
+ const seenStyleAssets = new Set();
485
+ const extraStyles = styleAssets
486
+ .flatMap((asset) => asset.styles
487
+ .filter((style) => {
488
+ const key = `${asset.themeName}:${style}`;
489
+ if (seenStyleAssets.has(key))
490
+ return false;
491
+ seenStyleAssets.add(key);
492
+ return true;
493
+ })
494
+ .filter((style) => !(style === 'dist/theme.css' && asset.buildId))
495
+ .map((style) => ` <link rel="stylesheet" href="/themes/${escapeHtml(asset.themeName)}/${escapeHtml(style)}${asset.buildId ? `?v=${encodeURIComponent(asset.buildId)}` : ''}" data-theme-style="${escapeHtml(asset.themeName)}" />`))
496
+ .join('\n');
497
+ const compiledStyles = extraStyles ? `${extraStyles}\n` : '';
528
498
  const themeHead = themeAssets?.head ? `${themeAssets.head}\n` : '';
529
499
  const themeScripts = themeAssets
530
500
  ? (themeAssets.scripts ?? [])
531
- .map((script) => `<script type="module" src="/themes/${escapeHtml(themeAssets.themeName)}/${escapeHtml(script)}"></script>`)
501
+ .map((script) => `<script type="module" src="/themes/${escapeHtml(themeAssets.themeName)}/${escapeHtml(script)}${themeAssets.buildId ? `?v=${encodeURIComponent(themeAssets.buildId)}` : ''}"></script>`)
532
502
  .join('\n')
533
503
  : '';
534
504
  const hydrationScript = themeAssets?.hydration
@@ -546,7 +516,7 @@ export function wrapDocument(body, pageTitle, settings, activeTheme, stylesheetT
546
516
  // Open Graph defaults das settings
547
517
  const ogTitle = seo?.ogTitle ?? pageTitle ?? settings.siteTitle;
548
518
  const ogDescription = seo?.ogDescription ?? seo?.pageDescription ?? settings.siteDescription;
549
- const ogImage = seo?.ogImage ?? settings['siteUrl'] ? `${settings['siteUrl']}/logo.png` : '';
519
+ const ogImage = seo?.ogImage ?? (settings['siteUrl'] ? `${settings['siteUrl']}/logo.png` : '');
550
520
  const ogType = seo?.ogType ?? 'website';
551
521
  const ogSiteName = seo?.ogSiteName ?? settings.siteTitle;
552
522
  const ogLocale = seo?.ogLocale ?? settings.language ?? 'pt-BR';
@@ -591,14 +561,13 @@ export function wrapDocument(body, pageTitle, settings, activeTheme, stylesheetT
591
561
  <head>
592
562
  <meta charset="UTF-8">
593
563
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
594
- <meta name="generator" content="OkCMS ${CMS_VERSION}">
595
564
  <title>${escapeHtml(title)}</title>
596
565
  <meta name="description" content="${description}">
597
566
  ${robotsTag}
598
567
  ${canonicalTag}
599
568
  ${ogTags.join('\n')}
600
569
  ${twitterTags.join('\n')}
601
- ${seoMetaTags}${stylesheet}${extraStyles ? `${extraStyles}\n` : ''}${themeHead}${headInjections}${assetHead}</head> <body>
570
+ ${seoMetaTags}${compiledStyles}${themeHead}${headInjections}${assetHead}</head> <body>
602
571
  ${body}${assetFooter}${hydrationScript ? `\n${hydrationScript}` : ''}${themeScripts ? `\n${themeScripts}` : ''}
603
572
  </body>
604
573
  </html>`;
@@ -613,90 +582,30 @@ function plainColumns(row) {
613
582
  }
614
583
  return out;
615
584
  }
616
- /** Tema sem template para a rota: HTML mínimo com os dados reais (nunca stub). */
617
- function renderFallbackPage(input, pluginAssets) {
618
- const title = toText((input.contentRow ?? {})['title']) || input.settings.siteTitle;
619
- const lang = escapeHtml(input.settings.language || 'pt-BR');
620
- // SEO for fallback page
621
- const canonicalPath = input.resolution.canonicalPath ?? '';
622
- const siteUrl = input.settings['siteUrl'] || '';
623
- const canonicalUrl = canonicalPath && siteUrl ? new URL(canonicalPath, siteUrl).toString() : '';
624
- const pageDescription = (input.contentRow
625
- ? input.contentRow['seo_description'] ?? input.contentRow['excerpt']
626
- : undefined) ?? input.settings.siteDescription;
627
- const ogTitle = title;
628
- const ogDescription = pageDescription;
629
- const ogImage = '';
630
- const ogType = 'website';
631
- const ogSiteName = input.settings.siteTitle;
632
- const ogLocale = input.settings.language ?? 'pt-BR';
633
- const twitterCard = 'summary_large_image';
634
- const twitterTitle = ogTitle;
635
- const twitterDescription = ogDescription;
636
- const twitterImage = ogImage;
637
- const robotsDirective = input.settings['defaultRobots'] ?? 'index,follow';
638
- // WP6: ponto de extensão theme:head — plugins injetam tags no <head>
639
- const registry = getHookRegistry();
640
- const headInjections = registry.applyFilters(HOOK_POINTS.THEME_HEAD, '', { settings: input.settings, activeTheme: input.activeTheme });
641
- const seoMetaTags = String(registry.applyFilters('okcms.seo.meta.tags', '', { settings: input.settings, activeTheme: input.activeTheme, seo: undefined }));
642
- const assetHead = pluginAssets?.head ? `${pluginAssets.head}\n` : '';
643
- const assetFooter = pluginAssets?.footer ? `\n${pluginAssets.footer}` : '';
644
- const canonicalTag = canonicalUrl ? ` <link rel="canonical" href="${escapeHtml(canonicalUrl)}">\n` : '';
645
- const ogTags = [];
646
- if (ogTitle)
647
- ogTags.push(` <meta property="og:title" content="${escapeHtml(ogTitle)}">`);
648
- if (ogDescription)
649
- ogTags.push(` <meta property="og:description" content="${escapeHtml(ogDescription)}">`);
650
- if (ogImage)
651
- ogTags.push(` <meta property="og:image" content="${escapeHtml(ogImage)}">`);
652
- ogTags.push(` <meta property="og:type" content="${escapeHtml(ogType)}">`);
653
- if (ogSiteName)
654
- ogTags.push(` <meta property="og:site_name" content="${escapeHtml(ogSiteName)}">`);
655
- if (canonicalUrl)
656
- ogTags.push(` <meta property="og:url" content="${escapeHtml(canonicalUrl)}">`);
657
- ogTags.push(` <meta property="og:locale" content="${escapeHtml(ogLocale)}">`);
658
- const twitterTags = [];
659
- twitterTags.push(` <meta name="twitter:card" content="${escapeHtml(twitterCard)}">`);
660
- if (twitterTitle)
661
- twitterTags.push(` <meta name="twitter:title" content="${escapeHtml(twitterTitle)}">`);
662
- if (twitterDescription)
663
- twitterTags.push(` <meta name="twitter:description" content="${escapeHtml(twitterDescription)}">`);
664
- if (twitterImage)
665
- twitterTags.push(` <meta name="twitter:image" content="${escapeHtml(twitterImage)}">`);
666
- const robotsTag = ` <meta name="robots" content="${escapeHtml(robotsDirective)}">`;
667
- return `<!DOCTYPE html>
668
- <html lang="${lang}">
669
- <head>
670
- <meta charset="UTF-8">
671
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
672
- <title>${escapeHtml(title)} | ${escapeHtml(input.settings.siteTitle)}</title>
673
- <meta name="description" content="${escapeHtml(pageDescription)}">
674
- ${robotsTag}
675
- ${canonicalTag}
676
- ${ogTags.join('\n')}
677
- ${twitterTags.join('\n')}
678
- ${seoMetaTags}<style>
679
- body { font-family: system-ui, sans-serif; margin: 0; color: #111; }
680
- main { max-width: 46rem; margin: 0 auto; padding: 3rem 1.5rem; }
681
- .fallback__hint { color: #555; line-height: 1.5; }
682
- details { margin-top: 2rem; }
683
- summary { cursor: pointer; color: #555; }
684
- pre { background: #f5f5f5; border: 1px solid #e3e3e3; border-radius: 6px; padding: 1rem; overflow: auto; font-size: 0.85rem; }
685
- </style>
686
- ${headInjections}${assetHead}</head>
687
- <body>
688
- <main data-theme="${escapeHtml(input.activeTheme)}">
689
- <article>
690
- <h1>${escapeHtml(title)}</h1>
691
- <p class="fallback__hint">Este tema não possui template para esta rota — os dados reais do conteúdo estão abaixo.</p>
692
- <details>
693
- <summary>Dados (JSON)</summary>
694
- <pre>${escapeHtml(JSON.stringify(input.data, null, 2))}</pre>
695
- </details>
696
- </article>
697
- </main>${assetFooter}
698
- </body>
699
- </html>`;
585
+ const PRIVATE_CONTENT_COLUMNS = new Set([
586
+ 'tenant_id',
587
+ 'password_hash',
588
+ 'password_reset_token',
589
+ 'reset_token',
590
+ 'reset_token_expires_at',
591
+ 'session_token',
592
+ 'api_key',
593
+ 'secret',
594
+ ]);
595
+ const PRIVATE_CONTENT_KEY_RE = /(?:password|token|secret|api[_-]?key|private[_-]?key|credential|authorization|cookie|hash)/i;
596
+ /** Recursively removes credential-like keys before data reaches a theme. */
597
+ function sanitizePublicValue(value) {
598
+ if (Array.isArray(value))
599
+ return value.map(sanitizePublicValue);
600
+ if (!value || typeof value !== 'object')
601
+ return value;
602
+ return Object.fromEntries(Object.entries(value)
603
+ .filter(([key]) => !PRIVATE_CONTENT_COLUMNS.has(key) && !PRIVATE_CONTENT_KEY_RE.test(key))
604
+ .map(([key, child]) => [key, sanitizePublicValue(child)]));
605
+ }
606
+ /** Removes storage-only and credential fields from the public theme contract. */
607
+ function publicContentRecord(row) {
608
+ return sanitizePublicValue(row);
700
609
  }
701
610
  export function escapeHtml(value) {
702
611
  return value.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
@@ -983,20 +892,15 @@ export function createContentLookup() {
983
892
  };
984
893
  }
985
894
  export function createRouter(themesRoot, activeTheme) {
986
- const resolver = new TemplateHierarchyResolver(createTemplateChecker(themesRoot, activeTheme));
987
- return new RuntimeRouter(createContentLookup(), resolver);
988
- }
989
- /**
990
- * Registra o hook registry no Theme SDK para habilitar os filtros theme:data:*.
991
- * Awaited no boot do web — fire-and-forget deixava a janela inicial sem hooks.
992
- */
993
- export async function wireThemeHooks() {
994
- const sdk = await import('@oktis-works/theme-sdk');
995
- sdk.setThemeHooks({
996
- applyFilters: (filter, value, ...args) => getHookRegistry().applyFilters(filter, value, ...args),
997
- applyFiltersAsync: (filter, value, ...args) => getHookRegistry().applyFiltersAsync(filter, value, ...args),
895
+ const catalog = loadThemeCatalog(themesRoot, activeTheme);
896
+ const active = catalog.entries[0];
897
+ if (!active)
898
+ throw new Error(`Active theme "${activeTheme}" was not found`);
899
+ const resolver = new ThemeTemplateResolver({
900
+ has: (key) => catalog.entries.some((entry) => entry.engine === active.engine &&
901
+ entry.problems.length === 0 &&
902
+ entry.build?.templates.includes(key)),
998
903
  });
999
- // Ponto de extensão head: plugins podem injetar tags no <head> do site público.
1000
- void HOOK_POINTS;
904
+ return new RuntimeRouter(createContentLookup(), resolver);
1001
905
  }
1002
906
  //# sourceMappingURL=rendering.js.map