PB + Writer (#287)
* add pb models * api rules has updated to view public * pb setup is completed * add migrate script * add pb migrations * ignore storage * add pocketbase SDK dependency * change Tag.id and PageCardDto.id to string for PocketBase * add DocV1 content block types * add PB client singleton and PB record types * rewrite factory for PocketBase record types * rewrite api.ts for PocketBase SDK * remove unused Strapi files, add PB to config * mark Task 7 complete in plan * feat: verify build, tests, and lint pass with PocketBase API layer * move completed plan: 2026-04-06-pocketbase-api-layer.md * scaffold hudozka-writer with Vite 8, React 19, TS 5.9, Tiptap * add PocketBase client and DocV1 types to writer * add Login component for PocketBase superuser auth * add App shell with auth gate and page loader * add DocV1 <-> Tiptap serialization layer * mark Task 5 complete in writer redesign plan * add custom Tiptap nodes for DocV1 block types * add Tiptap editor with toolbar and save to PocketBase * add image picker with browse and upload * feat: verify writer build and complete integration task * move completed plan: 2026-04-06-hudozka-writer-redesign.md * add local env * rm textblock from writer * add writer editor improvements design spec * add writer editor improvements implementation plan * feat: use @tiptap/markdown for text block serialization * feat: add global markdown/rendered toggle * feat: add BlockMenu component for block type selection * feat: add hover + button for block insertion * feat: add slash commands for block insertion * feat: add interactive file block editor with FilePicker * feat: show resolved page titles in card grid block * move completed plan: 2026-04-07-writer-editor-improvements.md * writer ui improved * pages migration * spec: draft/publish workflow for hudozka-writer * spec: rename draft_doc to draft in spec * plan: writer draft/publish implementation * plan has moved * gitignores * plans upd * feat(writer): update PbPage type for draft/publish workflow * feat(writer): add save/publish/discard handlers with dirty tracking * feat(writer): add DraftBanner component * feat(writer): add Publish button and update toolbar layout * feat(writer): add published toggle and update duplicate for new schema * docs: mark manual verification steps as skipped in writer draft/publish plan * move completed plan: 20260407-writer-draft-publish.md * feat(writer): add BlockActions component for inline block menus * feat(writer): add draggable NodeViews for text blocks * feat(writer): use BlockActions in custom block NodeViews * feat(writer): replace floating BlockInsert with inline BlockActions * fix(writer): ensure all block wrappers have position: relative for BlockActions * chore: mark manual verification tasks as skipped in writer block actions plan * move completed plan: 20260408-writer-block-actions.md * writer update * refactor(writer): simplify BlockActions to always-visible delete + drag handle * feat(writer): add BlockInsert component for inserting blocks between nodes * feat(writer): redesign block sidebar with always-visible actions and insert button * move completed plan: 20260408-writer-block-actions-redesign.md * add spec: textblock container redesign for writer editor * feat(writer): add TextBlock container node definition * feat(writer): replace DraggableXxx wrappers with TextBlock container * feat(writer): update Editor extensions for TextBlock container * feat(writer): add split button to BlockActions for text blocks * feat(writer): update serialization for TextBlock container * feat(writer): update BlockMenu and SlashCommands for TextBlock * fix(writer): use Fragment.from() for replaceWith calls in BlockActions and SlashCommands * move completed plan: 20260408-textblock-container.md * add air
This commit is contained in:
1 parent
907298779c
commit
ed3f93de53
109 files changed
+40520
-427
No files matched your search
@@ -0,0 +1,27 @@
|
||||
import sharp from "sharp"
|
||||
|
||||
// Tiny jpeg base64 data URL for blur placeholder (matches src/remote/image.ts semantics).
|
||||
export async function encodeBlur(buffer: Buffer): Promise<string | undefined> {
|
||||
try {
|
||||
const data = await sharp(buffer)
|
||||
.resize(8, 8, { fit: "inside" })
|
||||
.jpeg({ quality: 50 })
|
||||
.toBuffer()
|
||||
return `data:image/jpeg;base64,${data.toString("base64")}`
|
||||
} catch (e) {
|
||||
console.warn("blur failed:", (e as Error).message)
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
export async function imageDims(buffer: Buffer): Promise<{ width: number, height: number } | undefined> {
|
||||
try {
|
||||
const meta = await sharp(buffer).metadata()
|
||||
if (meta.width && meta.height) {
|
||||
return { width: meta.width, height: meta.height }
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("dims failed:", (e as Error).message)
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
export async function download(url: string): Promise<Buffer> {
|
||||
const res = await fetch(url)
|
||||
if (!res.ok) {
|
||||
throw new Error(`download ${url} -> ${res.status}`)
|
||||
}
|
||||
const buf = await res.arrayBuffer()
|
||||
return Buffer.from(buf)
|
||||
}
|
||||
|
||||
export function basenameFromUrl(url: string): string {
|
||||
try {
|
||||
const u = new URL(url)
|
||||
const parts = u.pathname.split("/")
|
||||
const last = parts[parts.length - 1]
|
||||
return decodeURIComponent(last) || "file"
|
||||
} catch {
|
||||
return "file"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { createHash } from "node:crypto"
|
||||
|
||||
export function sha256(buffer: Buffer): string {
|
||||
return createHash("sha256").update(buffer).digest("hex")
|
||||
}
|
||||
@@ -0,0 +1,469 @@
|
||||
import PocketBase from "pocketbase"
|
||||
import { customAlphabet } from "nanoid"
|
||||
|
||||
const nanoid = customAlphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 10)
|
||||
import { readFileSync, writeFileSync, existsSync } from "node:fs"
|
||||
import type {
|
||||
StrapiComponent,
|
||||
StrapiMedia,
|
||||
StrapiPageCard,
|
||||
} from "./strapi.ts"
|
||||
import {
|
||||
fetchAllPages,
|
||||
fetchHome,
|
||||
fetchMenu,
|
||||
fetchTags,
|
||||
} from "./strapi.ts"
|
||||
import { download, basenameFromUrl } from "./download.ts"
|
||||
import { encodeBlur, imageDims } from "./blurhash.ts"
|
||||
import { sha256 } from "./hash.ts"
|
||||
|
||||
const STRAPI_URL = process.env.STRAPI_URL ?? "https://hudozka.tmshv.com"
|
||||
const POCKETBASE_URL = required("POCKETBASE_URL")
|
||||
const POCKETBASE_EMAIL = required("POCKETBASE_EMAIL")
|
||||
const POCKETBASE_PASSWORD = required("POCKETBASE_PASSWORD")
|
||||
|
||||
const STATE_FILE = new URL("../.migrate-state.json", import.meta.url).pathname
|
||||
const PHASES = ["tags", "images", "files", "pages", "rewrite", "kv"] as const
|
||||
type Phase = typeof PHASES[number]
|
||||
|
||||
function required(name: string): string {
|
||||
const v = process.env[name]
|
||||
if (!v) {
|
||||
throw new Error(`missing env ${name}`)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Content blocks written to pages.doc JSON. During pages phase, image/file/page refs
|
||||
// are strapi numeric ids; rewrite phase remaps them to PB string ids.
|
||||
type Ref = string | number
|
||||
type BlockBase = { id: string }
|
||||
type BlockText = BlockBase & { type: "text", text: string }
|
||||
type BlockImage = BlockBase & { type: "image", image: Ref, wide: boolean, caption: string }
|
||||
type BlockDocument = BlockBase & { type: "document", file: Ref, title: string }
|
||||
type BlockEmbed = BlockBase & { type: "embed", src: string }
|
||||
type CardRef = { page: Ref, layout: "small" | "medium" | "big" }
|
||||
type BlockCardGrid = BlockBase & { type: "card-grid", items: CardRef[] }
|
||||
type Block = BlockText | BlockImage | BlockDocument | BlockEmbed | BlockCardGrid
|
||||
|
||||
type DocContent = { version: 1, blocks: Block[] }
|
||||
|
||||
type State = {
|
||||
tagMap: Record<string, string>,
|
||||
imageMap: Record<string, string>,
|
||||
fileMap: Record<string, string>,
|
||||
pageMap: Record<string, string>,
|
||||
}
|
||||
|
||||
function loadState(): State {
|
||||
if (existsSync(STATE_FILE)) {
|
||||
const raw = readFileSync(STATE_FILE, "utf-8")
|
||||
return JSON.parse(raw) as State
|
||||
}
|
||||
return { tagMap: {}, imageMap: {}, fileMap: {}, pageMap: {} }
|
||||
}
|
||||
|
||||
function saveState(s: State) {
|
||||
writeFileSync(STATE_FILE, JSON.stringify(s, null, 2))
|
||||
}
|
||||
|
||||
function mapFromState(r: Record<string, string>): Map<number, string> {
|
||||
const m = new Map<number, string>()
|
||||
for (const [k, v] of Object.entries(r)) {
|
||||
m.set(Number(k), v)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
function mapToState(m: Map<number, string>): Record<string, string> {
|
||||
const r: Record<string, string> = {}
|
||||
for (const [k, v] of m) {
|
||||
r[String(k)] = v
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
function parsePhases(args: string[]): Phase[] {
|
||||
if (args.length === 0) return [...PHASES]
|
||||
const unknown = args.filter(a => !PHASES.includes(a as Phase))
|
||||
if (unknown.length > 0) {
|
||||
console.error(`unknown phase(s): ${unknown.join(", ")}`)
|
||||
console.error(`known phases: ${PHASES.join(", ")}`)
|
||||
process.exit(1)
|
||||
}
|
||||
return args as Phase[]
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const phases = parsePhases(process.argv.slice(2))
|
||||
console.log(`phases: ${phases.join(", ")}`)
|
||||
|
||||
const pb = new PocketBase(POCKETBASE_URL)
|
||||
await pb.collection("_superusers").authWithPassword(POCKETBASE_EMAIL, POCKETBASE_PASSWORD)
|
||||
console.log("authed to pb")
|
||||
|
||||
const state = loadState()
|
||||
const tagMap = mapFromState(state.tagMap)
|
||||
const imageMap = mapFromState(state.imageMap)
|
||||
const fileMap = mapFromState(state.fileMap)
|
||||
const pageMap = mapFromState(state.pageMap)
|
||||
console.log(`state: tags=${tagMap.size} images=${imageMap.size} files=${fileMap.size} pages=${pageMap.size}`)
|
||||
|
||||
console.log("\nfetching strapi...")
|
||||
const [strapiPages, strapiTags, strapiHome, strapiMenu] = await Promise.all([
|
||||
fetchAllPages(STRAPI_URL),
|
||||
fetchTags(STRAPI_URL),
|
||||
fetchHome(STRAPI_URL),
|
||||
fetchMenu(STRAPI_URL),
|
||||
])
|
||||
console.log(`strapi: pages=${strapiPages.length} tags=${strapiTags.length} home.cards=${strapiHome.cards.length} menu.items=${strapiMenu.menu.items.length}`)
|
||||
|
||||
// phase: tags
|
||||
if (phases.includes("tags")) {
|
||||
console.log(`\n[tags] creating ${strapiTags.length}...`)
|
||||
let ti = 0
|
||||
for (const t of strapiTags) {
|
||||
ti++
|
||||
const payload = { label: t.name, slug: t.slug }
|
||||
try {
|
||||
const rec = await pb.collection("tags").create(payload)
|
||||
tagMap.set(t.id, rec.id)
|
||||
console.log(` [${ti}/${strapiTags.length}] ${t.slug} -> ${rec.id}`)
|
||||
} catch (e) {
|
||||
console.error(` [${ti}/${strapiTags.length}] tag ${t.id} (${t.slug}) failed:`)
|
||||
printErr(e, payload)
|
||||
throw e
|
||||
}
|
||||
}
|
||||
state.tagMap = mapToState(tagMap)
|
||||
saveState(state)
|
||||
console.log(`[tags] done: ${tagMap.size}`)
|
||||
}
|
||||
|
||||
// phase: images
|
||||
if (phases.includes("images")) {
|
||||
const imageMedia = new Map<number, StrapiMedia>()
|
||||
for (const p of strapiPages) {
|
||||
if (p.cover) {
|
||||
imageMedia.set(p.cover.id, p.cover)
|
||||
}
|
||||
for (const c of p.content) {
|
||||
if (c.__component === "hudozka.image" && c.media) {
|
||||
imageMedia.set(c.media.id, c.media)
|
||||
}
|
||||
}
|
||||
}
|
||||
console.log(`\n[images] uploading ${imageMedia.size}...`)
|
||||
const imageHashIndex = await buildHashIndex(pb, "images")
|
||||
console.log(` sha256 index: ${imageHashIndex.size} existing records`)
|
||||
let ii = 0
|
||||
for (const [sid, m] of imageMedia) {
|
||||
ii++
|
||||
if (imageMap.has(sid)) {
|
||||
console.log(` [${ii}/${imageMedia.size}] ${m.name} — skip (already uploaded)`)
|
||||
continue
|
||||
}
|
||||
try {
|
||||
const buf = await download(m.url)
|
||||
const hash = sha256(buf)
|
||||
const existingId = imageHashIndex.get(hash)
|
||||
if (existingId) {
|
||||
imageMap.set(sid, existingId)
|
||||
console.log(` [${ii}/${imageMedia.size}] ${m.name} — dedup -> ${existingId}`)
|
||||
continue
|
||||
}
|
||||
const filename = m.name || basenameFromUrl(m.url)
|
||||
const dims = (m.width && m.height)
|
||||
? { width: m.width, height: m.height }
|
||||
: (await imageDims(buf) ?? { width: 0, height: 0 })
|
||||
const blur = await encodeBlur(buf)
|
||||
|
||||
const form = new FormData()
|
||||
form.append("file", new Blob([buf], { type: m.mime || "application/octet-stream" }), filename)
|
||||
if (m.alternativeText) form.append("alt", m.alternativeText)
|
||||
if (m.caption) form.append("caption", m.caption)
|
||||
form.append("width", String(dims.width))
|
||||
form.append("height", String(dims.height))
|
||||
if (blur) {
|
||||
form.append("blurhash", blur)
|
||||
} else {
|
||||
console.warn(` [blur] encode failed or empty`)
|
||||
}
|
||||
form.append("filename", filename)
|
||||
form.append("sha256", hash)
|
||||
|
||||
const rec = await pb.collection("images").create(form)
|
||||
imageMap.set(sid, rec.id)
|
||||
imageHashIndex.set(hash, rec.id)
|
||||
console.log(` [${ii}/${imageMedia.size}] ${filename} (${dims.width}x${dims.height}, ${Math.round(buf.byteLength / 1024)}KB, blur=${blur ? blur.length + "ch" : "none"}) -> ${rec.id}`)
|
||||
} catch (e) {
|
||||
console.error(` [${ii}/${imageMedia.size}] image ${sid} failed:`)
|
||||
console.error(` strapi media:`, JSON.stringify({
|
||||
id: m.id,
|
||||
name: m.name,
|
||||
mime: m.mime,
|
||||
ext: m.ext,
|
||||
sizeKB: m.size,
|
||||
width: m.width,
|
||||
height: m.height,
|
||||
url: m.url,
|
||||
}, null, 2))
|
||||
printErr(e)
|
||||
}
|
||||
}
|
||||
state.imageMap = mapToState(imageMap)
|
||||
saveState(state)
|
||||
console.log(`[images] done: ${imageMap.size}/${imageMedia.size}`)
|
||||
}
|
||||
|
||||
// phase: files
|
||||
if (phases.includes("files")) {
|
||||
const docMedia = new Map<number, { id: number, url: string, name: string, mime: string, size: number }>()
|
||||
for (const p of strapiPages) {
|
||||
for (const c of p.content) {
|
||||
if (c.__component === "hudozka.document" && c.media) {
|
||||
docMedia.set(c.media.id, {
|
||||
id: c.media.id,
|
||||
url: c.media.url,
|
||||
name: c.media.name,
|
||||
mime: c.media.mime,
|
||||
size: c.media.size,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
console.log(`\n[files] uploading ${docMedia.size}...`)
|
||||
const fileHashIndex = await buildHashIndex(pb, "files")
|
||||
console.log(` sha256 index: ${fileHashIndex.size} existing records`)
|
||||
let fi = 0
|
||||
for (const [sid, m] of docMedia) {
|
||||
fi++
|
||||
if (fileMap.has(sid)) {
|
||||
console.log(` [${fi}/${docMedia.size}] ${m.name} — skip (already uploaded)`)
|
||||
continue
|
||||
}
|
||||
try {
|
||||
const buf = await download(m.url)
|
||||
const hash = sha256(buf)
|
||||
const existingId = fileHashIndex.get(hash)
|
||||
if (existingId) {
|
||||
fileMap.set(sid, existingId)
|
||||
console.log(` [${fi}/${docMedia.size}] ${m.name} — dedup -> ${existingId}`)
|
||||
continue
|
||||
}
|
||||
const filename = m.name || basenameFromUrl(m.url)
|
||||
const bytes = buf.byteLength
|
||||
|
||||
const form = new FormData()
|
||||
form.append("file", new Blob([buf], { type: m.mime || "application/octet-stream" }), filename)
|
||||
form.append("title", "")
|
||||
if (m.mime) form.append("mime", m.mime)
|
||||
form.append("size", String(bytes))
|
||||
form.append("filename", filename)
|
||||
form.append("sha256", hash)
|
||||
|
||||
const rec = await pb.collection("files").create(form)
|
||||
fileMap.set(sid, rec.id)
|
||||
fileHashIndex.set(hash, rec.id)
|
||||
console.log(` [${fi}/${docMedia.size}] ${filename} (${Math.round(bytes / 1024)}KB) -> ${rec.id}`)
|
||||
} catch (e) {
|
||||
console.error(` [${fi}/${docMedia.size}] file ${sid} failed:`)
|
||||
printErr(e)
|
||||
}
|
||||
}
|
||||
state.fileMap = mapToState(fileMap)
|
||||
saveState(state)
|
||||
console.log(`[files] done: ${fileMap.size}/${docMedia.size}`)
|
||||
}
|
||||
|
||||
// phase: pages
|
||||
if (phases.includes("pages")) {
|
||||
console.log(`\n[pages] creating ${strapiPages.length}...`)
|
||||
let pi = 0
|
||||
for (const p of strapiPages) {
|
||||
pi++
|
||||
if (pageMap.has(p.id)) {
|
||||
console.log(` [${pi}/${strapiPages.length}] ${p.slug} — skip (already created)`)
|
||||
continue
|
||||
}
|
||||
const blocks = p.content.map(toBlock).filter((b): b is Block => b !== null)
|
||||
const doc: DocContent = { version: 1, blocks }
|
||||
const coverId = p.cover ? imageMap.get(p.cover.id) : undefined
|
||||
const tagIds = p.tags.map(t => tagMap.get(t.id)).filter((x): x is string => !!x)
|
||||
|
||||
const data: Record<string, unknown> = {
|
||||
title: p.title,
|
||||
slug: p.slug,
|
||||
excerpt: p.excerpt ?? "",
|
||||
doc,
|
||||
tags: tagIds,
|
||||
draft: false,
|
||||
}
|
||||
if (p.date) data.date = p.date
|
||||
if (coverId) data.cover = coverId
|
||||
|
||||
try {
|
||||
const rec = await pb.collection("pages").create(data)
|
||||
pageMap.set(p.id, rec.id)
|
||||
console.log(` [${pi}/${strapiPages.length}] ${p.slug} -> ${rec.id} (${blocks.length} blocks, ${tagIds.length} tags${coverId ? ", cover" : ""})`)
|
||||
} catch (e) {
|
||||
console.error(` [${pi}/${strapiPages.length}] page ${p.id} (${p.slug}) failed:`)
|
||||
printErr(e)
|
||||
}
|
||||
}
|
||||
state.pageMap = mapToState(pageMap)
|
||||
saveState(state)
|
||||
console.log(`[pages] done: ${pageMap.size}/${strapiPages.length}`)
|
||||
}
|
||||
|
||||
// phase: rewrite. Remaps strapi numeric refs -> PB string ids:
|
||||
// - doc blocks (image/file/card-grid)
|
||||
// - tags relation
|
||||
// Drops blocks with unresolved refs. Preserves nanoid block ids.
|
||||
if (phases.includes("rewrite")) {
|
||||
console.log(`\n[rewrite] remapping refs...`)
|
||||
let rewritten = 0
|
||||
let dropped = 0
|
||||
for (const p of strapiPages) {
|
||||
const pbId = pageMap.get(p.id)
|
||||
if (!pbId) continue
|
||||
|
||||
try {
|
||||
const rec = await pb.collection("pages").getOne(pbId, { fields: "doc" })
|
||||
const doc = (rec as unknown as { doc: DocContent }).doc
|
||||
const before = doc.blocks.length
|
||||
doc.blocks = doc.blocks.map(b => remapBlock(b, imageMap, fileMap, pageMap)).filter((b): b is Block => b !== null)
|
||||
dropped += before - doc.blocks.length
|
||||
|
||||
const tagIds = p.tags.map(t => tagMap.get(t.id)).filter((x): x is string => !!x)
|
||||
|
||||
await pb.collection("pages").update(pbId, { doc, tags: tagIds })
|
||||
rewritten++
|
||||
console.log(` rewrote ${p.slug} (${doc.blocks.length}/${before} blocks, ${tagIds.length} tags)`)
|
||||
} catch (e) {
|
||||
console.error(` rewrite page ${p.id} failed:`)
|
||||
printErr(e)
|
||||
}
|
||||
}
|
||||
console.log(`[rewrite] done: ${rewritten} pages, ${dropped} blocks dropped (unresolved refs)`)
|
||||
}
|
||||
|
||||
// phase: kv (home + menu)
|
||||
if (phases.includes("kv")) {
|
||||
console.log(`\n[kv] creating home + menu...`)
|
||||
const homeCards = strapiHome.cards
|
||||
.map(c => ({ page: pageMap.get(c.page.id), layout: c.layout }))
|
||||
.filter((c): c is { page: string, layout: "small" | "medium" | "big" } => !!c.page)
|
||||
|
||||
await pb.collection("kv").create({
|
||||
key: "home",
|
||||
data: { cards: homeCards },
|
||||
})
|
||||
console.log(`kv home: ${homeCards.length} cards`)
|
||||
|
||||
const menuItems = strapiMenu.menu.items
|
||||
.map(c => ({ page: pageMap.get(c.page.id) }))
|
||||
.filter((c): c is { page: string } => !!c.page)
|
||||
|
||||
await pb.collection("kv").create({
|
||||
key: "menu",
|
||||
data: {
|
||||
homeLabel: strapiMenu.homeLabel,
|
||||
items: menuItems,
|
||||
},
|
||||
})
|
||||
console.log(`kv menu: homeLabel="${strapiMenu.homeLabel}" items=${menuItems.length}`)
|
||||
}
|
||||
|
||||
console.log("\ndone.")
|
||||
}
|
||||
|
||||
// Emit blocks with strapi numeric ids for media/page refs.
|
||||
// The rewrite phase remaps them to PB string ids.
|
||||
function toBlock(c: StrapiComponent): Block | null {
|
||||
const id = nanoid()
|
||||
switch (c.__component) {
|
||||
case "hudozka.text":
|
||||
return { id, type: "text", text: c.text }
|
||||
case "hudozka.image":
|
||||
if (!c.media) return null
|
||||
return { id, type: "image", image: c.media.id, wide: !!c.wide, caption: c.caption ?? "" }
|
||||
case "hudozka.document":
|
||||
if (!c.media) return null
|
||||
return { id, type: "document", file: c.media.id, title: c.title ?? "" }
|
||||
case "hudozka.embed":
|
||||
return { id, type: "embed", src: c.src }
|
||||
case "hudozka.card-grid": {
|
||||
const items: CardRef[] = (c.items ?? [])
|
||||
.filter((it: StrapiPageCard) => it && it.page)
|
||||
.map((it: StrapiPageCard) => ({ page: it.page.id, layout: it.layout }))
|
||||
return { id, type: "card-grid", items }
|
||||
}
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// Remap strapi numeric refs -> PB string ids. Returns null if ref unresolved.
|
||||
// If ref is already a string, pass through (already remapped).
|
||||
function remapBlock(
|
||||
b: Block,
|
||||
imageMap: Map<number, string>,
|
||||
fileMap: Map<number, string>,
|
||||
pageMap: Map<number, string>,
|
||||
): Block | null {
|
||||
switch (b.type) {
|
||||
case "image": {
|
||||
if (typeof b.image === "string") return b
|
||||
const ref = imageMap.get(b.image)
|
||||
if (!ref) return null
|
||||
return { ...b, image: ref }
|
||||
}
|
||||
case "document": {
|
||||
if (typeof b.file === "string") return b
|
||||
const ref = fileMap.get(b.file)
|
||||
if (!ref) return null
|
||||
return { ...b, file: ref }
|
||||
}
|
||||
case "card-grid": {
|
||||
const items = b.items
|
||||
.map(it => {
|
||||
if (typeof it.page === "string") return it
|
||||
const mapped = pageMap.get(it.page)
|
||||
return mapped ? { page: mapped, layout: it.layout } : null
|
||||
})
|
||||
.filter((x): x is CardRef => x !== null)
|
||||
return { ...b, items }
|
||||
}
|
||||
default:
|
||||
return b
|
||||
}
|
||||
}
|
||||
|
||||
async function buildHashIndex(pb: PocketBase, collection: string): Promise<Map<string, string>> {
|
||||
const idx = new Map<string, string>()
|
||||
const recs = await pb.collection(collection).getFullList({ fields: "id,sha256" })
|
||||
for (const r of recs) {
|
||||
const h = (r as unknown as { sha256?: string }).sha256
|
||||
if (h) idx.set(h, r.id)
|
||||
}
|
||||
return idx
|
||||
}
|
||||
|
||||
function printErr(e: unknown, input?: unknown) {
|
||||
const err = e as { message?: string, url?: string, status?: number, response?: { data?: unknown } }
|
||||
console.error("ERROR:", err.message)
|
||||
if (err.url) console.error(" url:", err.url, "status:", err.status)
|
||||
if (input !== undefined) {
|
||||
console.error(" input:", JSON.stringify(input, null, 2))
|
||||
}
|
||||
if (err.response?.data !== undefined) {
|
||||
console.error(" response:", JSON.stringify(err.response.data, null, 2))
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(e => {
|
||||
printErr(e)
|
||||
process.exit(1)
|
||||
})
|
||||
@@ -0,0 +1,136 @@
|
||||
export type StrapiMediaObject = {
|
||||
url: string,
|
||||
name: string,
|
||||
hash: string,
|
||||
ext: string,
|
||||
mime: string,
|
||||
width: number,
|
||||
height: number,
|
||||
size: number,
|
||||
}
|
||||
|
||||
export type StrapiMedia = StrapiMediaObject & {
|
||||
id: number,
|
||||
alternativeText: string | null,
|
||||
caption: string | null,
|
||||
formats: null | {
|
||||
thumbnail: StrapiMediaObject,
|
||||
large: StrapiMediaObject,
|
||||
medium: StrapiMediaObject,
|
||||
small: StrapiMediaObject,
|
||||
},
|
||||
}
|
||||
|
||||
export type StrapiComponentText = {
|
||||
__component: "hudozka.text",
|
||||
id: number,
|
||||
text: string,
|
||||
}
|
||||
|
||||
export type StrapiComponentImage = {
|
||||
__component: "hudozka.image",
|
||||
id: number,
|
||||
wide: boolean,
|
||||
caption: string,
|
||||
media: StrapiMedia,
|
||||
}
|
||||
|
||||
export type StrapiComponentDocument = {
|
||||
__component: "hudozka.document",
|
||||
id: number,
|
||||
title: string,
|
||||
media: StrapiMediaObject & { id: number },
|
||||
}
|
||||
|
||||
export type StrapiComponentEmbed = {
|
||||
__component: "hudozka.embed",
|
||||
id: number,
|
||||
src: string,
|
||||
}
|
||||
|
||||
export type StrapiComponentCardGrid = {
|
||||
__component: "hudozka.card-grid",
|
||||
id: number,
|
||||
items: StrapiPageCard[],
|
||||
}
|
||||
|
||||
export type StrapiComponent =
|
||||
| StrapiComponentText
|
||||
| StrapiComponentImage
|
||||
| StrapiComponentDocument
|
||||
| StrapiComponentEmbed
|
||||
| StrapiComponentCardGrid
|
||||
|
||||
export type StrapiTag = {
|
||||
id: number,
|
||||
slug: string,
|
||||
name: string,
|
||||
}
|
||||
|
||||
export type StrapiPage = {
|
||||
id: number,
|
||||
title: string,
|
||||
excerpt: string,
|
||||
slug: string,
|
||||
date: string | null,
|
||||
cover?: StrapiMedia,
|
||||
published_at: string,
|
||||
created_at: string,
|
||||
updated_at: string,
|
||||
content: StrapiComponent[],
|
||||
tags: StrapiTag[],
|
||||
}
|
||||
|
||||
export type StrapiPageCard = {
|
||||
__component: "hudozka.page-card",
|
||||
id: number,
|
||||
page: StrapiPage,
|
||||
layout: "small" | "medium" | "big",
|
||||
}
|
||||
|
||||
export type StrapiHome = {
|
||||
id: number,
|
||||
title: string,
|
||||
cards: StrapiPageCard[],
|
||||
}
|
||||
|
||||
export type StrapiMenu = {
|
||||
id: number,
|
||||
homeLabel: string,
|
||||
menu: StrapiComponentCardGrid,
|
||||
}
|
||||
|
||||
async function get<T>(base: string, path: string): Promise<T> {
|
||||
const res = await fetch(`${base}${path}`)
|
||||
if (!res.ok) {
|
||||
throw new Error(`GET ${path} -> ${res.status}`)
|
||||
}
|
||||
return await res.json() as T
|
||||
}
|
||||
|
||||
export async function fetchAllPages(base: string): Promise<StrapiPage[]> {
|
||||
const limit = 100
|
||||
let start = 0
|
||||
const all: StrapiPage[] = []
|
||||
while (true) {
|
||||
const batch = await get<StrapiPage[]>(base, `/pages?_limit=${limit}&_start=${start}`)
|
||||
if (batch.length === 0) {
|
||||
break
|
||||
}
|
||||
all.push(...batch)
|
||||
start += limit
|
||||
}
|
||||
return all
|
||||
}
|
||||
|
||||
export async function fetchTags(base: string): Promise<StrapiTag[]> {
|
||||
return await get<StrapiTag[]>(base, "/tags")
|
||||
}
|
||||
|
||||
export async function fetchHome(base: string): Promise<StrapiHome> {
|
||||
return await get<StrapiHome>(base, "/home")
|
||||
}
|
||||
|
||||
export async function fetchMenu(base: string): Promise<StrapiMenu> {
|
||||
return await get<StrapiMenu>(base, "/menu")
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import PocketBase from "pocketbase"
|
||||
import { existsSync, readFileSync, writeFileSync } from "node:fs"
|
||||
|
||||
const STATE_FILE = new URL("../.migrate-state.json", import.meta.url).pathname
|
||||
const POCKETBASE_URL = required("POCKETBASE_URL")
|
||||
const POCKETBASE_EMAIL = required("POCKETBASE_EMAIL")
|
||||
const POCKETBASE_PASSWORD = required("POCKETBASE_PASSWORD")
|
||||
|
||||
const KNOWN = ["tags", "images", "files", "pages", "kv"] as const
|
||||
|
||||
function required(name: string): string {
|
||||
const v = process.env[name]
|
||||
if (!v) {
|
||||
throw new Error(`missing env ${name}`)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
async function wipe(pb: PocketBase, collection: string) {
|
||||
console.log(`\n[${collection}] wiping...`)
|
||||
let total = 0
|
||||
while (true) {
|
||||
const batch = await pb.collection(collection).getList(1, 200, { fields: "id" })
|
||||
if (batch.items.length === 0) {
|
||||
break
|
||||
}
|
||||
for (const rec of batch.items) {
|
||||
await pb.collection(collection).delete(rec.id)
|
||||
total++
|
||||
if (total % 20 === 0) {
|
||||
console.log(` [${collection}] deleted ${total}...`)
|
||||
}
|
||||
}
|
||||
}
|
||||
console.log(`[${collection}] done: ${total} deleted`)
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const args = process.argv.slice(2)
|
||||
const targets = args.length > 0 ? args : [...KNOWN]
|
||||
|
||||
const unknown = targets.filter(t => !KNOWN.includes(t as typeof KNOWN[number]))
|
||||
if (unknown.length > 0) {
|
||||
console.error(`unknown collections: ${unknown.join(", ")}`)
|
||||
console.error(`known: ${KNOWN.join(", ")}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const pb = new PocketBase(POCKETBASE_URL)
|
||||
await pb.collection("_superusers").authWithPassword(POCKETBASE_EMAIL, POCKETBASE_PASSWORD)
|
||||
console.log("authed to pb")
|
||||
console.log(`wiping: ${targets.join(", ")}`)
|
||||
|
||||
// Wipe pages first (references images/files/tags), then kv, then images/files/tags.
|
||||
const order = ["pages", "kv", "images", "files", "tags"]
|
||||
for (const c of order) {
|
||||
if (targets.includes(c)) {
|
||||
await wipe(pb, c)
|
||||
}
|
||||
}
|
||||
|
||||
// Sync state file: drop map for each wiped collection
|
||||
if (existsSync(STATE_FILE)) {
|
||||
const state = JSON.parse(readFileSync(STATE_FILE, "utf-8")) as Record<string, Record<string, string>>
|
||||
const keyFor: Record<string, string> = {
|
||||
tags: "tagMap",
|
||||
images: "imageMap",
|
||||
files: "fileMap",
|
||||
pages: "pageMap",
|
||||
}
|
||||
for (const t of targets) {
|
||||
const key = keyFor[t]
|
||||
if (key) state[key] = {}
|
||||
}
|
||||
writeFileSync(STATE_FILE, JSON.stringify(state, null, 2))
|
||||
console.log("\nstate file updated")
|
||||
}
|
||||
|
||||
console.log("\ndone.")
|
||||
}
|
||||
|
||||
main().catch(e => {
|
||||
const err = e as { message?: string, url?: string, status?: number, response?: { data?: unknown } }
|
||||
console.error("ERROR:", err.message)
|
||||
if (err.url) console.error(" url:", err.url, "status:", err.status)
|
||||
if (err.response?.data !== undefined) {
|
||||
console.error(" response:", JSON.stringify(err.response.data, null, 2))
|
||||
}
|
||||
process.exit(1)
|
||||
})
|
||||
Reference in new issue
Block a user