Initial commit: BlackDice site rebuild with integrated CMS
Rebuilds content management around a single admin route (/admin — "BlackDice Studio"), replacing blackdice-studio.html. Publishing writes one JSON content document instead of regenerating HTML files, so it can no longer overwrite hand-made site changes the way the old tool did. - /admin: click-to-edit copy/images, article CRUD with a Word-safe rich text editor, demo clip management, per-page SEO, enquiry log, publish history with rollback - Real per-page URLs for all pages and articles, each with its own meta/canonical/OG/JSON-LD - Newsroom + article pages driven by the CMS post library, seeded from the old studio's export (17 articles) plus a drafted GSMA Open Gateway press release awaiting approval - Demo sections on Mobile SDK and Halo CPE, interactive by default and upgradable to an uploaded clip per slot - Dependency-free Node API server (auth, publish, uploads, snapshots, leads, live sitemap) - Deployment configs for Node/nginx/IIS, Vercel and Netlify See docs/ARCHITECTURE.md, docs/PROJECT-STRUCTURE.md, docs/CMS-GUIDE.md and docs/DEPLOYMENT.md. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* Dev runner: starts the CMS API (server/index.mjs) and the Vite dev server
|
||||
* together, so /admin can publish while you work on the site.
|
||||
*
|
||||
* npm run dev → API on 8787, site on 5173 (or $PORT)
|
||||
* npm run dev:web → Vite only (site reads factory content)
|
||||
* npm run dev:api → API only
|
||||
*/
|
||||
import { spawn } from 'node:child_process'
|
||||
import path from 'node:path'
|
||||
|
||||
const ROOT = path.resolve(import.meta.dirname, '..')
|
||||
const API_PORT = process.env.API_PORT || '8787'
|
||||
|
||||
const children = []
|
||||
// Both processes are plain Node scripts, launched without a shell so paths with
|
||||
// spaces (C:\Program Files\nodejs\node.exe) are passed through intact.
|
||||
function run(name, args, env) {
|
||||
const child = spawn(process.execPath, args, {
|
||||
cwd: ROOT,
|
||||
stdio: ['ignore', 'inherit', 'inherit'],
|
||||
env: { ...process.env, ...env },
|
||||
})
|
||||
child.on('exit', (code) => {
|
||||
if (code) console.error(`[${name}] exited with ${code}`)
|
||||
shutdown()
|
||||
})
|
||||
children.push(child)
|
||||
return child
|
||||
}
|
||||
|
||||
let closing = false
|
||||
function shutdown() {
|
||||
if (closing) return
|
||||
closing = true
|
||||
for (const child of children) child.kill()
|
||||
}
|
||||
process.on('SIGINT', shutdown)
|
||||
process.on('SIGTERM', shutdown)
|
||||
|
||||
run('api', ['server/index.mjs'], { PORT: API_PORT })
|
||||
run('web', ['node_modules/vite/bin/vite.js'], { API_URL: `http://localhost:${API_PORT}` })
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Writes public/sitemap.xml and public/robots.txt from the content that will ship
|
||||
* in the build. The server also serves a live sitemap at /sitemap.xml (which picks
|
||||
* up articles published after the build); this static copy is the fallback for
|
||||
* static hosting and for crawlers hitting the file directly.
|
||||
*
|
||||
* node scripts/generate-sitemap.mjs [siteUrl]
|
||||
*/
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
const ROOT = path.resolve(import.meta.dirname, '..')
|
||||
const SITE_URL = (process.argv[2] || process.env.SITE_URL || 'https://www.blackdice.ai').replace(/\/+$/, '')
|
||||
|
||||
const PATHS = [
|
||||
['/', '1.0'], ['/mobile-sdk', '0.9'], ['/dns-protect', '0.9'], ['/halo-cpe', '0.9'],
|
||||
['/for-operators', '0.8'], ['/financial-services', '0.8'], ['/why-blackdice', '0.7'],
|
||||
['/news', '0.8'], ['/investors', '0.6'], ['/contact', '0.7'],
|
||||
]
|
||||
|
||||
const seed = JSON.parse(fs.readFileSync(path.join(ROOT, 'src/cms/generated/seedContent.json'), 'utf8'))
|
||||
const live = (() => {
|
||||
const file = path.join(ROOT, 'content/site-content.json')
|
||||
return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : null
|
||||
})()
|
||||
const posts = (live?.posts || seed.posts || []).filter((p) => p.status !== 'draft')
|
||||
|
||||
const today = new Date().toISOString().slice(0, 10)
|
||||
const urls = [
|
||||
...PATHS.map(([p, pri]) => ({ loc: SITE_URL + p, lastmod: today, pri })),
|
||||
...posts.map((p) => ({
|
||||
loc: `${SITE_URL}/blog/${p.slug}`,
|
||||
lastmod: (p.updatedAt || p.date || today).slice(0, 10),
|
||||
pri: '0.6',
|
||||
})),
|
||||
]
|
||||
|
||||
const xml =
|
||||
'<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n' +
|
||||
urls
|
||||
.map((u) => ` <url>\n <loc>${u.loc}</loc>\n <lastmod>${u.lastmod}</lastmod>\n <priority>${u.pri}</priority>\n </url>`)
|
||||
.join('\n') +
|
||||
'\n</urlset>\n'
|
||||
|
||||
fs.writeFileSync(path.join(ROOT, 'public/sitemap.xml'), xml)
|
||||
fs.writeFileSync(path.join(ROOT, 'public/robots.txt'), `User-agent: *\nAllow: /\n\nSitemap: ${SITE_URL}/sitemap.xml\n`)
|
||||
console.log(`sitemap.xml: ${urls.length} URLs (${posts.length} articles) → ${SITE_URL}`)
|
||||
@@ -0,0 +1,182 @@
|
||||
/**
|
||||
* Injects CMS editing hooks into src/site/siteMarkup.txt.
|
||||
*
|
||||
* data-cms="cNNNN" → editable rich text (the element's innerHTML)
|
||||
* data-cms-img="imgNNN" → replaceable image (the element's src)
|
||||
* data-cms-num="nNNN" → editable animated stat (the element's data-count/data-suffix)
|
||||
*
|
||||
* Idempotent: elements that already carry an attribute keep their id, and new ids
|
||||
* continue from the highest number already present. Re-run it after editing the
|
||||
* markup by hand: node scripts/inject-cms-ids.mjs
|
||||
*
|
||||
* Also writes src/cms/generated/cmsFields.json — the field manifest the admin uses
|
||||
* to list and jump to every editable region.
|
||||
*/
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
const ROOT = path.resolve(import.meta.dirname, '..')
|
||||
const MARKUP = path.join(ROOT, 'src/site/siteMarkup.txt')
|
||||
const MANIFEST = path.join(ROOT, 'src/cms/generated/cmsFields.json')
|
||||
|
||||
const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr'])
|
||||
// Never touch anything inside these — their internals are structural, not copy.
|
||||
const SKIP_SUBTREE = new Set(['svg', 'script', 'style', 'template', 'noscript'])
|
||||
// An element containing any of these is a container, not a text field: descend instead.
|
||||
const BLOCK = new Set([
|
||||
'div', 'section', 'article', 'aside', 'header', 'footer', 'nav', 'main',
|
||||
'ul', 'ol', 'li', 'dl', 'dt', 'dd', 'table', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th',
|
||||
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'form', 'figure', 'figcaption', 'blockquote',
|
||||
'video', 'iframe', 'canvas', 'select', 'textarea', 'input', 'button', 'svg',
|
||||
])
|
||||
// Text holders worth exposing as a field.
|
||||
const CANDIDATE = new Set([
|
||||
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'li', 'blockquote', 'cite', 'figcaption',
|
||||
'td', 'th', 'label', 'button', 'a', 'span', 'strong', 'em', 'small', 'dt', 'dd',
|
||||
'summary', 'div',
|
||||
])
|
||||
// Regions rewritten by the runtime (live threat feed, React mounts) — editing them
|
||||
// there would be silently discarded, so they are left alone.
|
||||
const SKIP_CLASS = /(?:^|\s)(?:feed-body|bd-mobile-demo-mount)(?:\s|$)/
|
||||
|
||||
const html = fs.readFileSync(MARKUP, 'utf8')
|
||||
|
||||
// ── Parse into a light tree with source offsets ────────────────────────────────
|
||||
const TOKEN = /<!--[\s\S]*?-->|<\/([a-zA-Z][\w:-]*)\s*>|<([a-zA-Z][\w:-]*)((?:"[^"]*"|'[^']*'|[^>"'])*?)(\/?)>/g
|
||||
|
||||
const root = { tag: '#root', children: [], parent: null, depth: 0 }
|
||||
const stack = [root]
|
||||
let last = 0
|
||||
let m
|
||||
while ((m = TOKEN.exec(html))) {
|
||||
if (html.slice(last, m.index).trim()) stack[stack.length - 1].hasText = true
|
||||
last = TOKEN.lastIndex
|
||||
const [, closeTag, openTag, attrs = '', selfClose] = m
|
||||
if (closeTag) {
|
||||
const tag = closeTag.toLowerCase()
|
||||
for (let i = stack.length - 1; i > 0; i--) {
|
||||
if (stack[i].tag === tag) {
|
||||
stack[i].contentEnd = m.index
|
||||
stack.length = i
|
||||
break
|
||||
}
|
||||
}
|
||||
} else if (openTag) {
|
||||
const tag = openTag.toLowerCase()
|
||||
const parent = stack[stack.length - 1]
|
||||
const node = {
|
||||
tag,
|
||||
attrs,
|
||||
nameEnd: m.index + 1 + openTag.length, // insertion point for new attributes
|
||||
contentStart: TOKEN.lastIndex,
|
||||
contentEnd: TOKEN.lastIndex,
|
||||
children: [],
|
||||
parent,
|
||||
hasText: false,
|
||||
}
|
||||
parent.children.push(node)
|
||||
if (!VOID.has(tag) && !selfClose) stack.push(node)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Existing ids (idempotency) ─────────────────────────────────────────────────
|
||||
const attrOf = (node, name) => {
|
||||
const hit = new RegExp(`${name}="([^"]*)"`).exec(node.attrs)
|
||||
return hit ? hit[1] : null
|
||||
}
|
||||
let maxText = 0, maxImg = 0, maxNum = 0
|
||||
const seen = { text: new Set(), img: new Set(), num: new Set() }
|
||||
const walkAll = (node, fn) => {
|
||||
fn(node)
|
||||
node.children.forEach((c) => walkAll(c, fn))
|
||||
}
|
||||
walkAll(root, (node) => {
|
||||
if (!node.attrs) return
|
||||
const t = attrOf(node, 'data-cms'), i = attrOf(node, 'data-cms-img'), n = attrOf(node, 'data-cms-num')
|
||||
if (t) { seen.text.add(t); maxText = Math.max(maxText, +t.slice(1) || 0) }
|
||||
if (i) { seen.img.add(i); maxImg = Math.max(maxImg, +i.slice(3) || 0) }
|
||||
if (n) { seen.num.add(n); maxNum = Math.max(maxNum, +n.slice(1) || 0) }
|
||||
})
|
||||
|
||||
// ── Decide what gets a hook ────────────────────────────────────────────────────
|
||||
const inserts = [] // { at, text }
|
||||
const fields = []
|
||||
|
||||
const textOf = (node) =>
|
||||
html.slice(node.contentStart, node.contentEnd).replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim()
|
||||
|
||||
const pageOf = (node) => {
|
||||
for (let p = node; p; p = p.parent) {
|
||||
const id = p.attrs ? attrOf(p, 'id') : null
|
||||
if (id && id.startsWith('pg-')) return id.slice(3)
|
||||
}
|
||||
return 'global'
|
||||
}
|
||||
|
||||
const hasBlockDescendant = (node) =>
|
||||
node.children.some((c) => BLOCK.has(c.tag) || hasBlockDescendant(c))
|
||||
|
||||
const hasTextDeep = (node) => node.hasText || node.children.some(hasTextDeep)
|
||||
|
||||
function visit(node, { skipping = false, claimed = false } = {}) {
|
||||
for (const child of node.children) {
|
||||
const cls = child.attrs ? attrOf(child, 'class') || '' : ''
|
||||
const skip = skipping || SKIP_SUBTREE.has(child.tag) || SKIP_CLASS.test(cls)
|
||||
|
||||
if (!skip) {
|
||||
if (child.tag === 'img') {
|
||||
let id = attrOf(child, 'data-cms-img')
|
||||
if (!id) {
|
||||
id = 'img' + String(++maxImg).padStart(3, '0')
|
||||
inserts.push({ at: child.nameEnd, text: ` data-cms-img="${id}"` })
|
||||
}
|
||||
fields.push({ id, kind: 'image', page: pageOf(child), tag: 'img', preview: attrOf(child, 'alt') || attrOf(child, 'src') || '' })
|
||||
continue
|
||||
}
|
||||
|
||||
const isStat = child.attrs && attrOf(child, 'data-count') !== null
|
||||
if (isStat) {
|
||||
let id = attrOf(child, 'data-cms-num')
|
||||
if (!id) {
|
||||
id = 'n' + String(++maxNum).padStart(3, '0')
|
||||
inserts.push({ at: child.nameEnd, text: ` data-cms-num="${id}"` })
|
||||
}
|
||||
fields.push({
|
||||
id, kind: 'number', page: pageOf(child), tag: child.tag,
|
||||
preview: (attrOf(child, 'data-count') || '') + (attrOf(child, 'data-suffix') || ''),
|
||||
})
|
||||
continue // the animated value is the field; its text node is not
|
||||
}
|
||||
|
||||
const editable =
|
||||
!claimed && CANDIDATE.has(child.tag) && hasTextDeep(child) && !hasBlockDescendant(child)
|
||||
if (editable) {
|
||||
let id = attrOf(child, 'data-cms')
|
||||
if (!id) {
|
||||
id = 'c' + String(++maxText).padStart(4, '0')
|
||||
inserts.push({ at: child.nameEnd, text: ` data-cms="${id}"` })
|
||||
}
|
||||
fields.push({ id, kind: 'text', page: pageOf(child), tag: child.tag, preview: textOf(child).slice(0, 140) })
|
||||
visit(child, { skipping: skip, claimed: true })
|
||||
continue
|
||||
}
|
||||
}
|
||||
visit(child, { skipping: skip, claimed })
|
||||
}
|
||||
}
|
||||
visit(root)
|
||||
|
||||
// ── Write ──────────────────────────────────────────────────────────────────────
|
||||
let out = html
|
||||
for (const ins of inserts.sort((a, b) => b.at - a.at)) {
|
||||
out = out.slice(0, ins.at) + ins.text + out.slice(ins.at)
|
||||
}
|
||||
fs.writeFileSync(MARKUP, out)
|
||||
fs.mkdirSync(path.dirname(MANIFEST), { recursive: true })
|
||||
fs.writeFileSync(MANIFEST, JSON.stringify(fields, null, 0) + '\n')
|
||||
|
||||
const byKind = (k) => fields.filter((f) => f.kind === k).length
|
||||
console.log(
|
||||
`siteMarkup.txt: +${inserts.length} new hooks (${fields.length} fields total — ` +
|
||||
`${byKind('text')} text, ${byKind('image')} image, ${byKind('number')} stat)`,
|
||||
)
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* Downscales JPEG/PNG files in place — used by scripts/seed-content.mjs after it
|
||||
* extracts the base64 heroes out of a studio export (some originals are 8000px
|
||||
* wide and 12MB).
|
||||
*
|
||||
* node scripts/resize-images.mjs <dir> [maxWidth] [quality]
|
||||
*
|
||||
* Uses Windows' own imaging stack via PowerShell so the repo needs no native
|
||||
* image dependency. On other platforms it reports what it would have resized —
|
||||
* images uploaded through /admin are downscaled in the browser instead, so this
|
||||
* only affects the one-off import.
|
||||
*/
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
export function resizeDirectory(dir, maxWidth = 1600, quality = 82) {
|
||||
if (!fs.existsSync(dir)) return
|
||||
const files = fs.readdirSync(dir).filter((f) => /\.(jpe?g|png)$/i.test(f))
|
||||
const oversized = files.filter((f) => fs.statSync(path.join(dir, f)).size > 600 * 1024)
|
||||
if (!oversized.length) return
|
||||
|
||||
if (process.platform !== 'win32') {
|
||||
console.warn(
|
||||
` ! ${oversized.length} large image(s) in ${dir} were left as-is (resizing needs Windows imaging). ` +
|
||||
'Optimise them before deploying.',
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
const script = `
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
$enc = [System.Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() | Where-Object { $_.MimeType -eq 'image/jpeg' }
|
||||
$ps = New-Object System.Drawing.Imaging.EncoderParameters 1
|
||||
$ps.Param[0] = New-Object System.Drawing.Imaging.EncoderParameter([System.Drawing.Imaging.Encoder]::Quality, ${quality})
|
||||
Get-ChildItem -LiteralPath '${dir.replace(/'/g, "''")}' -Include *.jpg,*.jpeg,*.png -File -Recurse | ForEach-Object {
|
||||
$img = [System.Drawing.Image]::FromFile($_.FullName)
|
||||
if ($img.Width -le ${maxWidth}) { $img.Dispose(); return }
|
||||
$scale = ${maxWidth} / [double]$img.Width
|
||||
$nw = [int]($img.Width * $scale); $nh = [int]($img.Height * $scale)
|
||||
$bmp = New-Object System.Drawing.Bitmap $nw, $nh
|
||||
$g = [System.Drawing.Graphics]::FromImage($bmp)
|
||||
$g.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
|
||||
$g.DrawImage($img, 0, 0, $nw, $nh)
|
||||
$g.Dispose(); $img.Dispose()
|
||||
$tmp = $_.FullName + '.tmp'
|
||||
$bmp.Save($tmp, $enc, $ps); $bmp.Dispose()
|
||||
Move-Item -Force $tmp $_.FullName
|
||||
Write-Output (" resized {0} -> {1}px, {2}KB" -f $_.Name, $nw, [int]((Get-Item $_.FullName).Length/1KB))
|
||||
}`
|
||||
|
||||
try {
|
||||
const out = execFileSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', script], { encoding: 'utf8' })
|
||||
if (out.trim()) console.log(out.trimEnd())
|
||||
} catch (err) {
|
||||
console.warn(` ! image resize failed: ${err.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
// Standalone use
|
||||
if (process.argv[1] && import.meta.url.endsWith(path.basename(process.argv[1]))) {
|
||||
const [dir, max, quality] = process.argv.slice(2)
|
||||
if (!dir) {
|
||||
console.error('usage: node scripts/resize-images.mjs <dir> [maxWidth] [quality]')
|
||||
process.exit(1)
|
||||
}
|
||||
resizeDirectory(path.resolve(dir), Number(max) || 1600, Number(quality) || 82)
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
/**
|
||||
* Imports a blackdice-studio draft (blackdice-studio.json / any exported draft)
|
||||
* into this project's content model.
|
||||
*
|
||||
* node scripts/seed-content.mjs <path-to-blackdice-studio.json> [--content-dir <dir>]
|
||||
*
|
||||
* · base64 hero images are written out as real files under public/content/posts/
|
||||
* (the studio inlined them, which is what made its files 27MB)
|
||||
* · Word-pasted article bodies are sanitised down to semantic HTML so they inherit
|
||||
* the site's typography instead of carrying Aptos/black-on-dark inline styles
|
||||
* · the result is written to src/cms/generated/seedContent.json — the factory
|
||||
* content the site falls back to when nothing has been published yet
|
||||
*/
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { resizeDirectory } from './resize-images.mjs'
|
||||
|
||||
const ROOT = path.resolve(import.meta.dirname, '..')
|
||||
const OUT = path.join(ROOT, 'src/cms/generated/seedContent.json')
|
||||
const HERO_DIR = path.join(ROOT, 'public/content/posts')
|
||||
|
||||
const args = process.argv.slice(2)
|
||||
const src = args.find((a) => !a.startsWith('--'))
|
||||
if (!src) {
|
||||
console.error('usage: node scripts/seed-content.mjs <path-to-blackdice-studio.json>')
|
||||
process.exit(1)
|
||||
}
|
||||
const contentDirIdx = args.indexOf('--content-dir')
|
||||
const studioContentDir = contentDirIdx > -1 ? args[contentDirIdx + 1] : path.join(path.dirname(src), 'content')
|
||||
|
||||
// ── Body sanitiser ─────────────────────────────────────────────────────────────
|
||||
// Word/Outlook paste carries inline styles that fight the site's design system.
|
||||
// Keep the structure, drop the decoration.
|
||||
const KEEP_TAGS = new Set([
|
||||
'h2', 'h3', 'h4', 'p', 'ul', 'ol', 'li', 'strong', 'em', 'b', 'i', 'u', 'a', 'br',
|
||||
'blockquote', 'img', 'figure', 'figcaption', 'table', 'thead', 'tbody', 'tr', 'td', 'th', 'hr',
|
||||
])
|
||||
const UNWRAP_TAGS = new Set(['span', 'div', 'font', 'section', 'article', 'o:p', 'st1:place', 'header', 'main'])
|
||||
const KEEP_ATTRS = { a: ['href'], img: ['src', 'alt'] }
|
||||
|
||||
function sanitiseBody(html) {
|
||||
let s = String(html || '')
|
||||
s = s.replace(/<!--[\s\S]*?-->/g, '')
|
||||
s = s.replace(/<\/?o:p[^>]*>/gi, '')
|
||||
s = s.replace(/<\/?(?:xml|style|script)[^>]*>[\s\S]*?<\/(?:xml|style|script)>/gi, '')
|
||||
// h1 in a body would compete with the page title
|
||||
s = s.replace(/<(\/?)h1\b/gi, '<$1h2')
|
||||
s = s.replace(/<(\/?)b\b/gi, '<$1strong').replace(/<(\/?)i\b/gi, '<$1em')
|
||||
|
||||
s = s.replace(/<(\/?)([a-zA-Z][\w:-]*)((?:"[^"]*"|'[^']*'|[^>"'])*?)(\/?)>/g, (_m, close, rawTag, attrs, selfClose) => {
|
||||
const tag = rawTag.toLowerCase()
|
||||
if (UNWRAP_TAGS.has(tag)) return ''
|
||||
if (!KEEP_TAGS.has(tag)) return ''
|
||||
if (close) return `</${tag}>`
|
||||
const keep = KEEP_ATTRS[tag] || []
|
||||
const kept = keep
|
||||
.map((name) => {
|
||||
const hit = new RegExp(`${name}\\s*=\\s*"([^"]*)"`, 'i').exec(attrs)
|
||||
return hit ? ` ${name}="${hit[1].trim()}"` : ''
|
||||
})
|
||||
.join('')
|
||||
const rel = tag === 'a' && /href\s*=\s*"https?:/i.test(attrs) ? ' target="_blank" rel="noopener"' : ''
|
||||
return `<${tag}${kept}${rel}${selfClose ? ' /' : ''}>`
|
||||
})
|
||||
|
||||
s = s.replace(/ /g, ' ')
|
||||
// Empty blocks left behind by unwrapping
|
||||
for (let i = 0; i < 4; i++) {
|
||||
s = s.replace(/<(p|h2|h3|h4|li|strong|em|u|blockquote)>\s*(?:<br\s*\/?>)*\s*<\/\1>/gi, '')
|
||||
}
|
||||
s = s.replace(/(<br\s*\/?>\s*){3,}/gi, '<br /><br />')
|
||||
s = s.replace(/[ \t]+/g, ' ').replace(/\s*\n\s*/g, '\n').trim()
|
||||
return s
|
||||
}
|
||||
|
||||
const excerptOf = (post) =>
|
||||
(post.excerpt || sanitiseBody(post.body).replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 260)).trim()
|
||||
|
||||
// ── Hero extraction ────────────────────────────────────────────────────────────
|
||||
const EXT = { 'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp', 'image/gif': 'gif', 'image/svg+xml': 'svg' }
|
||||
|
||||
function extractHero(post) {
|
||||
const hero = String(post.hero || '').trim()
|
||||
if (!hero) return ''
|
||||
if (/^https?:\/\//i.test(hero)) return hero
|
||||
const dataUrl = /^data:([^;]+);base64,(.*)$/s.exec(hero)
|
||||
if (dataUrl) {
|
||||
const ext = EXT[dataUrl[1].toLowerCase()] || 'bin'
|
||||
const file = `${post.slug}.${ext}`
|
||||
fs.mkdirSync(HERO_DIR, { recursive: true })
|
||||
fs.writeFileSync(path.join(HERO_DIR, file), Buffer.from(dataUrl[2], 'base64'))
|
||||
return `/content/posts/${file}`
|
||||
}
|
||||
// A studio "content/<file>" reference — copy it across if we were given the folder.
|
||||
const rel = hero.replace(/^\.?\/*/, '').replace(/^content\//, '')
|
||||
const from = path.join(studioContentDir, rel)
|
||||
if (fs.existsSync(from)) {
|
||||
fs.mkdirSync(HERO_DIR, { recursive: true })
|
||||
const file = `${post.slug}${path.extname(rel) || '.jpg'}`
|
||||
fs.copyFileSync(from, path.join(HERO_DIR, file))
|
||||
return `/content/posts/${file}`
|
||||
}
|
||||
console.warn(` ! hero not found for ${post.slug}: ${hero} — left empty`)
|
||||
return ''
|
||||
}
|
||||
|
||||
// ── Run ────────────────────────────────────────────────────────────────────────
|
||||
const draft = JSON.parse(fs.readFileSync(src, 'utf8'))
|
||||
if (!/^blackdice-(studio|cms)-draft$/.test(draft.format || '')) {
|
||||
console.warn(`warning: unexpected format "${draft.format}" — importing anyway`)
|
||||
}
|
||||
|
||||
// Posts authored in this repo rather than in the studio export (e.g. releases
|
||||
// prepared ahead of approval). They survive a re-import, and any slug clash is
|
||||
// resolved in their favour.
|
||||
const EXTRA = path.join(ROOT, 'content-seed/additional-posts.json')
|
||||
const extraPosts = fs.existsSync(EXTRA) ? JSON.parse(fs.readFileSync(EXTRA, 'utf8')) : []
|
||||
|
||||
const posts = (draft.posts || []).map((p) => ({
|
||||
id: p.slug,
|
||||
slug: p.slug,
|
||||
title: p.title || 'Untitled',
|
||||
category: ['insights', 'news', 'press', 'events'].includes(p.category) ? p.category : 'insights',
|
||||
date: (p.date || '').slice(0, 10),
|
||||
author: p.author || 'BlackDice Cyber',
|
||||
excerpt: excerptOf(p),
|
||||
hero: extractHero(p),
|
||||
body: sanitiseBody(p.body),
|
||||
status: 'published',
|
||||
updatedAt: draft.savedAt || new Date().toISOString(),
|
||||
}))
|
||||
|
||||
for (const extra of extraPosts) {
|
||||
const at = posts.findIndex((p) => p.slug === extra.slug)
|
||||
const normalised = { status: 'draft', author: 'BlackDice Cyber', hero: '', ...extra, id: extra.id || extra.slug }
|
||||
if (at > -1) posts[at] = normalised
|
||||
else posts.push(normalised)
|
||||
}
|
||||
posts.sort((a, b) => (a.date < b.date ? 1 : -1))
|
||||
|
||||
const seed = {
|
||||
format: 'blackdice-react-content',
|
||||
version: 1,
|
||||
savedAt: draft.savedAt || new Date().toISOString(),
|
||||
content: draft.content || {},
|
||||
images: draft.images || {},
|
||||
numbers: {},
|
||||
posts,
|
||||
}
|
||||
|
||||
fs.mkdirSync(path.dirname(OUT), { recursive: true })
|
||||
fs.writeFileSync(OUT, JSON.stringify(seed, null, 2) + '\n')
|
||||
|
||||
// The studio inlined originals straight off a camera; serve something sensible.
|
||||
resizeDirectory(HERO_DIR)
|
||||
|
||||
const kb = (n) => (n / 1024).toFixed(0) + 'KB'
|
||||
console.log(`imported ${posts.length} posts → ${path.relative(ROOT, OUT)} (${kb(fs.statSync(OUT).size)})`)
|
||||
for (const p of posts) {
|
||||
console.log(` ${p.date} ${p.category.padEnd(8)} ${kb(p.body.length).padStart(6)} ${p.hero ? 'hero' : ' '} ${p.slug}`)
|
||||
}
|
||||
Reference in New Issue
Block a user