@contentrain/wp-import 0.6.0 → 0.7.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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["iso"],"sources":["../src/php-unserialize.ts","../src/core.ts","../src/wxr.ts","../src/rest.ts","../src/contentrain.ts","../src/comments.ts","../src/delta.ts"],"sourcesContent":["// Small PHP serialize() decoder, ported from the measured import chain.\n// Supported: s (byte-length strings), i, d, b, N, a (array → list or object), O (object → { __class, … }).\n// PHP string lengths are BYTES, so the walk happens over a Buffer, not a JS string.\n\nexport interface UnserializeResult {\n ok: boolean\n serialized: boolean\n value: unknown\n error?: string\n}\n\nexport function looksSerialized(s: unknown): s is string {\n return typeof s === 'string' && /^(a|O):\\d+:[{\"]|^(s|i|d|b):[^;]+;?$|^N;$/.test(s)\n}\n\nexport function phpUnserialize(str: string): unknown {\n const buf = Buffer.from(str, 'utf8')\n let p = 0\n const fail = (m: string): never => {\n throw new Error(`unserialize: ${m} at byte ${p}`)\n }\n const readUntil = (ch: string): string => {\n const i = buf.indexOf(ch, p)\n if (i < 0) fail(`expected ${ch}`)\n const s = buf.toString('utf8', p, i)\n p = i + 1\n return s\n }\n const expect = (ch: string): void => {\n if (buf[p] !== ch.charCodeAt(0)) fail(`expected '${ch}' got '${String.fromCharCode(buf[p] ?? 0)}'`)\n p++\n }\n const value = (): unknown => {\n const t = String.fromCharCode(buf[p] ?? 0)\n p++\n switch (t) {\n case 'N':\n expect(';')\n return null\n case 'b': {\n expect(':')\n return readUntil(';') === '1'\n }\n case 'i': {\n expect(':')\n return Number(readUntil(';'))\n }\n case 'd': {\n expect(':')\n const v = readUntil(';')\n return v === 'INF' ? Infinity : v === '-INF' ? -Infinity : v === 'NAN' ? Number.NaN : Number(v)\n }\n case 's': {\n expect(':')\n const n = Number(readUntil(':'))\n expect('\"')\n const s = buf.toString('utf8', p, p + n)\n p += n\n expect('\"')\n expect(';')\n return s\n }\n case 'a': {\n expect(':')\n const n = Number(readUntil(':'))\n expect('{')\n const entries: Array<[unknown, unknown]> = []\n for (let i = 0; i < n; i++) {\n const k = value()\n const v = value()\n entries.push([k, v])\n }\n expect('}')\n // consecutive 0..n-1 integer keys → JSON list; anything else → object\n const isList = entries.every(([k], i) => k === i)\n return isList ? entries.map(([, v]) => v) : Object.fromEntries(entries.map(([k, v]) => [String(k), v]))\n }\n case 'O': {\n expect(':')\n readUntil(':')\n expect('\"')\n const cls = readUntil('\"')\n expect(':')\n const n = Number(readUntil(':'))\n expect('{')\n const o: Record<string, unknown> = { __class: cls }\n for (let i = 0; i < n; i++) {\n const k = value()\n const v = value()\n o[String(k).split('\\u0000').at(-1) ?? String(k)] = v\n }\n expect('}')\n return o\n }\n default:\n return fail(`unknown type '${t}'`)\n }\n }\n const v = value()\n if (p !== buf.length) fail(`trailing ${buf.length - p} bytes`)\n return v\n}\n\n/** Attempt a decode; on failure the value stays exactly as it was. */\nexport function tryUnserialize(s: string): UnserializeResult {\n if (!looksSerialized(s)) return { ok: false, serialized: false, value: s }\n try {\n return { ok: true, serialized: true, value: phpUnserialize(s) }\n } catch (e) {\n return { ok: false, serialized: true, value: s, error: e instanceof Error ? e.message : String(e) }\n }\n}\n","// Shared conversion helpers, ported from the measured induction core.\n// The identity formulas here are load-bearing: hexId('posts:' + slug) must\n// produce the same entry id whether the site arrived via WXR or REST, or a\n// later delta import would duplicate every entry.\n\nimport { createHash } from 'node:crypto'\nimport type { FieldDef } from '@contentrain/types'\n\nexport const norm = (s: unknown): string => String(s ?? '').replace(/\\s+/g, ' ').trim()\n\nexport const strip = (s: unknown): string =>\n norm(\n String(s ?? '')\n .replace(/<[^>]*>/g, ' ')\n .replace(/&#(\\d+);/g, (_m, d: string) => String.fromCodePoint(Number(d)))\n .replace(/&amp;/g, '&'),\n )\n\n/** Entry id: deterministic hex from a stable key (model:slug style). */\nexport const hexId = (s: string): string => createHash('sha1').update(s).digest('hex').slice(0, 24)\n\nconst sortDeep = (v: unknown): unknown =>\n Array.isArray(v)\n ? v.map(sortDeep)\n : v && typeof v === 'object'\n ? Object.fromEntries(\n Object.keys(v as Record<string, unknown>)\n .toSorted()\n .map((k) => [k, sortDeep((v as Record<string, unknown>)[k])]),\n )\n : v\n\n/** Canonical serialization: sorted keys, 2-space indent, trailing newline. */\nexport const canon = (o: unknown): string => `${JSON.stringify(sortDeep(o), null, 2)}\\n`\n\n/** Field-type inference from a value (open meta / ACF fields). */\nexport const byValue = (v: unknown): string | null => {\n if (typeof v === 'boolean') return 'boolean'\n if (typeof v === 'number') return Number.isInteger(v) ? 'integer' : 'decimal'\n if (Array.isArray(v)) return 'array'\n if (v && typeof v === 'object') return 'object'\n const s = String(v ?? '').trim()\n if (!s) return null\n if (/^https?:\\/\\/\\S+\\.(mp3|m4a|wav|pdf|zip|docx?)(\\?|$)/i.test(s)) return 'file'\n if (/^https?:\\/\\/\\S+\\.(jpe?g|png|gif|webp|avif|svg)(\\?|$)/i.test(s)) return 'image'\n if (/^https?:\\/\\//.test(s)) return 'url'\n if (/^[^@\\s]+@[^@\\s]+\\.[a-z]{2,}$/i.test(s)) return 'email'\n if (/^\\d{4}-\\d{2}-\\d{2}([T ]\\d{2}:\\d{2})/.test(s)) return 'datetime'\n if (/<[a-z][\\s\\S]*>/i.test(s)) return 'richtext'\n return s.length > 200 ? 'text' : 'string'\n}\n\n/** What `RawPost.password` holds for a protected post: the fact, never the password. */\nexport const PROTECTED = '[protected]'\n\n/**\n * WP post types that never become content models: core plumbing (`wp_*`\n * covers `wp_global_styles`, `wp_navigation`, `wp_block`, `wp_template*`),\n * Jetpack, and theme/page-builder internals that store design, not content —\n * GeneratePress elements, GenerateBlocks styles, Elementor templates and\n * Contact Form 7 / WPForms definitions. ACF field/group records stay in:\n * their cross-model parent links are part of the lossless import contract.\n * Whether a stored record gets a public route is the route producer's decision.\n */\nexport const SKIP_TYPES =\n /^(attachment|nav_menu_item|wp_|jp_|pattern|revision|oembed_cache|customize_changeset|user_request|custom_css|gblocks_|gblocks-|gp_elements|gp-elements|elementor_library|e-landing-page|wpcf7_contact_form|wpforms)/\n\n/** Open meta keys that are plugin plumbing, not editorial fields. */\nexport const PLUGIN_META = /^(jetpack|wpdc|discourse|footnotes|inline_featured|spay_|advanced_seo|rank_math|yoast)/i\n\n/** WP core/plumbing meta keys (never editorial). */\nexport const CORE_META =\n /^(_edit_last|_edit_lock|_thumbnail_id|_wp_page_template|_wp_old_slug|_wp_attached_file|_wp_attachment_metadata|_wp_attachment_image_alt|_wp_attachment_backup_sizes|_wp_desired_post_slug|_wp_trash_meta_.*|_menu_item_.*|_oembed_.*|_publicize_.*|_wpas_.*|_pingme|_encloseme|enclosure|_last_editor_used_jetpack|_rest_api_.*|_wp_attachment_context|_wp_attachment_is_custom_header|_wp_attachment_is_custom_background|_customize_.*|_elementor_.*|_wpcom_.*|_wp_suggested_privacy_policy_content|geo_.*|_jetpack_.*|_links_to.*|_format_.*)$/\n\n/** Taxonomy → model id. */\nexport const taxModelId = (t: string): string =>\n t === 'post_tag' ? 'tags' : t === 'category' ? 'categories' : t.replace(/_/g, '-')\n\nexport const slugify = (s: unknown): string =>\n String(s ?? '')\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n\nexport const decodeSlug = (s: string): string => {\n try {\n return decodeURIComponent(s)\n } catch {\n return s\n }\n}\n\n/** The measured core field skeleton for content models (same order/labels). */\nexport function coreFields(opts: {\n excerpt: boolean\n body: boolean\n date: boolean\n author: boolean\n taxes: string[]\n cover: boolean\n}): { fields: Record<string, FieldDef>; order: number } {\n const fields: Record<string, FieldDef> = {\n title: { type: 'string', required: true, label: 'Title', order: 10 },\n slug: { type: 'slug', required: true, unique: true, label: 'Slug', order: 20 },\n }\n let o = 30\n if (opts.excerpt) fields.excerpt = { type: 'text', label: 'Excerpt', order: (o += 10) }\n if (opts.body) fields.body = { type: 'richtext', label: 'Body', order: (o += 10) }\n if (opts.date) fields.published_at = { type: 'datetime', label: 'Published at', order: (o += 10) }\n if (opts.author) fields.author = { type: 'relation', model: 'authors', label: 'Author', order: (o += 10) }\n for (const t of opts.taxes) fields[taxModelId(t)] = { type: 'relations', model: taxModelId(t), label: t, order: (o += 10) }\n if (opts.cover) fields.cover = { type: 'relation', model: 'media', label: 'Cover', order: (o += 10) }\n return { fields, order: o }\n}\n","// WXR (WordPress eXtended RSS) → RawIR.\n//\n// Streaming (sax) parse: a 100 MB export holds only its records in memory,\n// never the XML. Ported from the measured import chain — the state machine,\n// the meta decoding, and the resolution passes are the parts three sessions\n// of corpus work already debugged; they are transliterated, not redesigned.\n\nimport sax from 'sax'\nimport type { Readable } from 'node:stream'\nimport type {\n RawIR,\n RawPost,\n RawLanguagePair,\n RawAttachment,\n RawAuthor,\n RawComment,\n RawMenu,\n RawMenuItem,\n RawMenuTarget,\n RawTerm,\n RawTermRef,\n RawAcfValue,\n} from '@contentrain/types'\nimport { MIGRATION_CONTRACT_VERSION } from '@contentrain/types'\nimport { tryUnserialize } from './php-unserialize.js'\nimport { strip, PROTECTED } from './core.js'\n\nexport interface WxrStats {\n serialized: { detected: number; decoded: number; failed: number; keys: string[] }\n acf_fields: number\n unresolved_terms: number\n counts: Record<string, number>\n}\n\nexport interface WxrParseResult {\n raw: RawIR\n stats: WxrStats\n}\n\ninterface XItem {\n [k: string]: unknown\n terms: Array<{ taxonomy: string; slug: string; name?: string }>\n postmeta: Array<{ key?: string; value?: string }>\n comments: Array<Record<string, string | Array<{ key?: string; value?: string }>>>\n}\n\nconst ts = (s: string | undefined): string | null =>\n !s || s.startsWith('0000-00-00') ? null : s.replace(' ', 'T')\nconst iso = (local: string | undefined, gmt: string | undefined): string | null =>\n gmt && !gmt.startsWith('0000') ? `${ts(gmt)}Z` : ts(local)\nconst num = (s: unknown): number => (s === '' || s == null ? 0 : Number(s))\nconst termKey = (tax: string, slug: string): string => `${tax}:${slug}`\n\nexport async function parseWxr(input: string | Readable, opts?: { tool?: string }): Promise<WxrParseResult> {\n const site: Record<string, unknown> = {}\n const authors: Array<Record<string, string>> = []\n const terms: Array<Record<string, string>> = []\n const items: XItem[] = []\n const stats: WxrStats = {\n serialized: { detected: 0, decoded: 0, failed: 0, keys: [] },\n acf_fields: 0,\n unresolved_terms: 0,\n counts: {},\n }\n const serializedKeySet = new Set<string>()\n\n // ── sax state machine (ported verbatim) ──\n const parser = sax.createStream(true, { trim: false })\n const path: string[] = []\n let text = ''\n let item: XItem | null = null\n let meta: { key?: string; value?: string } | null = null\n let comment: Record<string, string | Array<{ key?: string; value?: string }>> | null = null\n let cmeta: { key?: string; value?: string } | null = null\n let author: Record<string, string> | null = null\n let term: (Record<string, string> & { _tag?: string }) | null = null\n const channelText: Record<string, string> = {}\n\n const leaf = (name: string, into: Record<string, unknown>, map: Record<string, string>): void => {\n const target = map[name]\n if (target) into[target] = text\n }\n parser.on('opentag', (node) => {\n path.push(node.name)\n text = ''\n const n = node.name\n if (n === 'item') item = { terms: [], postmeta: [], comments: [] }\n else if (n === 'wp:postmeta') meta = {}\n else if (n === 'wp:comment') comment = { meta: [] }\n else if (n === 'wp:commentmeta') cmeta = {}\n else if (n === 'wp:author') author = {}\n else if (n === 'wp:category' || n === 'wp:tag' || n === 'wp:term') term = { _tag: n }\n else if (n === 'category' && item) {\n const attrs = node.attributes as Record<string, string>\n item.terms.push({ taxonomy: attrs.domain ?? '', slug: attrs.nicename ?? '' })\n }\n })\n parser.on('text', (t) => {\n text += t\n })\n parser.on('cdata', (t) => {\n text += t\n })\n parser.on('comment', (c) => {\n const m = /generator=\"([^\"]*)\"\\s+created=\"([^\"]*)\"/.exec(c)\n if (m) {\n site.generator = m[1]\n site.export_date = m[2]\n }\n })\n parser.on('closetag', (n) => {\n const parent = path[path.length - 2]\n if (cmeta) {\n if (n === 'wp:meta_key') cmeta.key = text\n else if (n === 'wp:meta_value') cmeta.value = text\n else if (n === 'wp:commentmeta') {\n ;(comment!.meta as Array<{ key?: string; value?: string }>).push(cmeta)\n cmeta = null\n }\n } else if (comment) {\n const map: Record<string, string> = {\n 'wp:comment_id': 'id',\n 'wp:comment_author': 'author',\n 'wp:comment_author_email': 'email',\n 'wp:comment_author_url': 'url',\n 'wp:comment_date': 'date',\n 'wp:comment_date_gmt': 'date_gmt',\n 'wp:comment_content': 'content',\n 'wp:comment_approved': 'approved',\n 'wp:comment_type': 'type',\n 'wp:comment_parent': 'parent',\n 'wp:comment_user_id': 'user_id',\n }\n leaf(n, comment, map)\n if (n === 'wp:comment') {\n item!.comments.push(comment)\n comment = null\n }\n } else if (meta) {\n if (n === 'wp:meta_key') meta.key = text\n else if (n === 'wp:meta_value') meta.value = text\n else if (n === 'wp:postmeta') {\n item!.postmeta.push(meta)\n meta = null\n }\n } else if (item) {\n if (n === 'category') {\n const t = item.terms.at(-1)\n if (t) t.name = text\n } else {\n const map: Record<string, string> = {\n title: 'title',\n link: 'link',\n 'dc:creator': 'author',\n guid: 'guid',\n description: 'description',\n 'content:encoded': 'content',\n 'excerpt:encoded': 'excerpt',\n 'wp:post_id': 'id',\n 'wp:post_date': 'date',\n 'wp:post_date_gmt': 'date_gmt',\n 'wp:post_modified': 'modified',\n 'wp:post_modified_gmt': 'modified_gmt',\n 'wp:comment_status': 'comment_status',\n 'wp:ping_status': 'ping_status',\n 'wp:post_name': 'slug',\n 'wp:status': 'status',\n 'wp:post_parent': 'parent',\n 'wp:menu_order': 'menu_order',\n 'wp:post_type': 'type',\n 'wp:post_password': 'password',\n 'wp:is_sticky': 'sticky',\n 'wp:attachment_url': 'attachment_url',\n }\n leaf(n, item, map)\n if (n === 'item') {\n items.push(item)\n item = null\n }\n }\n } else if (author) {\n leaf(n, author, {\n 'wp:author_id': 'id',\n 'wp:author_login': 'login',\n 'wp:author_email': 'email',\n 'wp:author_display_name': 'display_name',\n 'wp:author_first_name': 'first_name',\n 'wp:author_last_name': 'last_name',\n })\n if (n === 'wp:author') {\n authors.push(author)\n author = null\n }\n } else if (term) {\n leaf(n, term, {\n 'wp:term_id': 'id',\n 'wp:category_nicename': 'slug',\n 'wp:category_parent': 'parent',\n 'wp:cat_name': 'name',\n 'wp:category_description': 'description',\n 'wp:tag_slug': 'slug',\n 'wp:tag_name': 'name',\n 'wp:tag_description': 'description',\n 'wp:term_taxonomy': 'taxonomy',\n 'wp:term_slug': 'slug',\n 'wp:term_parent': 'parent',\n 'wp:term_name': 'name',\n 'wp:term_description': 'description',\n })\n if (n === term._tag) {\n term.taxonomy = term._tag === 'wp:category' ? 'category' : term._tag === 'wp:tag' ? 'post_tag' : (term.taxonomy ?? '')\n delete term._tag\n terms.push(term)\n term = null\n }\n } else if (parent === 'channel') {\n leaf(n, channelText, {\n title: 'title',\n link: 'link',\n description: 'description',\n language: 'language',\n 'wp:wxr_version': 'wxr_version',\n 'wp:base_site_url': 'base_site_url',\n 'wp:base_blog_url': 'base_blog_url',\n })\n }\n path.pop()\n text = ''\n })\n\n await new Promise<void>((resolve, reject) => {\n parser.on('end', () => resolve())\n parser.on('error', reject)\n if (typeof input === 'string') {\n parser.end(input)\n } else {\n input.pipe(parser)\n }\n })\n Object.assign(site, channelText)\n\n // ── post-processing: meta decode, ACF pairing, entity split, resolution flags ──\n const decodeMeta = (list: Array<{ key?: string; value?: string }>): { meta: Record<string, unknown>; serializedKeys: string[] } => {\n const out: Record<string, unknown> = {}\n const serializedKeys: string[] = []\n for (const { key, value } of list) {\n if (!key) continue\n const r = tryUnserialize(value ?? '')\n if (r.serialized) {\n stats.serialized.detected++\n serializedKeySet.add(key)\n if (r.ok) {\n stats.serialized.decoded++\n serializedKeys.push(key)\n } else stats.serialized.failed++\n }\n const v = r.ok ? r.value : (value ?? '')\n out[key] = key in out ? ([] as unknown[]).concat(out[key] as unknown[], [v]) : v\n }\n return { meta: out, serializedKeys }\n }\n const extractAcf = (metaObj: Record<string, unknown>): Record<string, RawAcfValue> => {\n const acf: Record<string, RawAcfValue> = {}\n for (const [k, v] of Object.entries(metaObj)) {\n if (k.startsWith('_') && typeof v === 'string' && /^field_[0-9a-f]+$/.test(v) && k.slice(1) in metaObj) {\n acf[k.slice(1)] = { value: metaObj[k.slice(1)], field_key: v }\n }\n }\n return acf\n }\n\n const termSet = new Set(terms.map((t) => termKey(t.taxonomy ?? '', t.slug ?? '')))\n\n interface Rec extends RawPost {\n attachment_url: string | null\n _comments: RawComment[]\n }\n const records: Rec[] = items.map((it) => {\n const { meta: m, serializedKeys } = decodeMeta(it.postmeta)\n const acf = extractAcf(m)\n stats.acf_fields += Object.keys(acf).length\n const id = num(it.id)\n const termRefs: RawTermRef[] = it.terms.map((t) => ({\n taxonomy: t.taxonomy,\n slug: t.slug,\n name: t.name ?? '',\n resolved: termSet.has(termKey(t.taxonomy, t.slug)),\n }))\n const comments: RawComment[] = it.comments.map((c) => ({\n id: num(c.id),\n post: id,\n post_type: (it.type as string) || 'post',\n parent: num(c.parent) || null,\n parent_resolved: null,\n author: (c.author as string) ?? '',\n email: (c.email as string) || null,\n url: (c.url as string) || null,\n date: iso(c.date as string, c.date_gmt as string),\n date_gmt: ts(c.date_gmt as string),\n content: (c.content as string) ?? '',\n approved: (c.approved as string | undefined) ?? '1',\n type: (c.type as string) || 'comment',\n user_id: num(c.user_id) || null,\n meta: decodeMeta((c.meta as Array<{ key?: string; value?: string }>) ?? []).meta,\n }))\n return {\n id,\n type: (it.type as string) || 'post',\n status: (it.status as string) || 'publish',\n slug: (it.slug as string) || '',\n title: (it.title as string) ?? '',\n link: (it.link as string) || null,\n guid: (it.guid as string) || null,\n author: (it.author as string) || null,\n date: iso(it.date as string, it.date_gmt as string),\n modified: iso(it.modified as string, it.modified_gmt as string),\n content: (it.content as string) ?? '',\n excerpt: (it.excerpt as string) ?? '',\n parent: num(it.parent) || null,\n menu_order: num(it.menu_order),\n sticky: it.sticky === '1',\n password: it.password ? PROTECTED : null,\n comment_status: (it.comment_status as string) || null,\n ping_status: (it.ping_status as string) || null,\n terms: termRefs,\n meta: m,\n serialized_keys: serializedKeys,\n acf,\n // Polylang exports a post's language as a `language` taxonomy term.\n lang: termRefs.find((t) => t.taxonomy === 'language')?.slug || null,\n attachment_url: (it.attachment_url as string) || null,\n _comments: comments,\n }\n })\n for (const r of records) {\n for (const t of r.terms) if (!t.resolved && r.type !== 'nav_menu_item') stats.unresolved_terms++\n }\n\n const byId = new Map(records.map((r) => [r.id, r]))\n const posts: RawPost[] = records\n .filter((r) => r.type !== 'attachment' && r.type !== 'nav_menu_item')\n .map(({ attachment_url: _a, _comments: _c, ...p }) => p)\n // Polylang groups translations under a shared `post_translations` term\n // (`pll_…`); every post in a group is a translation of the others.\n const groups = new Map<string, RawPost[]>()\n for (const p of posts) {\n const group = p.terms.find((t) => t.taxonomy === 'post_translations')?.slug\n if (!group) continue\n groups.set(group, [...(groups.get(group) ?? []), p])\n }\n const languagePairs: RawLanguagePair[] = []\n for (const members of groups.values()) {\n const translations: Record<string, number> = {}\n for (const m of members) if (m.lang) translations[m.lang] = m.id\n if (Object.keys(translations).length > 1) languagePairs.push({ post: members[0]!.id, translations })\n }\n const attachments: RawAttachment[] = records\n .filter((r) => r.type === 'attachment')\n .map((r) => ({\n id: r.id,\n title: r.title,\n slug: r.slug,\n url: r.attachment_url ?? r.guid ?? null,\n alt: typeof r.meta._wp_attachment_image_alt === 'string' ? r.meta._wp_attachment_image_alt : '',\n caption: r.excerpt,\n description: r.content,\n file: typeof r.meta._wp_attached_file === 'string' ? r.meta._wp_attached_file : null,\n image_meta: r.meta._wp_attachment_metadata ?? null,\n mime: guessMime(r.attachment_url ?? r.guid ?? ''),\n parent: r.parent,\n parent_resolved: r.parent ? byId.has(r.parent) : null,\n author: r.author,\n date: r.date,\n status: r.status,\n meta: r.meta,\n }))\n\n // ── menus: nav_menu terms + nav_menu_item posts (targets from meta) ──\n const postById = new Map(posts.map((p) => [p.id, p]))\n const termByIdNum = new Map(terms.map((t) => [num(t.id), t]))\n const menus: RawMenu[] = terms\n .filter((t) => t.taxonomy === 'nav_menu')\n .map((mt) => ({ id: num(mt.id) || null, slug: mt.slug ?? '', name: mt.name ?? '', items: [] as RawMenuItem[] }))\n const menuBySlug = new Map(menus.map((m) => [m.slug, m]))\n for (const r of records.filter((x) => x.type === 'nav_menu_item')) {\n const m = r.meta\n const type = m._menu_item_type as string | undefined\n const object = m._menu_item_object as string | undefined\n const objectId = num(m._menu_item_object_id)\n let target: RawMenuTarget\n if (type === 'custom') target = { kind: 'url', url: String(m._menu_item_url ?? ''), resolved: true }\n else if (type === 'post_type') {\n const p = postById.get(objectId)\n target = { kind: 'post', post_type: object ?? '', id: objectId || null, slug: p?.slug ?? null, resolved: !!p }\n } else if (type === 'taxonomy') {\n const t = termByIdNum.get(objectId)\n target = { kind: 'term', taxonomy: object ?? '', id: objectId || null, slug: t?.slug ?? null, resolved: !!t }\n } else if (type === 'post_type_archive') target = { kind: 'archive', post_type: object ?? '', resolved: true }\n else target = { kind: 'unknown', resolved: false }\n const parent = num(m._menu_item_menu_item_parent) || null\n const itemRec: RawMenuItem = {\n id: r.id,\n title: r.title || (('slug' in target && target.slug) || '') || '',\n order: r.menu_order,\n parent,\n url: (m._menu_item_url as string) || null,\n target,\n target_attr: (m._menu_item_target as string) || null,\n classes: ([] as string[]).concat((m._menu_item_classes as string[]) ?? []).filter(Boolean),\n description: r.content,\n status: r.status,\n }\n const menuSlug = r.terms.find((t) => t.taxonomy === 'nav_menu')?.slug\n const menu = menuSlug ? menuBySlug.get(menuSlug) : undefined\n if (menu) menu.items.push(itemRec)\n }\n const allMenuItemIds = new Set(menus.flatMap((m) => m.items.map((i) => i.id)))\n for (const m of menus) {\n for (const i of m.items) if (i.parent && !allMenuItemIds.has(i.parent)) i.parent_unresolved = true\n }\n\n // ── comments: threaded, parent resolution within the same post ──\n const comments: RawComment[] = []\n for (const r of records) {\n const ids = new Set(r._comments.map((c) => c.id))\n for (const c of r._comments) comments.push({ ...c, parent_resolved: c.parent ? ids.has(c.parent) : null })\n }\n\n const rawAuthors: RawAuthor[] = authors.map((a) => ({\n id: num(a.id) || null,\n login: a.login ?? '',\n email: a.email || null,\n display_name: a.display_name || a.login || '',\n first_name: a.first_name || null,\n last_name: a.last_name || null,\n }))\n const rawTerms: RawTerm[] = terms\n .filter((t) => t.taxonomy !== 'nav_menu')\n .map((t) => ({\n id: num(t.id) || null,\n taxonomy: t.taxonomy ?? '',\n slug: t.slug ?? '',\n name: t.name ?? '',\n parent: t.parent || null,\n parent_resolved: t.parent ? termSet.has(termKey(t.taxonomy ?? '', t.parent)) : null,\n description: t.description || '',\n }))\n\n stats.serialized.keys = [...serializedKeySet].toSorted()\n stats.counts = {\n items: records.length,\n posts: posts.length,\n attachments: attachments.length,\n terms: rawTerms.length,\n authors: rawAuthors.length,\n menus: menus.length,\n comments: comments.length,\n }\n\n const raw: RawIR = {\n version: MIGRATION_CONTRACT_VERSION,\n provenance: { kind: 'wxr', tool: opts?.tool ?? '@contentrain/wp-import' },\n site: {\n url: String(site.link ?? channelText.link ?? ''),\n title: strip(channelText.title),\n description: strip(channelText.description) || undefined,\n base_site_url: channelText.base_site_url,\n base_blog_url: channelText.base_blog_url,\n language: channelText.language ?? null,\n generator: (site.generator as string) ?? null,\n export_date: (site.export_date as string) ?? null,\n wxr_version: channelText.wxr_version ?? null,\n },\n authors: rawAuthors,\n terms: rawTerms,\n posts,\n attachments,\n menus,\n comments,\n ...(languagePairs.length ? { language_pairs: languagePairs } : {}),\n }\n return { raw, stats }\n}\n\nconst MIME: Record<string, string> = {\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n png: 'image/png',\n gif: 'image/gif',\n webp: 'image/webp',\n svg: 'image/svg+xml',\n mp3: 'audio/mpeg',\n mp4: 'video/mp4',\n pdf: 'application/pdf',\n}\nfunction guessMime(u: string): string | null {\n const e = (u.split('?')[0]?.split('.').pop() ?? '').toLowerCase()\n return MIME[e] ?? null\n}\n","// Public/authenticated WordPress REST → RawIR.\n//\n// The lowest rungs of the source-access ladder. What REST cannot see (menus,\n// rest:false CPTs, unregistered meta) is simply absent from the result —\n// absence at a low rung is information, not an error, and the manifest layer\n// decides what to recommend about it.\n\nimport type { RawIR, RawAttachment, RawComment, RawLanguagePair, RawPost, RawTerm, RawTermRef, SourceAccessKind } from '@contentrain/types'\nimport { MIGRATION_CONTRACT_VERSION } from '@contentrain/types'\nimport { strip, SKIP_TYPES, PROTECTED } from './core.js'\n\nconst iso = (gmt: string | undefined): string | null => (gmt ? `${gmt}Z` : null)\nconst approvedOf = (status: string | undefined): RawComment['approved'] =>\n status === 'approved' ? '1' : status === 'hold' ? '0' : status === 'spam' ? 'spam' : status === 'trash' ? 'trash' : (status ?? '1')\n\nexport interface RestImportOptions {\n origin: string\n /** Injectable for tests and for hosts that need custom dispatch. */\n fetchImpl?: typeof fetch\n /**\n * WordPress Application Password credentials — lifts the rung to rest_auth.\n * With them, post types are listed with every non-trash status\n * (`AUTH_POST_STATUSES`) in the edit context, and comments with held ones\n * too; anonymous REST only ever returns published posts and approved\n * comments. A credential the site refuses for that falls back to the\n * public listing, with a warning.\n */\n auth?: { user: string; appPassword: string }\n perPage?: number\n /**\n * Requests in flight at once, across every collection. Default 4. A site\n * with 74 pages of posts, 40 of media and 37 of comments used to receive\n * ~150 simultaneous requests — enough to trip a host's rate limit or WAF.\n */\n concurrency?: number\n /**\n * Pages fetched per collection at most. Unset = all. A truncated collection\n * is named in `warnings` (with what was skipped), never silently shortened.\n */\n maxPages?: number\n tool?: string\n}\n\nexport interface RestImportResult {\n raw: RawIR\n warnings: string[]\n /**\n * Whether the credential was honoured, for callers that must act on it\n * without reading `warnings`. `none`: no `auth` given. `accepted`: every\n * listing it unlocks was read with it. `rejected`: at least one was not —\n * `fell_back` names each (`posts`, `pages`, a CPT's rest base, `comments`,\n * `comments:hold`), and those came from the public listing instead, or not\n * at all for `comments:hold`, which has none.\n */\n credential: { status: 'none' | 'accepted' | 'rejected'; fell_back: string[] }\n}\n\ninterface RestPost {\n id: number\n slug: string\n status?: string\n type?: string\n link?: string\n title?: { rendered?: string }\n content?: { rendered?: string }\n excerpt?: { rendered?: string }\n date_gmt?: string\n modified_gmt?: string\n author?: number\n parent?: number\n menu_order?: number\n sticky?: boolean\n /** Edit context only. */\n password?: string\n comment_status?: string\n ping_status?: string\n featured_media?: number\n categories?: number[]\n tags?: number[]\n meta?: Record<string, unknown>\n /** Polylang: language slug of the post and its translation group (`{ en: 12, tr: 34 }`, self included). */\n lang?: string\n translations?: Record<string, number>\n /** WPML: locale of the post and its other translations. */\n wpml_current_locale?: string\n wpml_translations?: Array<{ locale?: string; id?: number }>\n}\n\n/** What a credential lists beyond `publish`: drafts, scheduled, in-review and private posts. Trash stays out. */\nexport const AUTH_POST_STATUSES = ['publish', 'future', 'draft', 'pending', 'private'] as const\n/** Comment listings for a credential: WP's `status` takes one value, so approved and held are two requests. */\nconst AUTH_COMMENT_STATUSES = ['approve', 'hold'] as const\nconst DENIED = new Set([400, 401, 403])\n/** A comment listing's name in `credential.fell_back`: `comments` (approved) or `comments:hold`. */\nconst commentKey = (status: string): string => (status === 'approve' ? 'comments' : `comments:${status}`)\n\nconst positiveInteger = (name: string, value: number): number => {\n if (!Number.isSafeInteger(value) || value < 1) throw new RangeError(`${name} must be a positive safe integer`)\n return value\n}\n\nexport async function fetchRestRawIR(options: RestImportOptions): Promise<RestImportResult> {\n const origin = options.origin.replace(/\\/$/, '')\n const doFetch = options.fetchImpl ?? fetch\n const perPage = positiveInteger('perPage', options.perPage ?? 100)\n if (perPage > 100) throw new RangeError('perPage must be at most 100')\n const concurrency = positiveInteger('concurrency', options.concurrency ?? 4)\n const maxPages = options.maxPages !== undefined ? positiveInteger('maxPages', options.maxPages) : undefined\n const warnings: string[] = []\n // One pool for the whole import: page fetches of every collection queue here,\n // so the cap holds even though collections are requested \"in parallel\".\n const queue: Array<() => Promise<void>> = []\n let running = 0\n const schedule = <T>(task: () => Promise<T>): Promise<T> =>\n new Promise<T>((resolve, reject) => {\n queue.push(() => task().then(resolve, reject))\n pump()\n })\n const pump = (): void => {\n while (running < concurrency && queue.length) {\n const task = queue.shift()!\n running++\n void task().finally(() => {\n running--\n pump()\n })\n }\n }\n const anonymous: Record<string, string> = { accept: 'application/json' }\n let headers = anonymous\n if (options.auth) {\n headers = { ...anonymous, authorization: `Basic ${Buffer.from(`${options.auth.user}:${options.auth.appPassword}`).toString('base64')}` }\n }\n const fellBack = new Set<string>()\n // WordPress answers a wrong Application Password with 401 on every route,\n // public ones too, so a rejected credential is found once and dropped:\n // sent on, it would also empty the public listings the import falls back to.\n let rejected = false\n if (options.auth) {\n const me = await doFetch(`${origin}/wp-json/wp/v2/users/me`, { headers })\n await me.body?.cancel()\n if (me.status === 401 || me.status === 403) {\n rejected = true\n headers = anonymous\n warnings.push(`credential: HTTP ${me.status} on users/me — the site rejected it; imported the public listings only`)\n }\n }\n\n /**\n * Every page of `path`. With `fallback`, a first page the site refuses\n * (400/401/403 — the credential may not list those statuses or the edit\n * context) is retried as `fallback` instead of dropping the collection;\n * an empty `fallback` means there is nothing public to retry, so it is\n * skipped with that warning. The retry is anonymous, and `key` goes into\n * `credential.fell_back`.\n */\n const getAll = async <T>(path: string, fallback?: string, key?: string, send = headers): Promise<T[]> => {\n const label = path.split('?')[0]!\n const url = (page: number) => `${origin}/wp-json/wp/v2/${path}${path.includes('?') ? '&' : '?'}per_page=${perPage}&page=${page}`\n // Hold the slot until the body is consumed, not merely until headers arrive.\n const pageData = (page: number) => schedule(async () => {\n const response = await doFetch(url(page), { headers: send })\n if (!response.ok) {\n await response.body?.cancel()\n if (page === 1 && fallback !== undefined && DENIED.has(response.status)) return { items: [] as T[], pages: 1, denied: response.status }\n warnings.push(`${label}: page ${page} HTTP ${response.status} — skipped`)\n return { items: [] as T[], pages: 1 }\n }\n const pages = Number(response.headers.get('x-wp-totalpages') ?? '1')\n if (!Number.isSafeInteger(pages) || pages < 0) throw new Error(`${path}: invalid x-wp-totalpages`)\n const items = await response.json() as T[]\n if (!Array.isArray(items)) throw new Error(`${path}: page ${page} is not a collection`)\n return { items, pages: Math.max(1, pages), denied: undefined as number | undefined }\n })\n const first = await pageData(1)\n if (first.denied !== undefined) {\n warnings.push(`${label}: HTTP ${first.denied} for ${path.split('?')[1]} with the credential — ${fallback ? 'fell back to the public listing' : 'skipped (no public listing)'}`)\n fellBack.add(key ?? label)\n return fallback ? getAll<T>(fallback, undefined, undefined, anonymous) : []\n }\n const totalPages = first.pages\n const firstPage = first.items\n const wanted = maxPages !== undefined ? Math.min(totalPages, maxPages) : totalPages\n if (wanted < totalPages) {\n warnings.push(`${label}: ${totalPages} pages, fetched ${wanted} (maxPages) — ${totalPages - wanted} pages skipped`)\n }\n if (wanted <= 1) return firstPage\n const rest = await Promise.all(\n Array.from({ length: wanted - 1 }, (_v, i) =>\n pageData(i + 2).then((r) => r.items),\n ),\n )\n return firstPage.concat(...rest)\n }\n\n interface RestType { slug: string; rest_base?: string }\n const typesResp = await doFetch(`${origin}/wp-json/wp/v2/types`, { headers })\n const types: Record<string, RestType> = typesResp.ok ? ((await typesResp.json()) as Record<string, RestType>) : {}\n if (!typesResp.ok) warnings.push(`types: HTTP ${typesResp.status} — importing posts and pages only`)\n const postTypes = Object.values(types).filter(\n (t) => t.rest_base && !SKIP_TYPES.test(t.slug) && t.slug !== 'attachment',\n )\n const bases = postTypes.length ? postTypes.map((t) => ({ slug: t.slug, base: t.rest_base! })) : [\n { slug: 'post', base: 'posts' },\n { slug: 'page', base: 'pages' },\n ]\n\n interface RestTerm { id: number; slug: string; name: string; taxonomy?: string; parent?: number; description?: string }\n interface RestUser { id: number; slug: string; name: string }\n interface RestMedia {\n id: number\n slug: string\n title?: { rendered?: string }\n source_url?: string\n alt_text?: string\n caption?: { rendered?: string }\n mime_type?: string\n media_details?: { width?: number; height?: number; file?: string }\n post?: number | null\n date_gmt?: string\n }\n interface RestComment {\n id: number\n post: number\n parent?: number\n author?: number\n author_name?: string\n author_url?: string\n date_gmt?: string\n content?: { rendered?: string }\n status?: string\n type?: string\n }\n\n // Anonymous: WP's defaults (published posts, approved comments). With a\n // credential: every non-trash status, and held comments as a second listing.\n // A credential rejected outright unlocks nothing: every listing it would have read fell back.\n if (rejected) {\n for (const b of bases) fellBack.add(b.base)\n for (const status of AUTH_COMMENT_STATUSES) fellBack.add(commentKey(status))\n }\n const authed = options.auth !== undefined && !rejected\n const postListing = (base: string): Promise<RestPost[]> =>\n authed ? getAll<RestPost>(`${base}?status=${AUTH_POST_STATUSES.join(',')}&context=edit`, base, base) : getAll<RestPost>(base)\n const commentListing = async (): Promise<RestComment[]> => {\n if (!authed) return getAll<RestComment>('comments')\n const lists = await Promise.all(AUTH_COMMENT_STATUSES.map((status) =>\n // Approved comments are public, so a refused credential still gets them; held ones have no public listing.\n getAll<RestComment>(`comments?status=${status}&context=edit`, status === 'approve' ? 'comments' : '', commentKey(status))))\n const byId = new Map<number, RestComment>()\n for (const c of lists.flat()) if (!byId.has(c.id)) byId.set(c.id, c)\n return [...byId.values()]\n }\n const [categories, tags, users, media, restComments, ...postLists] = await Promise.all([\n getAll<RestTerm>('categories'),\n getAll<RestTerm>('tags'),\n getAll<RestUser>('users'),\n getAll<RestMedia>('media'),\n commentListing(),\n ...bases.map((b) => postListing(b.base)),\n ])\n\n const termsById = new Map<number, RawTerm>()\n for (const [tax, list] of [\n ['category', categories],\n ['post_tag', tags],\n ] as const) {\n for (const t of list) {\n termsById.set(t.id, {\n id: t.id,\n taxonomy: tax,\n slug: t.slug,\n name: strip(t.name),\n parent: t.parent ? (list.find((x) => x.id === t.parent)?.slug ?? null) : null,\n parent_resolved: t.parent ? list.some((x) => x.id === t.parent) : null,\n description: t.description ?? '',\n })\n }\n }\n const userById = new Map(users.map((u) => [u.id, u]))\n\n const posts: RawPost[] = []\n // Translation groups, one pair per group. Polylang's `translations` already\n // includes the post itself; WPML lists the OTHER translations, so add self.\n const languagePairs: RawLanguagePair[] = []\n const seenGroups = new Set<string>()\n const recordGroup = (self: RestPost, lang: string | null) => {\n const translations: Record<string, number> = {}\n if (self.translations && typeof self.translations === 'object') {\n for (const [code, id] of Object.entries(self.translations)) if (typeof id === 'number') translations[code] = id\n } else if (Array.isArray(self.wpml_translations)) {\n for (const t of self.wpml_translations) if (t.locale && typeof t.id === 'number') translations[t.locale] = t.id\n if (lang) translations[lang] = self.id\n }\n const ids = Object.values(translations)\n if (ids.length < 2) return\n const key = [...ids].toSorted((a, b) => a - b).join(',')\n if (seenGroups.has(key)) return\n seenGroups.add(key)\n languagePairs.push({ post: self.id, translations })\n }\n for (const [i, base] of bases.entries()) {\n for (const p of postLists[i] ?? []) {\n const termRefs: RawTermRef[] = [...(p.categories ?? []), ...(p.tags ?? [])].map((id) => {\n const t = termsById.get(id)\n return t\n ? { taxonomy: t.taxonomy, slug: t.slug, name: t.name, resolved: true }\n : { taxonomy: 'category', slug: String(id), name: String(id), resolved: false }\n })\n const author = p.author ? (userById.get(p.author)?.slug ?? null) : null\n const meta: Record<string, unknown> = { ...(p.meta && typeof p.meta === 'object' ? p.meta : {}) }\n if (p.featured_media) meta._thumbnail_id = String(p.featured_media)\n const lang = (typeof p.lang === 'string' && p.lang) || (typeof p.wpml_current_locale === 'string' && p.wpml_current_locale) || null\n recordGroup(p, lang)\n posts.push({\n ...(lang ? { lang } : {}),\n id: p.id,\n type: base.slug,\n status: p.status ?? 'publish',\n slug: p.slug,\n title: p.title?.rendered ?? '',\n link: p.link ?? null,\n guid: null,\n author,\n date: iso(p.date_gmt),\n modified: iso(p.modified_gmt),\n content: p.content?.rendered ?? '',\n excerpt: p.excerpt?.rendered ?? '',\n parent: p.parent || null,\n menu_order: p.menu_order ?? 0,\n sticky: p.sticky ?? false,\n password: p.password ? PROTECTED : null,\n comment_status: p.comment_status ?? null,\n ping_status: p.ping_status ?? null,\n terms: termRefs,\n meta,\n })\n }\n }\n\n const attachments: RawAttachment[] = media.map((m) => ({\n id: m.id,\n title: strip(m.title?.rendered) || m.slug,\n slug: m.slug,\n url: m.source_url ?? null,\n alt: m.alt_text ?? '',\n caption: strip(m.caption?.rendered),\n file: m.media_details?.file ?? null,\n image_meta: m.media_details ?? null,\n mime: m.mime_type ?? null,\n parent: m.post ?? null,\n parent_resolved: m.post ? posts.some((p) => p.id === m.post) : null,\n date: iso(m.date_gmt),\n }))\n\n const postIds = new Set(posts.map((p) => p.id))\n const commentIds = new Set(restComments.map((c) => c.id))\n const comments: RawComment[] = restComments.map((c) => ({\n id: c.id,\n post: c.post,\n post_type: posts.find((p) => p.id === c.post)?.type,\n parent: c.parent || null,\n parent_resolved: c.parent ? commentIds.has(c.parent) : null,\n author: strip(c.author_name) || 'anonymous',\n email: null,\n url: c.author_url || null,\n date: iso(c.date_gmt),\n date_gmt: c.date_gmt ?? null,\n content: c.content?.rendered ?? '',\n approved: approvedOf(c.status),\n type: c.type ?? 'comment',\n user_id: c.author || null,\n }))\n for (const c of comments) if (!postIds.has(c.post)) warnings.push(`comment ${c.id}: post ${c.post} not in fetched set`)\n\n // The rung is what was actually read: a credential rejected outright read nothing.\n const kind: SourceAccessKind = authed ? 'rest_auth' : 'rest_public'\n const raw: RawIR = {\n version: MIGRATION_CONTRACT_VERSION,\n provenance: { kind, tool: options.tool ?? '@contentrain/wp-import' },\n site: { url: origin },\n authors: users.map((u) => ({ id: u.id, login: u.slug, display_name: strip(u.name) || u.slug, email: null })),\n terms: [...termsById.values()],\n posts,\n attachments,\n comments,\n ...(languagePairs.length ? { language_pairs: languagePairs } : {}),\n }\n const credential: RestImportResult['credential'] = {\n status: !options.auth ? 'none' : fellBack.size ? 'rejected' : 'accepted',\n fell_back: [...fellBack].toSorted(),\n }\n return { raw, warnings, credential }\n}\n","// RawIR → .contentrain content store, as a pure file map.\n//\n// Ported from the measured import chain (the \"deviations from r4i\" it carried\n// are already folded in: PATH_PATTERNS-conformant layout, ContentrainConfig\n// shape, meta files per locale). Two properties are load-bearing:\n//\n// 1. Identity formulas — hexId('posts:' + slug), hexId('category:' + slug) —\n// are shared with the REST path, so the same site imported twice (or via a\n// later delta) lands on the same entry ids.\n// 2. The EntrySourceMap (wp post id → entry address) is produced HERE and only\n// here: this is the one place that knows both sides of the mapping, and the\n// comments intake downstream cannot exist without it.\n\nimport type { EntrySourceMap, FieldDef, ModelDefinition, RawIR, RawPost } from '@contentrain/types'\nimport {\n byValue,\n canon,\n coreFields,\n decodeSlug,\n hexId,\n PLUGIN_META,\n SKIP_TYPES,\n slugify,\n strip,\n taxModelId,\n} from './core.js'\n\nexport interface ImportReport {\n slug_rewritten: number\n slug_fallback: number\n title_fallback: number\n meta_fields: Record<string, string>\n acf_fields: Record<string, string>\n skipped_types: string[]\n dropped_relations: number\n models: Record<string, { kind: string; domain: string; fields: number; entries: number }>\n /** Default first, then every other language seen on a post. One entry on a monolingual site. */\n locales: string[]\n /** Translation groups that were folded into one entry id across locales. */\n translation_groups: number\n /**\n * Password-protected posts imported as `draft`, whatever their WordPress\n * status. Their body is the protected text, and nothing downstream (query\n * SDK, emitter) enforces `visibility: password`, so publishing one would\n * put that text on a public site. Publish only after deciding what to show.\n */\n password_protected_drafts: number\n}\n\nexport interface ContentrainResult {\n files: Record<string, string>\n entry_source_map: EntrySourceMap\n report: ImportReport\n}\n\ntype Entry = Record<string, unknown>\ntype Meta = { status: string; source: string; updated_by: string; publish_at?: string }\n\nconst pick = (o: Record<string, unknown>, keys: Set<string>): Entry =>\n Object.fromEntries(Object.entries(o).filter(([k, v]) => keys.has(k) && v !== undefined && v !== null && v !== ''))\nconst typeModelId = (t: string): string => (t === 'post' ? 'posts' : t === 'page' ? 'pages' : t.replace(/_/g, '-'))\nconst domainOf = (t: string): string => (t === 'post' ? 'blog' : t === 'page' ? 'site' : 'custom')\n\n/** `en_US` / `tr-TR` / `en` → `en`: the store's locale is the primary subtag. */\nconst normLocale = (code: string | null | undefined): string => (code ?? '').split(/[-_]/)[0]?.toLowerCase() ?? ''\n\n/** Multilingual-plugin taxonomies that carry language bookkeeping, not content. */\nconst LANGUAGE_TAXONOMIES = new Set(['language', 'post_translations', 'term_language', 'term_translations'])\n\n/**\n * A relation field over `targets`: its declared model, and how a reference into\n * it is stored.\n *\n * With several targets the id alone does not say which model's entry it is, so\n * the reference is the pair `{ model, ref }`. With one there is nothing to\n * choose between: the field is single-target and stores the entry id. Writing\n * the pair there fails the same validator that requires it when there are\n * several — so the choice is made in one place, from the same list the model\n * declares.\n */\nfunction relationOver(targets: string[]): {\n model: string | string[]\n ref: (entry: { model: string; ref: string }) => string | { model: string; ref: string }\n} {\n const single = targets.length === 1\n return { model: single ? targets[0]! : targets, ref: (entry) => (single ? entry.ref : entry) }\n}\n\nexport function rawToContentrain(raw: RawIR, opts?: { updatedBy?: string }): ContentrainResult {\n const updatedBy = opts?.updatedBy ?? '@contentrain/wp-import'\n const locale = normLocale(raw.site.language) || 'en'\n const models: Record<string, ModelDefinition> = {}\n const contents: Record<string, Record<string, Entry>> = {}\n const metas: Record<string, Record<string, Meta>> = {}\n // Per-locale buckets for i18n models (post types on a multilingual site).\n const localeContents: Record<string, Record<string, Record<string, Entry>>> = {}\n const localeMetas: Record<string, Record<string, Record<string, Meta>>> = {}\n\n // ── languages ──\n // A post's language comes from the plugin (`lang`) or, in WXR, from the\n // `language` taxonomy term Polylang attaches. Posts without one belong to the\n // site's default locale. More than one locale seen → post-type models are\n // i18n and content is written per locale.\n const postLocale = (p: RawPost): string =>\n normLocale(p.lang ?? p.terms.find((t) => t.taxonomy === 'language')?.slug) || locale\n const locales = [locale, ...[...new Set(raw.posts.filter((p) => !SKIP_TYPES.test(p.type)).map(postLocale))].filter((l) => l !== locale).toSorted()]\n const multilingual = locales.length > 1\n // Translation groups → one canonical post per group. Its entry id is shared\n // by every translation, which is how an i18n collection addresses one entry\n // in several locales. The canonical member is the default-locale post when\n // there is one, else the lowest id — deterministic either way.\n const postById = new Map(raw.posts.map((p) => [p.id, p]))\n const canonicalOf = new Map<number, number>()\n let translationGroups = 0\n for (const pair of raw.language_pairs ?? []) {\n const members = [...new Set(Object.values(pair.translations))].filter((id) => postById.has(id) && !SKIP_TYPES.test(postById.get(id)!.type))\n if (members.length < 2) continue\n const memberLocales = members.map((id) => postLocale(postById.get(id)!))\n if (new Set(memberLocales).size !== members.length)\n throw new Error(`Translation group ${pair.post} has multiple posts in the same normalized locale; refusing to overwrite a translation`)\n const canonical = members.find((id) => postLocale(postById.get(id)!) === locale) ?? Math.min(...members)\n for (const id of members) canonicalOf.set(id, canonical)\n translationGroups++\n }\n let siteEntry: Entry = {}\n let siteMeta: Meta | null = null\n const report: ImportReport = {\n slug_rewritten: 0,\n slug_fallback: 0,\n title_fallback: 0,\n meta_fields: {},\n acf_fields: {},\n skipped_types: [],\n dropped_relations: 0,\n models: {},\n locales,\n translation_groups: translationGroups,\n password_protected_drafts: 0,\n }\n const importMeta = (status: string, extra: Partial<Meta> = {}): Meta => ({\n status,\n source: 'import',\n updated_by: updatedBy,\n ...extra,\n })\n const mapStatus = (p: RawPost): Meta => {\n // Checked first: a protected post must never come in published or scheduled.\n if (p.password && p.status !== 'trash') {\n report.password_protected_drafts++\n return importMeta('draft')\n }\n if (p.status === 'future' && (!p.date || !Number.isFinite(Date.parse(p.date))))\n throw new Error(`Scheduled WordPress post ${p.id} has no valid publication date`)\n return p.status === 'publish' || p.status === 'inherit'\n ? importMeta('published')\n : p.status === 'future'\n ? importMeta('published', { publish_at: p.date! })\n : p.status === 'pending'\n ? importMeta('in_review')\n : p.status === 'trash'\n ? importMeta('archived')\n : importMeta('draft')\n }\n const addModel = (m: ModelDefinition): void => {\n models[m.id] = m\n contents[m.id] ??= {}\n metas[m.id] ??= {}\n }\n\n // ── identities (shared formulas — REST and WXR must agree) ──\n const authorId = (login: string): string => hexId(`authors:${login}`)\n const termId = (tax: string, slug: string): string => hexId(`${tax}:${slug}`)\n const usedSlugs = new Map<string, number>()\n const postSlug = (p: RawPost): string => {\n let s = slugify(decodeSlug(p.slug))\n if (!s) {\n s = `${p.type}-${p.id}`\n report.slug_fallback++\n } else if (s !== p.slug) report.slug_rewritten++\n // Slugs are unique per type — and per locale on a multilingual site, where\n // `/about/` and `/tr/about/` are different entries with the same slug.\n const key = multilingual ? `${p.type}:${postLocale(p)}:${s}` : `${p.type}:${s}`\n const n = usedSlugs.get(key) ?? 0\n usedSlugs.set(key, n + 1)\n return n ? `${s}-${p.id}` : s\n }\n const slugOf = new Map<number, string>()\n const postEntry = new Map<number, { model: string; ref: string }>()\n for (const p of raw.posts.toSorted((a, b) => a.id - b.id)) {\n // Only exported entries may be relation targets or appear in the source map.\n if (SKIP_TYPES.test(p.type)) continue\n slugOf.set(p.id, postSlug(p))\n }\n // Keep established slug identities unless distinct translation groups collide.\n // Prefer the default-locale group, then the lowest WP id, independently of\n // REST pagination/WXR order. A colliding group gets a WP-id namespace.\n const identityOwner = new Map<string, number>()\n const exported = raw.posts.filter((p) => !SKIP_TYPES.test(p.type))\n const canonicalPosts = exported.filter((p) => (canonicalOf.get(p.id) ?? p.id) === p.id)\n .toSorted((a, b) => Number(postLocale(b) === locale) - Number(postLocale(a) === locale) || a.id - b.id)\n for (const p of canonicalPosts) {\n const key = `${typeModelId(p.type)}:${slugOf.get(p.id)!}`\n if (!identityOwner.has(key)) identityOwner.set(key, p.id)\n }\n for (const p of exported) {\n const canonical = canonicalOf.get(p.id) ?? p.id\n const mid = typeModelId(p.type)\n const key = `${mid}:${slugOf.get(canonical) ?? slugOf.get(p.id)!}`\n postEntry.set(p.id, { model: mid, ref: hexId(identityOwner.get(key) === canonical ? key : `${mid}:wp:${canonical}`) })\n }\n const mediaRef = (id: number): string | null => (raw.attachments.some((a) => a.id === id) ? hexId(`media:${id}`) : null)\n const titleOf = (p: RawPost): string => {\n const t = strip(p.title)\n if (t) return t\n report.title_fallback++\n return slugOf.get(p.id) ?? `#${p.id}`\n }\n\n // ── authors ──\n addModel({\n id: 'authors', name: 'Authors', kind: 'collection', domain: 'blog', i18n: false, title_field: 'name',\n fields: {\n name: { type: 'string', required: true, label: 'Name', order: 10 },\n slug: { type: 'slug', required: true, unique: true, label: 'Slug', order: 20 },\n email: { type: 'email', label: 'Email', order: 30 },\n wp_id: { type: 'integer', label: 'WP user ID', order: 40 },\n },\n })\n for (const a of raw.authors) {\n const id = authorId(slugify(a.login))\n contents.authors![id] = pick(\n { name: strip(a.display_name), slug: slugify(a.login), email: a.email, wp_id: a.id },\n new Set(['name', 'slug', 'email', 'wp_id']),\n )\n metas.authors![id] = importMeta('published')\n }\n for (const p of raw.posts) {\n if (p.author && !contents.authors![authorId(slugify(p.author))]) {\n contents.authors![authorId(slugify(p.author))] = { name: p.author, slug: slugify(p.author) }\n metas.authors![authorId(slugify(p.author))] = importMeta('published')\n }\n }\n\n // ── taxonomies (nav_menu and post_format excluded; post_format → select field) ──\n const taxonomies = [...new Set(raw.terms.map((t) => t.taxonomy))].filter(\n (t) => t !== 'nav_menu' && t !== 'post_format' && !LANGUAGE_TAXONOMIES.has(t),\n )\n for (const tax of taxonomies) {\n const mid = taxModelId(tax)\n addModel({\n id: mid, name: mid, kind: 'collection', domain: 'blog', i18n: false, title_field: 'name',\n fields: {\n name: { type: 'string', required: true, label: 'Name', order: 10 },\n slug: { type: 'slug', required: true, unique: true, label: 'Slug', order: 20 },\n description: { type: 'text', label: 'Description', order: 30 },\n parent: { type: 'relation', model: mid, label: 'Parent', order: 40 },\n wp_id: { type: 'integer', label: 'WP term ID', order: 50 },\n },\n })\n for (const t of raw.terms.filter((x) => x.taxonomy === tax)) {\n const id = termId(tax, t.slug)\n contents[mid]![id] = pick(\n {\n name: strip(t.name),\n slug: slugify(decodeSlug(t.slug)) || `term-${t.id}`,\n description: strip(t.description),\n parent: t.parent && t.parent_resolved ? termId(tax, t.parent) : null,\n wp_id: t.id,\n },\n new Set(['name', 'slug', 'description', 'parent', 'wp_id']),\n )\n metas[mid]![id] = importMeta('published')\n }\n }\n // referenced-but-unlisted terms join the pool (marked resolved:false upstream, never dropped)\n for (const p of raw.posts) {\n for (const t of p.terms) {\n if (t.taxonomy === 'nav_menu' || t.taxonomy === 'post_format' || t.resolved) continue\n const mid = taxModelId(t.taxonomy)\n if (!models[mid]) continue\n const id = termId(t.taxonomy, t.slug)\n contents[mid]![id] ??= { name: strip(t.name), slug: slugify(t.slug) }\n metas[mid]![id] ??= importMeta('published')\n }\n }\n\n const postTypes = [...new Set(raw.posts.map((p) => p.type))].filter((t) => {\n if (SKIP_TYPES.test(t)) {\n report.skipped_types.push(t)\n return false\n }\n return true\n })\n const contentModelIds = postTypes.map(typeModelId)\n const toContent = relationOver(contentModelIds)\n\n // ── media ──\n addModel({\n id: 'media', name: 'Media', kind: 'collection', domain: 'assets', i18n: false, title_field: 'title',\n fields: {\n title: { type: 'string', required: true, label: 'Title', order: 10 },\n slug: { type: 'slug', required: true, unique: true, label: 'Slug', order: 20 },\n url: { type: 'url', required: true, label: 'Source URL', order: 30 },\n alt: { type: 'string', label: 'Alt text', order: 40 },\n caption: { type: 'text', label: 'Caption', order: 50 },\n description: { type: 'text', label: 'Description', order: 60 },\n mime: { type: 'string', label: 'MIME type', order: 70 },\n width: { type: 'integer', label: 'Width', order: 80 },\n height: { type: 'integer', label: 'Height', order: 90 },\n file: { type: 'string', label: 'Upload path', order: 100 },\n parent: { type: 'relation', model: toContent.model, label: 'Attached to', order: 110 },\n wp_id: { type: 'integer', label: 'WP attachment ID', order: 120 },\n uploaded_at: { type: 'datetime', label: 'Uploaded at', order: 130 },\n },\n })\n const mediaSlugs = new Set<string>()\n for (const a of raw.attachments) {\n const id = hexId(`media:${a.id}`)\n let slug = slugify(decodeSlug(a.slug)) || `media-${a.id}`\n if (mediaSlugs.has(slug)) slug = `${slug}-${a.id}`\n mediaSlugs.add(slug)\n const target = a.parent ? postEntry.get(a.parent) : undefined\n if (a.parent && !target) report.dropped_relations++\n const parent = target ? toContent.ref(target) : null\n const im = (a.image_meta ?? null) as { width?: number; height?: number } | null\n contents.media![id] = pick(\n {\n title: strip(a.title) || slug,\n slug,\n url: a.url,\n alt: strip(a.alt),\n caption: strip(a.caption),\n description: strip(a.description),\n mime: a.mime,\n width: im?.width,\n height: im?.height,\n file: a.file,\n parent,\n wp_id: a.id,\n uploaded_at: a.date,\n },\n new Set(['title', 'slug', 'url', 'alt', 'caption', 'description', 'mime', 'width', 'height', 'file', 'parent', 'wp_id', 'uploaded_at']),\n )\n metas.media![id] = importMeta('published')\n }\n\n // ── post types (post, page, CPTs) ──\n for (const type of postTypes) {\n const typeItems = raw.posts.filter((p) => p.type === type)\n const mid = typeModelId(type)\n const taxes = [...new Set(typeItems.flatMap((p) => p.terms.map((t) => t.taxonomy)))].filter((t) => models[taxModelId(t)])\n const { fields, order } = coreFields({\n excerpt: typeItems.some((p) => p.excerpt),\n body: typeItems.some((p) => p.content),\n date: typeItems.some((p) => p.date),\n author: typeItems.some((p) => p.author),\n taxes,\n cover: typeItems.some((p) => p.meta._thumbnail_id),\n })\n let o = order\n fields.wp_id = { type: 'integer', required: true, unique: true, label: 'WP post ID', order: (o += 10) }\n fields.modified_at = { type: 'datetime', label: 'Modified at', order: (o += 10) }\n fields.link = { type: 'url', label: 'Original permalink', order: (o += 10) }\n const parentModels = [...new Set(typeItems.flatMap((p) => {\n const parent = p.parent ? postEntry.get(p.parent) : undefined\n return parent ? [parent.model] : []\n }))].toSorted()\n if (typeItems.some((p) => p.parent)) fields.parent = {\n type: 'relation',\n model: parentModels.length > 1 ? parentModels : (parentModels[0] ?? mid),\n label: 'Parent', order: (o += 10),\n }\n if (typeItems.some((p) => p.menu_order)) fields.menu_order = { type: 'integer', label: 'Menu order', order: (o += 10) }\n if (typeItems.some((p) => p.sticky)) fields.sticky = { type: 'boolean', label: 'Sticky', order: (o += 10) }\n if (typeItems.some((p) => typeof p.meta._wp_page_template === 'string' && p.meta._wp_page_template !== 'default'))\n fields.template = { type: 'string', label: 'Page template', order: (o += 10) }\n const formats = [\n ...new Set(\n typeItems.flatMap((p) =>\n p.terms.filter((t) => t.taxonomy === 'post_format').map((t) => t.slug.replace(/^post-format-/, '')),\n ),\n ),\n ].toSorted()\n if (formats.length) fields.format = { type: 'select', options: formats, label: 'Post format', order: (o += 10) }\n if (typeItems.some((p) => p.status === 'private' || p.password))\n fields.visibility = { type: 'select', options: ['public', 'private', 'password'], label: 'Visibility', order: (o += 10) }\n if (typeItems.some((p) => p.comment_status))\n fields.comments_open = { type: 'boolean', label: 'Comments open', order: (o += 10) }\n for (const p of typeItems) {\n for (const [k, v] of Object.entries(p.meta)) {\n if (k.startsWith('_') || fields[k] || PLUGIN_META.test(k) || k === 'enclosure') continue\n const t = byValue(v)\n if (t && t !== 'object') {\n fields[k] = { type: t as FieldDef['type'], label: k, order: (o += 10) }\n report.meta_fields[k] = t\n }\n }\n for (const [k, acf] of Object.entries(p.acf ?? {})) {\n if (fields[k]) continue\n const t = byValue(acf.value) ?? 'string'\n fields[k] = { type: (t === 'object' ? 'object' : t) as FieldDef['type'], label: k, description: 'ACF', order: (o += 10) }\n report.acf_fields[k] = t\n }\n }\n // The locales this type actually has content in. A partially-translated\n // site — pages in one language, posts in three — used to fail validation on\n // every untranslated entry, because parity was checked against the whole\n // project list. Declaring the real coverage says so once, in the model.\n //\n // The default locale is always in: it is the site's source of truth, and a\n // post that carries no language tag belongs to it (`postLocale`), so its\n // absence here would be the importer's uncertainty, not a fact about the\n // site. Full coverage writes nothing — absent already means \"all\", and a\n // redundant list would then have to be maintained as locales are added.\n const covered = locales.filter(l => l === locale || typeItems.some((p) => postLocale(p) === l))\n addModel({\n id: mid,\n name: type === 'post' ? 'Posts' : type === 'page' ? 'Pages' : mid,\n kind: 'collection',\n domain: domainOf(type),\n i18n: multilingual,\n ...(multilingual && covered.length < locales.length ? { locales: covered } : {}),\n title_field: 'title',\n fields,\n })\n for (const p of typeItems) {\n const id = postEntry.get(p.id)!.ref\n const loc = postLocale(p)\n const contentBucket = multilingual ? ((localeContents[mid] ??= {})[loc] ??= {}) : contents[mid]!\n const metaBucket = multilingual ? ((localeMetas[mid] ??= {})[loc] ??= {}) : metas[mid]!\n const e: Entry = { title: titleOf(p), slug: slugOf.get(p.id), wp_id: p.id }\n if (fields.excerpt) e.excerpt = strip(p.excerpt)\n if (fields.body) e.body = p.content // Gutenberg comments and shortcodes verbatim (known gap)\n if (fields.published_at && p.date) e.published_at = p.date\n if (p.modified) e.modified_at = p.modified\n if (p.link) e.link = p.link\n if (fields.author && p.author) e.author = authorId(slugify(p.author))\n for (const t of taxes) {\n e[taxModelId(t)] = p.terms\n .filter((x) => x.taxonomy === t && contents[taxModelId(t)]![termId(t, x.slug)])\n .map((x) => termId(t, x.slug))\n }\n if (fields.cover && p.meta._thumbnail_id) {\n const m = mediaRef(Number(p.meta._thumbnail_id))\n if (m) e.cover = m\n else report.dropped_relations++\n }\n if (fields.parent && p.parent) {\n const pe = postEntry.get(p.parent)\n if (pe) e.parent = parentModels.length > 1 ? pe : pe.ref\n else report.dropped_relations++\n }\n if (fields.menu_order && p.menu_order) e.menu_order = p.menu_order\n if (fields.sticky) e.sticky = p.sticky ?? false\n if (fields.template && typeof p.meta._wp_page_template === 'string' && p.meta._wp_page_template !== 'default')\n e.template = p.meta._wp_page_template\n if (fields.format) {\n const f = p.terms.find((t) => t.taxonomy === 'post_format')\n if (f) e.format = f.slug.replace(/^post-format-/, '')\n }\n if (fields.visibility) e.visibility = p.password ? 'password' : p.status === 'private' ? 'private' : 'public'\n if (fields.comments_open) e.comments_open = p.comment_status === 'open'\n for (const k of Object.keys(fields)) if (k in p.meta && !(k in e) && !k.startsWith('_')) e[k] = p.meta[k]\n for (const [k, acf] of Object.entries(p.acf ?? {})) if (fields[k] && !(k in e)) e[k] = acf.value\n contentBucket[id] = e\n metaBucket[id] = mapStatus(p)\n }\n }\n\n // ── menus ──\n const menus = raw.menus ?? []\n if (menus.length) {\n addModel({\n id: 'menus', name: 'Menus', kind: 'collection', domain: 'site', i18n: false, title_field: 'name',\n fields: {\n name: { type: 'string', required: true, label: 'Name', order: 10 },\n slug: { type: 'slug', required: true, unique: true, label: 'Slug', order: 20 },\n items: { type: 'relations', model: 'menu-items', label: 'Items', order: 30 },\n wp_id: { type: 'integer', label: 'WP term ID', order: 40 },\n },\n })\n const toTarget = relationOver([...contentModelIds, ...taxonomies.map(taxModelId)])\n addModel({\n id: 'menu-items', name: 'Menu items', kind: 'collection', domain: 'site', i18n: false, title_field: 'title',\n fields: {\n title: { type: 'string', required: true, label: 'Label', order: 10 },\n menu: { type: 'relation', model: 'menus', required: true, label: 'Menu', order: 20 },\n order: { type: 'integer', label: 'Order', order: 30 },\n parent: { type: 'relation', model: 'menu-items', label: 'Parent item', order: 40 },\n type: { type: 'select', options: ['custom', 'post_type', 'taxonomy', 'post_type_archive'], label: 'Type', order: 50 },\n url: { type: 'url', label: 'URL', order: 60 },\n target: { type: 'relation', model: toTarget.model, label: 'Target', order: 70 },\n open_in_new_tab: { type: 'boolean', label: 'Open in new tab', order: 80 },\n classes: { type: 'array', items: 'string', label: 'CSS classes', order: 90 },\n description: { type: 'text', label: 'Description', order: 100 },\n wp_id: { type: 'integer', label: 'WP post ID', order: 110 },\n },\n })\n const itemRef = (id: number): string => hexId(`menu-items:${id}`)\n for (const m of menus) {\n const mid = hexId(`menus:${m.slug}`)\n contents.menus![mid] = {\n name: strip(m.name),\n slug: slugify(m.slug) || `menu-${m.id}`,\n items: m.items.map((i) => itemRef(i.id)),\n wp_id: m.id,\n }\n metas.menus![mid] = importMeta('published')\n for (const i of m.items) {\n const e: Entry = {\n title: strip(i.title) || i.url || `item-${i.id}`,\n menu: mid,\n order: i.order,\n type: i.target.kind === 'url' ? 'custom' : i.target.kind === 'post' ? 'post_type' : i.target.kind === 'term' ? 'taxonomy' : i.target.kind === 'archive' ? 'post_type_archive' : 'custom',\n wp_id: i.id,\n open_in_new_tab: i.target_attr === '_blank',\n }\n if (i.parent && !i.parent_unresolved) e.parent = itemRef(i.parent)\n if (i.target.kind === 'url' && i.url) e.url = i.url\n if (i.target.kind === 'post' && i.target.resolved && i.target.id != null) {\n const pe = postEntry.get(i.target.id)\n if (pe) e.target = toTarget.ref(pe)\n else report.dropped_relations++\n }\n if (i.target.kind === 'term' && i.target.resolved && i.target.slug && models[taxModelId(i.target.taxonomy)])\n e.target = toTarget.ref({ model: taxModelId(i.target.taxonomy), ref: termId(i.target.taxonomy, i.target.slug) })\n if (i.classes?.length) e.classes = i.classes\n if (i.description) e.description = strip(i.description)\n contents['menu-items']![itemRef(i.id)] = e\n metas['menu-items']![itemRef(i.id)] = importMeta(i.status === 'publish' ? 'published' : 'draft')\n }\n }\n }\n\n // ── comments (frozen archive collection; the live-service path is CommentsExport) ──\n const comments = raw.comments ?? []\n if (comments.length) {\n addModel({\n id: 'comments', name: 'Comments', kind: 'collection', domain: 'blog', i18n: false, title_field: 'author',\n fields: {\n author: { type: 'string', required: true, label: 'Author', order: 10 },\n email: { type: 'email', label: 'Email', order: 20 },\n url: { type: 'url', label: 'Website', order: 30 },\n body: { type: 'richtext', label: 'Body', order: 40 },\n published_at: { type: 'datetime', label: 'Date', order: 50 },\n post: { type: 'relation', model: toContent.model, required: true, label: 'Post', order: 60 },\n parent: { type: 'relation', model: 'comments', label: 'In reply to', order: 70 },\n type: { type: 'string', label: 'Type', order: 80 },\n user: { type: 'relation', model: 'authors', label: 'User', order: 90 },\n wp_id: { type: 'integer', label: 'WP comment ID', order: 100 },\n },\n })\n const cRef = (id: number): string => hexId(`comments:${id}`)\n const userById = new Map(raw.authors.filter((a) => a.id != null).map((a) => [a.id, authorId(slugify(a.login))]))\n for (const c of comments) {\n const post = postEntry.get(c.post)\n if (!post) {\n report.dropped_relations++\n continue\n }\n contents.comments![cRef(c.id)] = pick(\n {\n author: strip(c.author) || 'anonymous',\n email: c.email,\n url: c.url,\n body: c.content,\n published_at: c.date,\n post: toContent.ref(post),\n parent: c.parent && c.parent_resolved ? cRef(c.parent) : null,\n type: c.type,\n user: c.user_id ? userById.get(c.user_id) : null,\n wp_id: c.id,\n },\n new Set(['author', 'email', 'url', 'body', 'published_at', 'post', 'parent', 'type', 'user', 'wp_id']),\n )\n metas.comments![cRef(c.id)] = importMeta(\n c.approved === '1' ? 'published' : c.approved === 'spam' || c.approved === 'trash' ? 'archived' : 'in_review',\n )\n }\n }\n\n // ── site singleton + vocabulary ──\n addModel({\n id: 'site', name: 'Site', kind: 'singleton', domain: 'site', i18n: false, title_field: 'title',\n fields: {\n title: { type: 'string', required: true, label: 'Site title', order: 10 },\n tagline: { type: 'string', label: 'Tagline', order: 20 },\n url: { type: 'url', label: 'URL', order: 30 },\n language: { type: 'string', label: 'Language', order: 40 },\n },\n })\n siteEntry = pick(\n { title: strip(raw.site.title) || 'Site', tagline: raw.site.description, url: raw.site.url, language: raw.site.language },\n new Set(['title', 'tagline', 'url', 'language']),\n )\n siteMeta = importMeta('published')\n const vocabTerms: Record<string, Record<string, string>> = {}\n for (const m of menus) {\n for (const i of m.items) {\n const k = slugify(strip(i.title))\n if (k && !vocabTerms[k]) vocabTerms[k] = { [locale]: strip(i.title) }\n }\n }\n\n // ── file map (canonical serialization; PATH_PATTERNS layout) ──\n const files: Record<string, string> = {}\n const domains = [...new Set(Object.values(models).map((m) => m.domain))].toSorted()\n for (const m of Object.values(models)) {\n files[`.contentrain/models/${m.id}.json`] = canon(m)\n if (m.i18n) {\n // One content + meta file per locale; an entry id recurs across the\n // locales it has a translation in.\n const perLocale = localeContents[m.id] ?? {}\n const ids = new Set<string>()\n for (const loc of Object.keys(perLocale).toSorted()) {\n files[`.contentrain/content/${m.domain}/${m.id}/${loc}.json`] = canon(perLocale[loc])\n files[`.contentrain/meta/${m.id}/${loc}.json`] = canon(localeMetas[m.id]?.[loc] ?? {})\n for (const id of Object.keys(perLocale[loc]!)) ids.add(id)\n }\n report.models[m.id] = { kind: m.kind, domain: m.domain, fields: Object.keys(m.fields ?? {}).length, entries: ids.size }\n continue\n }\n const content = m.kind === 'singleton' ? siteEntry : contents[m.id]!\n const meta = m.kind === 'singleton' ? siteMeta : metas[m.id]!\n files[`.contentrain/content/${m.domain}/${m.id}/data.json`] = canon(content)\n files[`.contentrain/meta/${m.id}/${locale}.json`] = canon(meta)\n report.models[m.id] = {\n kind: m.kind,\n domain: m.domain,\n fields: Object.keys(m.fields ?? {}).length,\n entries: m.kind === 'singleton' ? 1 : Object.keys(contents[m.id]!).length,\n }\n }\n files['.contentrain/config.json'] = canon({\n version: 1,\n stack: 'astro',\n platform: 'web',\n workflow: 'review',\n locales: { default: locale, supported: locales },\n domains,\n })\n files['.contentrain/vocabulary.json'] = canon({ version: 1, terms: vocabTerms })\n\n const entrySourceMap: EntrySourceMap = {}\n for (const [wpId, ref] of postEntry) {\n entrySourceMap[String(wpId)] = { model_id: ref.model, entry_id: ref.ref, locale: postLocale(postById.get(wpId)!) }\n }\n\n files['import-report.json'] = canon(report)\n return { files, entry_source_map: entrySourceMap, report }\n}\n","// CommentsExport builder — the bridge from a migrated static site to a live\n// comments service. Everything the receiving side needs travels here: the\n// entry addresses (WordPress ids mean nothing after migration), the verbatim\n// comments, and which threads were closed at the source.\n\nimport type { CommentsExport, EntrySourceMap, HandoffComments, RawComment, RawIR } from '@contentrain/types'\nimport { COMMENTS_EXPORT_FORMAT, MIGRATION_CONTRACT_VERSION } from '@contentrain/types'\n\n/**\n * The comments that may leave the source site (see `CommentsExport.comments`). An allowlist, so it\n * fails closed: a comment travels only when its entry is in this RawIR and public, and its status is\n * approved (`'1'`, or none) or pending (`'0'`). Everything else is counted in `excluded`: spam, trash,\n * WordPress's `post-trashed`, a plugin's own status, a post this RawIR does not hold.\n */\nexport function selectComments(raw: RawIR): { comments: RawComment[]; excluded: NonNullable<CommentsExport['excluded']> } {\n const posts = new Map(raw.posts.map((p) => [p.id, p]))\n const excluded: NonNullable<CommentsExport['excluded']> = {}\n const count = (key: keyof typeof excluded) => { excluded[key] = (excluded[key] ?? 0) + 1 }\n const comments: RawComment[] = []\n for (const c of raw.comments ?? []) {\n const post = posts.get(c.post)\n if (!post) { count('unknown_entry'); continue }\n if (post.status !== 'publish' || (post.password !== null && post.password !== undefined && post.password !== '')) { count('non_public_entry'); continue }\n const status = c.approved ?? '1'\n if (status === '1' || status === '0') { comments.push(c); continue }\n count(status === 'spam' ? 'spam' : status === 'trash' ? 'trash' : 'other_status')\n }\n return { comments, excluded }\n}\n\nexport function buildCommentsExport(raw: RawIR, entries: EntrySourceMap, opts?: { generated_at?: string }): CommentsExport {\n const threadsClosed = raw.posts.filter((p) => p.comment_status && p.comment_status !== 'open').map((p) => p.id)\n const { comments, excluded } = selectComments(raw)\n return {\n version: MIGRATION_CONTRACT_VERSION,\n format: COMMENTS_EXPORT_FORMAT,\n source: raw.provenance,\n site_url: raw.site.url || undefined,\n generated_at: opts?.generated_at ?? new Date().toISOString(),\n entries,\n threads_closed: threadsClosed.length ? threadsClosed : undefined,\n comments,\n excluded: Object.keys(excluded).length ? excluded : undefined,\n }\n}\n\n/** Handoff summary for the export: counts + closed threads + what could not be addressed. */\nexport function summarizeComments(exp: CommentsExport): HandoffComments {\n const byStatus: Record<string, number> = {}\n const byType: Record<string, number> = {}\n const unresolved: Array<{ comment_id: number; post: number; reason: string }> = []\n for (const c of exp.comments) {\n byStatus[c.approved ?? '1'] = (byStatus[c.approved ?? '1'] ?? 0) + 1\n byType[c.type ?? 'comment'] = (byType[c.type ?? 'comment'] ?? 0) + 1\n if (!exp.entries[String(c.post)]) unresolved.push({ comment_id: c.id, post: c.post, reason: 'post has no entry mapping' })\n }\n return {\n total: exp.comments.length,\n by_status: byStatus,\n types: byType,\n export: { format: exp.format },\n threads_closed: exp.threads_closed,\n unresolved: unresolved.length ? unresolved : undefined,\n excluded: exp.excluded,\n }\n}\n","// SourceDeltaPlan (as a bridge produces it) + the repository's store → a plan\n// a person can review: every origin record placed in the store, or said to be\n// unplaceable and why.\n//\n// The bridge knows what changed at the origin and nothing about the store; the\n// store knows its entries and nothing about the origin. The EntrySourceMap\n// written at import time is the only link, so this module lives next to the\n// code that writes it. Pure over file maps, like `rawToContentrain`: no git,\n// no provider, and nothing is written — applying a plan is a governed write\n// that belongs to whoever reviews it.\n//\n// What the planner refuses to do is decide. A record the repository also\n// edited is flagged, not overwritten; a trashed record stays distinguishable\n// from a purged one; a record it cannot place says why instead of vanishing.\n\nimport type { EntryMeta, EntrySourceMap, ModelDefinition, SourceDeltaEntry, SourceDeltaPlan } from '@contentrain/types'\nimport { canon, taxModelId } from './core.js'\n\n/** A `.contentrain` store as a file map (repo-relative path → file text), with the source map it was built from. */\nexport interface DeltaStore {\n files: Record<string, string>\n entry_source_map: EntrySourceMap\n}\n\nexport interface PlanSourceDeltaInput {\n /** The origin delta, as the bridge wrote it. */\n delta: SourceDeltaPlan\n /** The repository's store, as it is now — including edits made since the import. */\n store: DeltaStore\n /** The new export the delta describes. Without it the plan has no field-level differences and no address for a created record. */\n incoming?: DeltaStore\n /**\n * Origin types that are taxonomies. Their ids are term ids, which the\n * source map (post ids) must never be consulted for: post 6 and category 6\n * are different records. Defaults to WordPress core's.\n */\n taxonomies?: string[]\n /**\n * `updated_by` values that mean \"written by an import\". Meta with any other\n * writer — or with a `source` other than `import` — is a repository edit.\n */\n importers?: string[]\n}\n\nexport const DEFAULT_TAXONOMIES = ['category', 'post_tag', 'nav_menu', 'post_format'] as const\nexport const DEFAULT_IMPORTERS = ['contentrain-bridge', '@contentrain/wp-import'] as const\n\ninterface Placed {\n model: ModelDefinition\n entry_id: string\n locale: string\n}\n\ntype Placement = Placed | { unmapped: NonNullable<SourceDeltaEntry['unmapped']> }\n\n/** A stored entry, reduced to what a comparison needs: each field's value as text, and its meta. */\ninterface StoredEntry {\n fields: Record<string, string>\n meta?: EntryMeta\n}\n\n// ─── Store reading ───\n\nconst parseJson = (text: string | undefined): unknown => {\n if (text === undefined) return undefined\n try {\n return JSON.parse(text)\n }\n catch {\n return undefined\n }\n}\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined\n\nfunction readModel(files: Record<string, string>, id: string): ModelDefinition | undefined {\n const model = asRecord(parseJson(files[`.contentrain/models/${id}.json`]))\n return model && model.id === id ? (model as unknown as ModelDefinition) : undefined\n}\n\nfunction defaultLocale(files: Record<string, string>): string {\n const config = asRecord(parseJson(files['.contentrain/config.json']))\n const locales = asRecord(config?.locales)\n return typeof locales?.default === 'string' ? locales.default : 'en'\n}\n\n/** The model's own directory. A custom `content_path` or locale strategy is not read — the entry is reported as not found. */\nconst contentDir = (model: ModelDefinition): string | undefined =>\n model.content_path || (model.locale_strategy && model.locale_strategy !== 'file')\n ? undefined\n : `.contentrain/content/${model.domain}/${model.id}`\n\n/**\n * A markdown document's fields as raw text: each top-level frontmatter key\n * with its value lines (a list's items included), and `body`. Compared as\n * written — the store is canonical, so equal values are equal text.\n */\nfunction documentFields(text: string): Record<string, string> {\n const fields: Record<string, string> = {}\n const match = /^---\\n([\\s\\S]*?)\\n---\\n?([\\s\\S]*)$/.exec(text)\n if (!match) return { body: text }\n let key: string | undefined\n for (const line of match[1]!.split('\\n')) {\n const top = /^([^\\s:#][^:]*):(.*)$/.exec(line)\n if (top) {\n key = top[1]!.trim()\n fields[key] = top[2]!.trim()\n }\n else if (key !== undefined) {\n fields[key] += `\\n${line}`\n }\n }\n fields.body = match[2]!\n return fields\n}\n\nfunction readEntry(files: Record<string, string>, at: Placed): StoredEntry | undefined {\n const { model, entry_id: id, locale } = at\n const dir = contentDir(model)\n if (!dir) return undefined\n if (model.kind === 'document') {\n const text = files[model.i18n ? `${dir}/${id}/${locale}.md` : `${dir}/${id}.md`]\n if (text === undefined) return undefined\n const meta = asRecord(parseJson(files[`.contentrain/meta/${model.id}/${id}/${locale}.json`]))\n return { fields: documentFields(text), meta: meta as EntryMeta | undefined }\n }\n if (model.kind !== 'collection') return undefined\n const entries = asRecord(parseJson(files[`${dir}/${model.i18n ? locale : 'data'}.json`]))\n const entry = asRecord(entries?.[id])\n if (!entry) return undefined\n const metas = asRecord(parseJson(files[`.contentrain/meta/${model.id}/${locale}.json`]))\n const fields = Object.fromEntries(Object.entries(entry).map(([key, value]) => [key, canon(value)]))\n return { fields, meta: asRecord(metas?.[id]) as EntryMeta | undefined }\n}\n\n/** The entry in `model` whose `wp_id` is `wpId`, for records the source map does not list (terms, media). */\nfunction findByWpId(files: Record<string, string>, model: ModelDefinition, wpId: number, locale: string): string | undefined {\n const dir = contentDir(model)\n if (!dir) return undefined\n if (model.kind === 'collection') {\n const entries = asRecord(parseJson(files[`${dir}/${model.i18n ? locale : 'data'}.json`])) ?? {}\n return Object.keys(entries).find(id => asRecord(entries[id])?.wp_id === wpId)\n }\n if (model.kind !== 'document') return undefined\n const suffix = model.i18n ? `/${locale}.md` : '.md'\n for (const [path, text] of Object.entries(files)) {\n if (!path.startsWith(`${dir}/`) || !path.endsWith(suffix)) continue\n if (documentFields(text).wp_id === String(wpId)) {\n const rest = path.slice(dir.length + 1, -suffix.length)\n if (!rest.includes('/')) return rest\n }\n }\n return undefined\n}\n\n/** Store models that can hold records of an origin type the source map does not cover. */\nfunction typeModelIds(wpType: string): string[] {\n if (wpType === 'attachment') return ['wp-media', 'media']\n return [`wp-tax-${wpType.replace(/_/g, '-')}`, taxModelId(wpType)]\n}\n\nfunction place(store: DeltaStore, wpType: string | undefined, wpId: number, taxonomies: Set<string>): Placement {\n const { files } = store\n const locale = defaultLocale(files)\n const models = wpType ? typeModelIds(wpType).map(id => readModel(files, id)).filter(model => model !== undefined) : []\n // A listed taxonomy, media, or any type the store has a model of its own for\n // is found by `wp_id` in that model. Only what is left falls to the map.\n if (wpType && (wpType === 'attachment' || taxonomies.has(wpType) || models.length)) {\n if (!models.length) return { unmapped: 'no-model-for-type' }\n for (const model of models) {\n const entryId = findByWpId(files, model, wpId, locale)\n if (entryId) return { model, entry_id: entryId, locale }\n }\n return { unmapped: 'entry-not-found' }\n }\n const ref = store.entry_source_map[String(wpId)]\n if (!ref) return { unmapped: 'not-in-source-map' }\n const model = readModel(files, ref.model_id)\n if (!model) return { unmapped: 'no-model-for-type' }\n return { model, entry_id: ref.entry_id, locale: ref.locale ?? locale }\n}\n\n// ─── Planning ───\n\nconst isPlaced = (placement: Placement): placement is Placed => 'model' in placement\n\nfunction repoEdit(meta: EntryMeta | undefined, importers: Set<string>): SourceDeltaEntry['repo_edit'] {\n if (!meta) return undefined\n if (meta.source === 'import' && importers.has(meta.updated_by)) return undefined\n return {\n updated_by: meta.updated_by,\n ...(meta.updated_at ? { updated_at: meta.updated_at } : {}),\n source: meta.source,\n }\n}\n\nfunction changedFields(before: StoredEntry, after: StoredEntry): string[] {\n const keys = new Set([...Object.keys(before.fields), ...Object.keys(after.fields)])\n return [...keys].filter(key => before.fields[key] !== after.fields[key]).toSorted()\n}\n\nconst DELETED_DETAIL = {\n trashed: 'tombstone: trashed at the origin — it can still come back',\n purged: 'tombstone: purged from the origin',\n} as const\n\nfunction planEntry(entry: SourceDeltaEntry, input: PlanSourceDeltaInput, taxonomies: Set<string>, importers: Set<string>): SourceDeltaEntry {\n const { store, incoming } = input\n const out: SourceDeltaEntry = { ...entry }\n // The bridge's detail for a deletion is the kind itself; the tombstone note below says it in full.\n const notes: string[] = entry.detail && entry.detail !== entry.deleted_kind ? [entry.detail] : []\n\n // A created record is not in the store yet; its address comes from the export that carries it.\n const target = entry.op === 'created'\n ? (incoming ? place(incoming, entry.wp_type, entry.wp_id, taxonomies) : { unmapped: 'not-in-source-map' as const })\n : place(store, entry.wp_type, entry.wp_id, taxonomies)\n\n if (!isPlaced(target)) {\n out.unmapped = target.unmapped\n if (entry.op === 'created' && !incoming) notes.push('no incoming export to place it')\n if (entry.op === 'deleted' && entry.deleted_kind) notes.push(DELETED_DETAIL[entry.deleted_kind])\n out.detail = notes.join('; ')\n return out\n }\n\n out.model = target.model.id\n out.entry_id = target.entry_id\n out.locale = target.locale\n const stored = readEntry(store.files, target)\n\n if (entry.op === 'created') {\n if (stored) notes.push('the store already has an entry at this address')\n }\n else if (!stored) {\n out.unmapped = 'entry-not-found'\n }\n\n if (entry.op === 'deleted' && entry.deleted_kind) notes.push(DELETED_DETAIL[entry.deleted_kind])\n\n if ((entry.op === 'updated' || entry.op === 'moved') && stored) {\n const after = incoming ? place(incoming, entry.wp_type, entry.wp_id, taxonomies) : undefined\n const next = after && isPlaced(after) ? readEntry(incoming!.files, after) : undefined\n if (next) {\n out.fields_changed = changedFields(stored, next)\n if (isPlaced(after!) && after.entry_id !== target.entry_id) out.entry_id_after = after.entry_id\n }\n else {\n notes.push(incoming ? 'not in the incoming export' : 'no incoming export to compare with')\n }\n }\n\n const edit = repoEdit(stored?.meta, importers)\n if (edit) {\n out.conflict = true\n out.repo_edit = edit\n notes.push(`also edited in the repository by ${edit.updated_by}${edit.updated_at ? ` at ${edit.updated_at}` : ''} — not overwritten`)\n }\n\n if (notes.length) out.detail = notes.join('; ')\n return out\n}\n\n/**\n * Place a bridge's source delta in the repository's store.\n *\n * Every entry keeps the bridge's facts (op, ids, fingerprints, paths,\n * `deleted_kind`) and gains its store address — or `unmapped` with the reason.\n * `updated` and `moved` gain `fields_changed` against the incoming export; a\n * record the repository also edited gets `conflict: true` and `repo_edit`;\n * every `moved` whose address changed adds a 301 to `redirects`.\n *\n * Nothing is written and nothing is decided: a conflict is reported for a\n * person to resolve, and applying the plan is a separate, governed step.\n */\nexport function planSourceDelta(input: PlanSourceDeltaInput): SourceDeltaPlan {\n const taxonomies = new Set<string>(input.taxonomies ?? DEFAULT_TAXONOMIES)\n const importers = new Set<string>(input.importers ?? DEFAULT_IMPORTERS)\n const { delta } = input\n const entries = delta.entries.map(entry => planEntry(entry, input, taxonomies, importers))\n\n const redirects = [...(delta.redirects ?? [])]\n const seen = new Set(redirects.map(redirect => redirect.from))\n for (const entry of entries) {\n if (entry.op !== 'moved' || !entry.path_before || !entry.path_after || entry.path_before === entry.path_after) continue\n if (seen.has(entry.path_before)) continue\n seen.add(entry.path_before)\n redirects.push({ from: entry.path_before, to: entry.path_after, status: 301 })\n }\n\n const warnings = [...(delta.warnings ?? [])]\n if (!delta.deletions_detectable) warnings.push('deletions could not be determined from this cursor; the absence of a deleted entry does not mean nothing was deleted')\n if (delta.deletions_undetectable_types?.length) warnings.push(`deletions could not be determined for: ${delta.deletions_undetectable_types.join(', ')}`)\n if (!input.incoming) warnings.push('no incoming export: no field-level differences and no address for created records')\n\n return {\n ...delta,\n entries,\n ...(redirects.length ? { redirects } : {}),\n ...(warnings.length ? { warnings } : {}),\n }\n}\n\n// ─── Report ───\n\nconst address = (entry: SourceDeltaEntry): string =>\n entry.model && entry.entry_id ? `${entry.model}/${entry.entry_id}${entry.entry_id_after ? ` → ${entry.entry_id_after}` : ''}` : `unmapped (${entry.unmapped})`\n\n/** The plan as text, for a dry run: one line per record, then conflicts, unmapped records, redirects and warnings. */\nexport function formatSourceDeltaReport(plan: SourceDeltaPlan): string {\n const counts = new Map<string, number>()\n for (const entry of plan.entries) counts.set(entry.op, (counts.get(entry.op) ?? 0) + 1)\n const summary = [...counts].map(([op, n]) => `${n} ${op}`).join(', ') || 'no changes'\n const { cursor } = plan\n const lines = [\n `Source delta: ${plan.entries.length} records (${summary})`,\n `Cursor: ${[cursor.kind, cursor.inventory_hash ?? cursor.modified_after ?? cursor.export_id, `(${cursor.taken_at})`].filter(Boolean).join(' ')}`,\n `Deletions: ${plan.deletions_detectable ? 'detectable' : 'NOT detectable'}`,\n '',\n ]\n for (const entry of plan.entries) {\n const parts = [`${entry.op.padEnd(8)} ${entry.wp_type ?? '?'} ${entry.wp_id}`, address(entry)]\n if (entry.op === 'moved' && entry.path_before) parts.push(`${entry.path_before} → ${entry.path_after}`)\n if (entry.deleted_kind) parts.push(entry.deleted_kind)\n if (entry.fields_changed) parts.push(`fields: ${entry.fields_changed.join(', ') || 'none'}`)\n if (entry.conflict) parts.push('CONFLICT')\n lines.push(` ${parts.join(' ')}`)\n }\n const conflicts = plan.entries.filter(entry => entry.conflict)\n const unmapped = plan.entries.filter(entry => entry.unmapped)\n lines.push('', `Conflicts (${conflicts.length})${conflicts.length ? ':' : ''}`)\n for (const entry of conflicts) lines.push(` ${entry.wp_type} ${entry.wp_id} → ${address(entry)}: edited by ${entry.repo_edit?.updated_by}${entry.repo_edit?.updated_at ? ` at ${entry.repo_edit.updated_at}` : ''}`)\n lines.push(`Unmapped (${unmapped.length})${unmapped.length ? ':' : ''}`)\n for (const entry of unmapped) lines.push(` ${entry.op} ${entry.wp_type} ${entry.wp_id}: ${entry.unmapped}`)\n lines.push(`Redirects (${plan.redirects?.length ?? 0})${plan.redirects?.length ? ':' : ''}`)\n for (const redirect of plan.redirects ?? []) lines.push(` ${redirect.from} → ${redirect.to} (${redirect.status})`)\n for (const warning of plan.warnings ?? []) lines.push(`Warning: ${warning}`)\n lines.push('', 'Dry run: nothing was written. Applying a plan goes through review.')\n return `${lines.join('\\n')}\\n`\n}\n"],"mappings":";;;;AAWA,SAAgB,gBAAgB,GAAyB;AACvD,QAAO,OAAO,MAAM,YAAY,2CAA2C,KAAK,EAAE;;AAGpF,SAAgB,eAAe,KAAsB;CACnD,MAAM,MAAM,OAAO,KAAK,KAAK,OAAO;CACpC,IAAI,IAAI;CACR,MAAM,QAAQ,MAAqB;AACjC,QAAM,IAAI,MAAM,gBAAgB,EAAE,WAAW,IAAI;;CAEnD,MAAM,aAAa,OAAuB;EACxC,MAAM,IAAI,IAAI,QAAQ,IAAI,EAAE;AAC5B,MAAI,IAAI,EAAG,MAAK,YAAY,KAAK;EACjC,MAAM,IAAI,IAAI,SAAS,QAAQ,GAAG,EAAE;AACpC,MAAI,IAAI;AACR,SAAO;;CAET,MAAM,UAAU,OAAqB;AACnC,MAAI,IAAI,OAAO,GAAG,WAAW,EAAE,CAAE,MAAK,aAAa,GAAG,SAAS,OAAO,aAAa,IAAI,MAAM,EAAE,CAAC,GAAG;AACnG;;CAEF,MAAM,cAAuB;EAC3B,MAAM,IAAI,OAAO,aAAa,IAAI,MAAM,EAAE;AAC1C;AACA,UAAQ,GAAR;GACE,KAAK;AACH,WAAO,IAAI;AACX,WAAO;GACT,KAAK;AACH,WAAO,IAAI;AACX,WAAO,UAAU,IAAI,KAAK;GAE5B,KAAK;AACH,WAAO,IAAI;AACX,WAAO,OAAO,UAAU,IAAI,CAAC;GAE/B,KAAK,KAAK;AACR,WAAO,IAAI;IACX,MAA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,SAAS,MAAM,KAAK;AAC5F,MAAK,MAAM,YAAY,KAAK,aAAa,EAAE,CAAE,OAAM,KAAK,KAAK,SAAS,KAAK,KAAK,SAAS,GAAG,IAAI,SAAS,OAAO,GAAG;AACnH,MAAK,MAAM,WAAW,KAAK,YAAY,EAAE,CAAE,OAAM,KAAK,YAAY,UAAU;AAC5E,OAAM,KAAK,IAAI,qEAAqE;AACpF,QAAO,GAAG,MAAM,KAAK,KAAK,CAAC"}
1
+ {"version":3,"file":"index.mjs","names":["iso"],"sources":["../src/php-unserialize.ts","../src/core.ts","../src/wxr.ts","../src/rest-menus.ts","../src/rest.ts","../src/contentrain.ts","../src/comments.ts","../src/delta.ts"],"sourcesContent":["// Small PHP serialize() decoder, ported from the measured import chain.\n// Supported: s (byte-length strings), i, d, b, N, a (array → list or object), O (object → { __class, … }).\n// PHP string lengths are BYTES, so the walk happens over a Buffer, not a JS string.\n\nexport interface UnserializeResult {\n ok: boolean\n serialized: boolean\n value: unknown\n error?: string\n}\n\nexport function looksSerialized(s: unknown): s is string {\n return typeof s === 'string' && /^(a|O):\\d+:[{\"]|^(s|i|d|b):[^;]+;?$|^N;$/.test(s)\n}\n\nexport function phpUnserialize(str: string): unknown {\n const buf = Buffer.from(str, 'utf8')\n let p = 0\n const fail = (m: string): never => {\n throw new Error(`unserialize: ${m} at byte ${p}`)\n }\n const readUntil = (ch: string): string => {\n const i = buf.indexOf(ch, p)\n if (i < 0) fail(`expected ${ch}`)\n const s = buf.toString('utf8', p, i)\n p = i + 1\n return s\n }\n const expect = (ch: string): void => {\n if (buf[p] !== ch.charCodeAt(0)) fail(`expected '${ch}' got '${String.fromCharCode(buf[p] ?? 0)}'`)\n p++\n }\n const value = (): unknown => {\n const t = String.fromCharCode(buf[p] ?? 0)\n p++\n switch (t) {\n case 'N':\n expect(';')\n return null\n case 'b': {\n expect(':')\n return readUntil(';') === '1'\n }\n case 'i': {\n expect(':')\n return Number(readUntil(';'))\n }\n case 'd': {\n expect(':')\n const v = readUntil(';')\n return v === 'INF' ? Infinity : v === '-INF' ? -Infinity : v === 'NAN' ? Number.NaN : Number(v)\n }\n case 's': {\n expect(':')\n const n = Number(readUntil(':'))\n expect('\"')\n const s = buf.toString('utf8', p, p + n)\n p += n\n expect('\"')\n expect(';')\n return s\n }\n case 'a': {\n expect(':')\n const n = Number(readUntil(':'))\n expect('{')\n const entries: Array<[unknown, unknown]> = []\n for (let i = 0; i < n; i++) {\n const k = value()\n const v = value()\n entries.push([k, v])\n }\n expect('}')\n // consecutive 0..n-1 integer keys → JSON list; anything else → object\n const isList = entries.every(([k], i) => k === i)\n return isList ? entries.map(([, v]) => v) : Object.fromEntries(entries.map(([k, v]) => [String(k), v]))\n }\n case 'O': {\n expect(':')\n readUntil(':')\n expect('\"')\n const cls = readUntil('\"')\n expect(':')\n const n = Number(readUntil(':'))\n expect('{')\n const o: Record<string, unknown> = { __class: cls }\n for (let i = 0; i < n; i++) {\n const k = value()\n const v = value()\n o[String(k).split('\\u0000').at(-1) ?? String(k)] = v\n }\n expect('}')\n return o\n }\n default:\n return fail(`unknown type '${t}'`)\n }\n }\n const v = value()\n if (p !== buf.length) fail(`trailing ${buf.length - p} bytes`)\n return v\n}\n\n/** Attempt a decode; on failure the value stays exactly as it was. */\nexport function tryUnserialize(s: string): UnserializeResult {\n if (!looksSerialized(s)) return { ok: false, serialized: false, value: s }\n try {\n return { ok: true, serialized: true, value: phpUnserialize(s) }\n } catch (e) {\n return { ok: false, serialized: true, value: s, error: e instanceof Error ? e.message : String(e) }\n }\n}\n","// Shared conversion helpers, ported from the measured induction core.\n// The identity formulas here are load-bearing: hexId('posts:' + slug) must\n// produce the same entry id whether the site arrived via WXR or REST, or a\n// later delta import would duplicate every entry.\n\nimport { createHash } from 'node:crypto'\nimport type { FieldDef } from '@contentrain/types'\n\nexport const norm = (s: unknown): string => String(s ?? '').replace(/\\s+/g, ' ').trim()\n\nexport const strip = (s: unknown): string =>\n norm(\n String(s ?? '')\n .replace(/<[^>]*>/g, ' ')\n .replace(/&#(\\d+);/g, (_m, d: string) => String.fromCodePoint(Number(d)))\n .replace(/&amp;/g, '&'),\n )\n\n/** Entry id: deterministic hex from a stable key (model:slug style). */\nexport const hexId = (s: string): string => createHash('sha1').update(s).digest('hex').slice(0, 24)\n\nconst sortDeep = (v: unknown): unknown =>\n Array.isArray(v)\n ? v.map(sortDeep)\n : v && typeof v === 'object'\n ? Object.fromEntries(\n Object.keys(v as Record<string, unknown>)\n .toSorted()\n .map((k) => [k, sortDeep((v as Record<string, unknown>)[k])]),\n )\n : v\n\n/** Canonical serialization: sorted keys, 2-space indent, trailing newline. */\nexport const canon = (o: unknown): string => `${JSON.stringify(sortDeep(o), null, 2)}\\n`\n\n/** Field-type inference from a value (open meta / ACF fields). */\nexport const byValue = (v: unknown): string | null => {\n if (typeof v === 'boolean') return 'boolean'\n if (typeof v === 'number') return Number.isInteger(v) ? 'integer' : 'decimal'\n if (Array.isArray(v)) return 'array'\n if (v && typeof v === 'object') return 'object'\n const s = String(v ?? '').trim()\n if (!s) return null\n if (/^https?:\\/\\/\\S+\\.(mp3|m4a|wav|pdf|zip|docx?)(\\?|$)/i.test(s)) return 'file'\n if (/^https?:\\/\\/\\S+\\.(jpe?g|png|gif|webp|avif|svg)(\\?|$)/i.test(s)) return 'image'\n if (/^https?:\\/\\//.test(s)) return 'url'\n if (/^[^@\\s]+@[^@\\s]+\\.[a-z]{2,}$/i.test(s)) return 'email'\n if (/^\\d{4}-\\d{2}-\\d{2}([T ]\\d{2}:\\d{2})/.test(s)) return 'datetime'\n if (/<[a-z][\\s\\S]*>/i.test(s)) return 'richtext'\n return s.length > 200 ? 'text' : 'string'\n}\n\n/** What `RawPost.password` holds for a protected post: the fact, never the password. */\nexport const PROTECTED = '[protected]'\n\n/**\n * WP post types that never become content models: core plumbing (`wp_*`\n * covers `wp_global_styles`, `wp_navigation`, `wp_block`, `wp_template*`),\n * Jetpack, and theme/page-builder internals that store design, not content —\n * GeneratePress elements, GenerateBlocks styles, Elementor templates and\n * Contact Form 7 / WPForms definitions. ACF field/group records stay in:\n * their cross-model parent links are part of the lossless import contract.\n * Whether a stored record gets a public route is the route producer's decision.\n */\nexport const SKIP_TYPES =\n /^(attachment|nav_menu_item|wp_|jp_|pattern|revision|oembed_cache|customize_changeset|user_request|custom_css|gblocks_|gblocks-|gp_elements|gp-elements|elementor_library|e-landing-page|wpcf7_contact_form|wpforms)/\n\n/** Open meta keys that are plugin plumbing, not editorial fields. */\nexport const PLUGIN_META = /^(jetpack|wpdc|discourse|footnotes|inline_featured|spay_|advanced_seo|rank_math|yoast)/i\n\n/** WP core/plumbing meta keys (never editorial). */\nexport const CORE_META =\n /^(_edit_last|_edit_lock|_thumbnail_id|_wp_page_template|_wp_old_slug|_wp_attached_file|_wp_attachment_metadata|_wp_attachment_image_alt|_wp_attachment_backup_sizes|_wp_desired_post_slug|_wp_trash_meta_.*|_menu_item_.*|_oembed_.*|_publicize_.*|_wpas_.*|_pingme|_encloseme|enclosure|_last_editor_used_jetpack|_rest_api_.*|_wp_attachment_context|_wp_attachment_is_custom_header|_wp_attachment_is_custom_background|_customize_.*|_elementor_.*|_wpcom_.*|_wp_suggested_privacy_policy_content|geo_.*|_jetpack_.*|_links_to.*|_format_.*)$/\n\n/** Taxonomy → model id. */\nexport const taxModelId = (t: string): string =>\n t === 'post_tag' ? 'tags' : t === 'category' ? 'categories' : t.replace(/_/g, '-')\n\nexport const slugify = (s: unknown): string =>\n String(s ?? '')\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n\nexport const decodeSlug = (s: string): string => {\n try {\n return decodeURIComponent(s)\n } catch {\n return s\n }\n}\n\n/** The measured core field skeleton for content models (same order/labels). */\nexport function coreFields(opts: {\n excerpt: boolean\n body: boolean\n date: boolean\n author: boolean\n taxes: string[]\n cover: boolean\n}): { fields: Record<string, FieldDef>; order: number } {\n const fields: Record<string, FieldDef> = {\n title: { type: 'string', required: true, label: 'Title', order: 10 },\n slug: { type: 'slug', required: true, unique: true, label: 'Slug', order: 20 },\n }\n let o = 30\n if (opts.excerpt) fields.excerpt = { type: 'text', label: 'Excerpt', order: (o += 10) }\n if (opts.body) fields.body = { type: 'richtext', label: 'Body', order: (o += 10) }\n if (opts.date) fields.published_at = { type: 'datetime', label: 'Published at', order: (o += 10) }\n if (opts.author) fields.author = { type: 'relation', model: 'authors', label: 'Author', order: (o += 10) }\n for (const t of opts.taxes) fields[taxModelId(t)] = { type: 'relations', model: taxModelId(t), label: t, order: (o += 10) }\n if (opts.cover) fields.cover = { type: 'relation', model: 'media', label: 'Cover', order: (o += 10) }\n return { fields, order: o }\n}\n","// WXR (WordPress eXtended RSS) → RawIR.\n//\n// Streaming (sax) parse: a 100 MB export holds only its records in memory,\n// never the XML. Ported from the measured import chain — the state machine,\n// the meta decoding, and the resolution passes are the parts three sessions\n// of corpus work already debugged; they are transliterated, not redesigned.\n\nimport sax from 'sax'\nimport type { Readable } from 'node:stream'\nimport type {\n RawIR,\n RawPost,\n RawLanguagePair,\n RawAttachment,\n RawAuthor,\n RawComment,\n RawMenu,\n RawMenuItem,\n RawMenuTarget,\n RawTerm,\n RawTermRef,\n RawAcfValue,\n} from '@contentrain/types'\nimport { MIGRATION_CONTRACT_VERSION } from '@contentrain/types'\nimport { tryUnserialize } from './php-unserialize.js'\nimport { strip, PROTECTED } from './core.js'\n\nexport interface WxrStats {\n serialized: { detected: number; decoded: number; failed: number; keys: string[] }\n acf_fields: number\n unresolved_terms: number\n counts: Record<string, number>\n}\n\nexport interface WxrParseResult {\n raw: RawIR\n stats: WxrStats\n}\n\ninterface XItem {\n [k: string]: unknown\n terms: Array<{ taxonomy: string; slug: string; name?: string }>\n postmeta: Array<{ key?: string; value?: string }>\n comments: Array<Record<string, string | Array<{ key?: string; value?: string }>>>\n}\n\nconst ts = (s: string | undefined): string | null =>\n !s || s.startsWith('0000-00-00') ? null : s.replace(' ', 'T')\nconst iso = (local: string | undefined, gmt: string | undefined): string | null =>\n gmt && !gmt.startsWith('0000') ? `${ts(gmt)}Z` : ts(local)\nconst num = (s: unknown): number => (s === '' || s == null ? 0 : Number(s))\nconst termKey = (tax: string, slug: string): string => `${tax}:${slug}`\n\nexport async function parseWxr(input: string | Readable, opts?: { tool?: string }): Promise<WxrParseResult> {\n const site: Record<string, unknown> = {}\n const authors: Array<Record<string, string>> = []\n const terms: Array<Record<string, string>> = []\n const items: XItem[] = []\n const stats: WxrStats = {\n serialized: { detected: 0, decoded: 0, failed: 0, keys: [] },\n acf_fields: 0,\n unresolved_terms: 0,\n counts: {},\n }\n const serializedKeySet = new Set<string>()\n\n // ── sax state machine (ported verbatim) ──\n const parser = sax.createStream(true, { trim: false })\n const path: string[] = []\n let text = ''\n let item: XItem | null = null\n let meta: { key?: string; value?: string } | null = null\n let comment: Record<string, string | Array<{ key?: string; value?: string }>> | null = null\n let cmeta: { key?: string; value?: string } | null = null\n let author: Record<string, string> | null = null\n let term: (Record<string, string> & { _tag?: string }) | null = null\n const channelText: Record<string, string> = {}\n\n const leaf = (name: string, into: Record<string, unknown>, map: Record<string, string>): void => {\n const target = map[name]\n if (target) into[target] = text\n }\n parser.on('opentag', (node) => {\n path.push(node.name)\n text = ''\n const n = node.name\n if (n === 'item') item = { terms: [], postmeta: [], comments: [] }\n else if (n === 'wp:postmeta') meta = {}\n else if (n === 'wp:comment') comment = { meta: [] }\n else if (n === 'wp:commentmeta') cmeta = {}\n else if (n === 'wp:author') author = {}\n else if (n === 'wp:category' || n === 'wp:tag' || n === 'wp:term') term = { _tag: n }\n else if (n === 'category' && item) {\n const attrs = node.attributes as Record<string, string>\n item.terms.push({ taxonomy: attrs.domain ?? '', slug: attrs.nicename ?? '' })\n }\n })\n parser.on('text', (t) => {\n text += t\n })\n parser.on('cdata', (t) => {\n text += t\n })\n parser.on('comment', (c) => {\n const m = /generator=\"([^\"]*)\"\\s+created=\"([^\"]*)\"/.exec(c)\n if (m) {\n site.generator = m[1]\n site.export_date = m[2]\n }\n })\n parser.on('closetag', (n) => {\n const parent = path[path.length - 2]\n if (cmeta) {\n if (n === 'wp:meta_key') cmeta.key = text\n else if (n === 'wp:meta_value') cmeta.value = text\n else if (n === 'wp:commentmeta') {\n ;(comment!.meta as Array<{ key?: string; value?: string }>).push(cmeta)\n cmeta = null\n }\n } else if (comment) {\n const map: Record<string, string> = {\n 'wp:comment_id': 'id',\n 'wp:comment_author': 'author',\n 'wp:comment_author_email': 'email',\n 'wp:comment_author_url': 'url',\n 'wp:comment_date': 'date',\n 'wp:comment_date_gmt': 'date_gmt',\n 'wp:comment_content': 'content',\n 'wp:comment_approved': 'approved',\n 'wp:comment_type': 'type',\n 'wp:comment_parent': 'parent',\n 'wp:comment_user_id': 'user_id',\n }\n leaf(n, comment, map)\n if (n === 'wp:comment') {\n item!.comments.push(comment)\n comment = null\n }\n } else if (meta) {\n if (n === 'wp:meta_key') meta.key = text\n else if (n === 'wp:meta_value') meta.value = text\n else if (n === 'wp:postmeta') {\n item!.postmeta.push(meta)\n meta = null\n }\n } else if (item) {\n if (n === 'category') {\n const t = item.terms.at(-1)\n if (t) t.name = text\n } else {\n const map: Record<string, string> = {\n title: 'title',\n link: 'link',\n 'dc:creator': 'author',\n guid: 'guid',\n description: 'description',\n 'content:encoded': 'content',\n 'excerpt:encoded': 'excerpt',\n 'wp:post_id': 'id',\n 'wp:post_date': 'date',\n 'wp:post_date_gmt': 'date_gmt',\n 'wp:post_modified': 'modified',\n 'wp:post_modified_gmt': 'modified_gmt',\n 'wp:comment_status': 'comment_status',\n 'wp:ping_status': 'ping_status',\n 'wp:post_name': 'slug',\n 'wp:status': 'status',\n 'wp:post_parent': 'parent',\n 'wp:menu_order': 'menu_order',\n 'wp:post_type': 'type',\n 'wp:post_password': 'password',\n 'wp:is_sticky': 'sticky',\n 'wp:attachment_url': 'attachment_url',\n }\n leaf(n, item, map)\n if (n === 'item') {\n items.push(item)\n item = null\n }\n }\n } else if (author) {\n leaf(n, author, {\n 'wp:author_id': 'id',\n 'wp:author_login': 'login',\n 'wp:author_email': 'email',\n 'wp:author_display_name': 'display_name',\n 'wp:author_first_name': 'first_name',\n 'wp:author_last_name': 'last_name',\n })\n if (n === 'wp:author') {\n authors.push(author)\n author = null\n }\n } else if (term) {\n leaf(n, term, {\n 'wp:term_id': 'id',\n 'wp:category_nicename': 'slug',\n 'wp:category_parent': 'parent',\n 'wp:cat_name': 'name',\n 'wp:category_description': 'description',\n 'wp:tag_slug': 'slug',\n 'wp:tag_name': 'name',\n 'wp:tag_description': 'description',\n 'wp:term_taxonomy': 'taxonomy',\n 'wp:term_slug': 'slug',\n 'wp:term_parent': 'parent',\n 'wp:term_name': 'name',\n 'wp:term_description': 'description',\n })\n if (n === term._tag) {\n term.taxonomy = term._tag === 'wp:category' ? 'category' : term._tag === 'wp:tag' ? 'post_tag' : (term.taxonomy ?? '')\n delete term._tag\n terms.push(term)\n term = null\n }\n } else if (parent === 'channel') {\n leaf(n, channelText, {\n title: 'title',\n link: 'link',\n description: 'description',\n language: 'language',\n 'wp:wxr_version': 'wxr_version',\n 'wp:base_site_url': 'base_site_url',\n 'wp:base_blog_url': 'base_blog_url',\n })\n }\n path.pop()\n text = ''\n })\n\n await new Promise<void>((resolve, reject) => {\n parser.on('end', () => resolve())\n parser.on('error', reject)\n if (typeof input === 'string') {\n parser.end(input)\n } else {\n input.pipe(parser)\n }\n })\n Object.assign(site, channelText)\n\n // ── post-processing: meta decode, ACF pairing, entity split, resolution flags ──\n const decodeMeta = (list: Array<{ key?: string; value?: string }>): { meta: Record<string, unknown>; serializedKeys: string[] } => {\n const out: Record<string, unknown> = {}\n const serializedKeys: string[] = []\n for (const { key, value } of list) {\n if (!key) continue\n const r = tryUnserialize(value ?? '')\n if (r.serialized) {\n stats.serialized.detected++\n serializedKeySet.add(key)\n if (r.ok) {\n stats.serialized.decoded++\n serializedKeys.push(key)\n } else stats.serialized.failed++\n }\n const v = r.ok ? r.value : (value ?? '')\n out[key] = key in out ? ([] as unknown[]).concat(out[key] as unknown[], [v]) : v\n }\n return { meta: out, serializedKeys }\n }\n const extractAcf = (metaObj: Record<string, unknown>): Record<string, RawAcfValue> => {\n const acf: Record<string, RawAcfValue> = {}\n for (const [k, v] of Object.entries(metaObj)) {\n if (k.startsWith('_') && typeof v === 'string' && /^field_[0-9a-f]+$/.test(v) && k.slice(1) in metaObj) {\n acf[k.slice(1)] = { value: metaObj[k.slice(1)], field_key: v }\n }\n }\n return acf\n }\n\n const termSet = new Set(terms.map((t) => termKey(t.taxonomy ?? '', t.slug ?? '')))\n\n interface Rec extends RawPost {\n attachment_url: string | null\n _comments: RawComment[]\n }\n const records: Rec[] = items.map((it) => {\n const { meta: m, serializedKeys } = decodeMeta(it.postmeta)\n const acf = extractAcf(m)\n stats.acf_fields += Object.keys(acf).length\n const id = num(it.id)\n const termRefs: RawTermRef[] = it.terms.map((t) => ({\n taxonomy: t.taxonomy,\n slug: t.slug,\n name: t.name ?? '',\n resolved: termSet.has(termKey(t.taxonomy, t.slug)),\n }))\n const comments: RawComment[] = it.comments.map((c) => ({\n id: num(c.id),\n post: id,\n post_type: (it.type as string) || 'post',\n parent: num(c.parent) || null,\n parent_resolved: null,\n author: (c.author as string) ?? '',\n email: (c.email as string) || null,\n url: (c.url as string) || null,\n date: iso(c.date as string, c.date_gmt as string),\n date_gmt: ts(c.date_gmt as string),\n content: (c.content as string) ?? '',\n approved: (c.approved as string | undefined) ?? '1',\n type: (c.type as string) || 'comment',\n user_id: num(c.user_id) || null,\n meta: decodeMeta((c.meta as Array<{ key?: string; value?: string }>) ?? []).meta,\n }))\n return {\n id,\n type: (it.type as string) || 'post',\n status: (it.status as string) || 'publish',\n slug: (it.slug as string) || '',\n title: (it.title as string) ?? '',\n link: (it.link as string) || null,\n guid: (it.guid as string) || null,\n author: (it.author as string) || null,\n date: iso(it.date as string, it.date_gmt as string),\n modified: iso(it.modified as string, it.modified_gmt as string),\n content: (it.content as string) ?? '',\n excerpt: (it.excerpt as string) ?? '',\n parent: num(it.parent) || null,\n menu_order: num(it.menu_order),\n sticky: it.sticky === '1',\n password: it.password ? PROTECTED : null,\n comment_status: (it.comment_status as string) || null,\n ping_status: (it.ping_status as string) || null,\n terms: termRefs,\n meta: m,\n serialized_keys: serializedKeys,\n acf,\n // Polylang exports a post's language as a `language` taxonomy term.\n lang: termRefs.find((t) => t.taxonomy === 'language')?.slug || null,\n attachment_url: (it.attachment_url as string) || null,\n _comments: comments,\n }\n })\n for (const r of records) {\n for (const t of r.terms) if (!t.resolved && r.type !== 'nav_menu_item') stats.unresolved_terms++\n }\n\n const byId = new Map(records.map((r) => [r.id, r]))\n const posts: RawPost[] = records\n .filter((r) => r.type !== 'attachment' && r.type !== 'nav_menu_item')\n .map(({ attachment_url: _a, _comments: _c, ...p }) => p)\n // Polylang groups translations under a shared `post_translations` term\n // (`pll_…`); every post in a group is a translation of the others.\n const groups = new Map<string, RawPost[]>()\n for (const p of posts) {\n const group = p.terms.find((t) => t.taxonomy === 'post_translations')?.slug\n if (!group) continue\n groups.set(group, [...(groups.get(group) ?? []), p])\n }\n const languagePairs: RawLanguagePair[] = []\n for (const members of groups.values()) {\n const translations: Record<string, number> = {}\n for (const m of members) if (m.lang) translations[m.lang] = m.id\n if (Object.keys(translations).length > 1) languagePairs.push({ post: members[0]!.id, translations })\n }\n const attachments: RawAttachment[] = records\n .filter((r) => r.type === 'attachment')\n .map((r) => ({\n id: r.id,\n title: r.title,\n slug: r.slug,\n url: r.attachment_url ?? r.guid ?? null,\n alt: typeof r.meta._wp_attachment_image_alt === 'string' ? r.meta._wp_attachment_image_alt : '',\n caption: r.excerpt,\n description: r.content,\n file: typeof r.meta._wp_attached_file === 'string' ? r.meta._wp_attached_file : null,\n image_meta: r.meta._wp_attachment_metadata ?? null,\n mime: guessMime(r.attachment_url ?? r.guid ?? ''),\n parent: r.parent,\n parent_resolved: r.parent ? byId.has(r.parent) : null,\n author: r.author,\n date: r.date,\n status: r.status,\n meta: r.meta,\n }))\n\n // ── menus: nav_menu terms + nav_menu_item posts (targets from meta) ──\n const postById = new Map(posts.map((p) => [p.id, p]))\n const termByIdNum = new Map(terms.map((t) => [num(t.id), t]))\n const menus: RawMenu[] = terms\n .filter((t) => t.taxonomy === 'nav_menu')\n .map((mt) => ({ id: num(mt.id) || null, slug: mt.slug ?? '', name: mt.name ?? '', items: [] as RawMenuItem[] }))\n const menuBySlug = new Map(menus.map((m) => [m.slug, m]))\n for (const r of records.filter((x) => x.type === 'nav_menu_item')) {\n const m = r.meta\n const type = m._menu_item_type as string | undefined\n const object = m._menu_item_object as string | undefined\n const objectId = num(m._menu_item_object_id)\n let target: RawMenuTarget\n if (type === 'custom') target = { kind: 'url', url: String(m._menu_item_url ?? ''), resolved: true }\n else if (type === 'post_type') {\n const p = postById.get(objectId)\n target = { kind: 'post', post_type: object ?? '', id: objectId || null, slug: p?.slug ?? null, resolved: !!p }\n } else if (type === 'taxonomy') {\n const t = termByIdNum.get(objectId)\n target = { kind: 'term', taxonomy: object ?? '', id: objectId || null, slug: t?.slug ?? null, resolved: !!t }\n } else if (type === 'post_type_archive') target = { kind: 'archive', post_type: object ?? '', resolved: true }\n else target = { kind: 'unknown', resolved: false }\n const parent = num(m._menu_item_menu_item_parent) || null\n const itemRec: RawMenuItem = {\n id: r.id,\n title: r.title || (('slug' in target && target.slug) || '') || '',\n order: r.menu_order,\n parent,\n url: (m._menu_item_url as string) || null,\n target,\n target_attr: (m._menu_item_target as string) || null,\n classes: ([] as string[]).concat((m._menu_item_classes as string[]) ?? []).filter(Boolean),\n description: r.content,\n status: r.status,\n }\n const menuSlug = r.terms.find((t) => t.taxonomy === 'nav_menu')?.slug\n const menu = menuSlug ? menuBySlug.get(menuSlug) : undefined\n if (menu) menu.items.push(itemRec)\n }\n const allMenuItemIds = new Set(menus.flatMap((m) => m.items.map((i) => i.id)))\n for (const m of menus) {\n for (const i of m.items) if (i.parent && !allMenuItemIds.has(i.parent)) i.parent_unresolved = true\n }\n\n // ── comments: threaded, parent resolution within the same post ──\n const comments: RawComment[] = []\n for (const r of records) {\n const ids = new Set(r._comments.map((c) => c.id))\n for (const c of r._comments) comments.push({ ...c, parent_resolved: c.parent ? ids.has(c.parent) : null })\n }\n\n const rawAuthors: RawAuthor[] = authors.map((a) => ({\n id: num(a.id) || null,\n login: a.login ?? '',\n email: a.email || null,\n display_name: a.display_name || a.login || '',\n first_name: a.first_name || null,\n last_name: a.last_name || null,\n }))\n const rawTerms: RawTerm[] = terms\n .filter((t) => t.taxonomy !== 'nav_menu')\n .map((t) => ({\n id: num(t.id) || null,\n taxonomy: t.taxonomy ?? '',\n slug: t.slug ?? '',\n name: t.name ?? '',\n parent: t.parent || null,\n parent_resolved: t.parent ? termSet.has(termKey(t.taxonomy ?? '', t.parent)) : null,\n description: t.description || '',\n }))\n\n stats.serialized.keys = [...serializedKeySet].toSorted()\n stats.counts = {\n items: records.length,\n posts: posts.length,\n attachments: attachments.length,\n terms: rawTerms.length,\n authors: rawAuthors.length,\n menus: menus.length,\n comments: comments.length,\n }\n\n const raw: RawIR = {\n version: MIGRATION_CONTRACT_VERSION,\n provenance: { kind: 'wxr', tool: opts?.tool ?? '@contentrain/wp-import' },\n site: {\n url: String(site.link ?? channelText.link ?? ''),\n title: strip(channelText.title),\n description: strip(channelText.description) || undefined,\n base_site_url: channelText.base_site_url,\n base_blog_url: channelText.base_blog_url,\n language: channelText.language ?? null,\n generator: (site.generator as string) ?? null,\n export_date: (site.export_date as string) ?? null,\n wxr_version: channelText.wxr_version ?? null,\n },\n authors: rawAuthors,\n terms: rawTerms,\n posts,\n attachments,\n menus,\n comments,\n ...(languagePairs.length ? { language_pairs: languagePairs } : {}),\n }\n return { raw, stats }\n}\n\nconst MIME: Record<string, string> = {\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n png: 'image/png',\n gif: 'image/gif',\n webp: 'image/webp',\n svg: 'image/svg+xml',\n mp3: 'audio/mpeg',\n mp4: 'video/mp4',\n pdf: 'application/pdf',\n}\nfunction guessMime(u: string): string | null {\n const e = (u.split('?')[0]?.split('.').pop() ?? '').toLowerCase()\n return MIME[e] ?? null\n}\n","// Menus over REST → RawMenu[].\n//\n// Two sources, both behind `edit_theme_options` (an application password):\n// - classic menus: `/wp/v2/menus` (with the theme locations each is assigned to) and `/wp/v2/menu-items`;\n// - block-theme navigation: published `wp_navigation` posts, whose block markup is the menu. A block\n// menu's location is the template part (`header` / `footer`) that references it — or, for a\n// navigation block without a `ref`, the most recent published one, which is what WordPress shows.\n// Block menu items have no ids of their own; they get negative ids, unique within the import, so they\n// can never collide with a WordPress post id.\n\nimport type { RawMenu, RawMenuItem, RawMenuTarget } from '@contentrain/types'\nimport { strip } from './core.js'\n\nexport interface RestMenu { id: number; name?: string; slug?: string; locations?: string[] }\n\nexport interface RestMenuItem {\n id: number\n title?: { rendered?: string; raw?: string }\n status?: string\n url?: string\n description?: string\n type?: string\n object?: string\n object_id?: number\n parent?: number\n menu_order?: number\n target?: string\n classes?: string[]\n menus?: number\n}\n\nexport interface RestNavigation {\n id: number\n slug?: string\n date_gmt?: string\n status?: string\n title?: { rendered?: string; raw?: string }\n content?: { raw?: string }\n}\n\nexport interface RestTemplatePart { area?: string; content?: { raw?: string } }\n\n/** What a target is checked against: the posts and terms this import read. */\nexport interface MenuContext {\n origin: string\n /**\n * Slug of a post this import read and saw published and unprotected — the only kind a menu item may\n * point at. Anything else (a draft, a private or scheduled post, one behind a password, or one this\n * import never read: a type outside REST, past a page cap) is left out, fail-closed: a menu item's label\n * is often its target's title, and that title must not reach the store.\n */\n postSlug: (id: number) => string | undefined\n termSlug: (taxonomy: string, id: number) => string | undefined\n /** Published pages, for `core/page-list` (id, parent, order, title, link). */\n pages: Array<{ id: number; parent: number | null; menu_order: number; title: string; link: string | null; slug: string }>\n}\n\nconst targetOf = (kind: string | undefined, object: string | undefined, id: number | undefined, url: string | undefined, ctx: MenuContext): RawMenuTarget => {\n const objectId = id && id > 0 ? id : null\n if (kind === 'post_type' && object) {\n const slug = objectId ? ctx.postSlug(objectId) : undefined\n return { kind: 'post', post_type: object, id: objectId, slug: slug ?? null, resolved: slug !== undefined }\n }\n if (kind === 'taxonomy' && object) {\n const slug = objectId ? ctx.termSlug(object, objectId) : undefined\n return { kind: 'term', taxonomy: object, id: objectId, slug: slug ?? null, resolved: slug !== undefined }\n }\n if (kind === 'post_type_archive' && object) return { kind: 'archive', post_type: object, resolved: true }\n if (url) return { kind: 'url', url, resolved: true }\n return { kind: 'unknown', resolved: false }\n}\n\n/**\n * Items that are left out: a draft item, or one whose post target is not proven visible. Their children move up\n * to the nearest kept ancestor, as WordPress's walker shows them.\n */\nfunction hiddenItems(items: RestMenuItem[], drop: (i: RestMenuItem) => boolean): { gone: Set<number>; lift: (parent: number | null) => number | null } {\n const parentOf = new Map(items.filter(drop).map((i) => [i.id, i.parent || null]))\n const lift = (parent: number | null): number | null => {\n const seen = new Set<number>()\n let p = parent\n while (p !== null && parentOf.has(p) && !seen.has(p)) { seen.add(p); p = parentOf.get(p) ?? null }\n return p\n }\n return { gone: new Set(parentOf.keys()), lift }\n}\n\n/** Classic menus and their items; each menu names the theme locations it is assigned to. `dropped` counts left-out items. */\nexport function classicMenus(menus: RestMenu[], items: RestMenuItem[], ctx: MenuContext, dropped = { count: 0 }): RawMenu[] {\n const out: RawMenu[] = []\n for (const m of [...menus].toSorted((a, b) => a.id - b.id)) {\n const all = items.filter((i) => i.menus === m.id).toSorted((a, b) => (a.menu_order ?? 0) - (b.menu_order ?? 0) || a.id - b.id)\n const { gone, lift } = hiddenItems(all, (i) => (i.status ?? 'publish') !== 'publish' || (i.type === 'post_type' && !(i.object_id && ctx.postSlug(i.object_id))))\n dropped.count += gone.size\n const own = all.filter((i) => !gone.has(i.id))\n const ids = new Set(own.map((i) => i.id))\n const menu: RawMenu = {\n id: m.id,\n slug: m.slug ?? '',\n name: strip(m.name ?? m.slug ?? ''),\n items: own.map((i) => {\n const item: RawMenuItem = {\n id: i.id,\n title: i.title?.raw || i.title?.rendered || '',\n order: i.menu_order ?? 0,\n parent: lift(i.parent || null),\n url: i.url || null,\n target: targetOf(i.type, i.object, i.object_id, i.url, ctx),\n target_attr: i.target || null,\n classes: (i.classes ?? []).filter(Boolean),\n description: i.description ?? '',\n status: i.status ?? 'publish',\n }\n if (item.parent && !ids.has(item.parent)) item.parent_unresolved = true\n return item\n }),\n }\n const locations = (m.locations ?? []).filter(Boolean).toSorted()\n if (locations.length) menu.locations = locations\n out.push(menu)\n }\n return out\n}\n\n// ── Block navigation ─────────────────────────────────────────────────────────\n\ninterface Block { name: string; attrs: Record<string, unknown>; children: Block[] }\n\n/** Serialized block comments (`<!-- wp:name {attrs} /-->`, `<!-- /wp:name -->`). Same grammar as the facts builder parser. */\nconst BLOCK_TOKEN = /<!--\\s+(\\/)?wp:([a-z][a-z0-9_-]*\\/)?([a-z][a-z0-9_-]*)\\s+({(?:(?!}\\s+\\/?-->)[\\s\\S])*?}\\s+)?(\\/)?-->/g\n\nexport function parseBlocks(content: string): Block[] {\n const root: Block = { name: 'root', attrs: {}, children: [] }\n const stack: Block[] = [root]\n const token = new RegExp(BLOCK_TOKEN.source, 'g')\n let m: RegExpExecArray | null\n while ((m = token.exec(content))) {\n const [, closer, ns, local, json, selfClose] = m\n if (closer) {\n if (stack.length > 1) stack.pop()\n continue\n }\n let attrs: Record<string, unknown> = {}\n if (json) {\n try { attrs = JSON.parse(json) as Record<string, unknown> } catch { attrs = {} }\n }\n const block: Block = { name: `${ns ? ns.slice(0, -1) : 'core'}/${local}`, attrs, children: [] }\n stack[stack.length - 1]!.children.push(block)\n if (!selfClose) stack.push(block)\n }\n return root.children\n}\n\nconst str = (v: unknown): string | undefined => (typeof v === 'string' && v ? v : undefined)\nconst absolute = (url: string | undefined, origin: string): string | undefined => {\n if (!url) return undefined\n try { return new URL(url, `${origin}/`).href } catch { return url }\n}\n/** The block editor's link kinds → the classic menu item types. */\nconst KIND: Record<string, string> = { 'post-type': 'post_type', taxonomy: 'taxonomy', custom: 'custom' }\n\n/**\n * Menu items of one `wp_navigation` body. Links and submenus become items; a page list becomes the\n * published pages it lists; a home link points at `/`. Other blocks (search, social icons, spacers) are not links.\n */\nexport function navigationItems(content: string, ctx: MenuContext, nextId: () => number, dropped = { count: 0 }): RawMenuItem[] {\n const items: RawMenuItem[] = []\n const push = (b: { title: string; url?: string; kind?: string; object?: string; id?: number; newTab?: boolean; className?: string; description?: string }, parent: number | null): number => {\n const id = nextId()\n const url = absolute(b.url, ctx.origin)\n items.push({\n id,\n title: b.title,\n order: items.length + 1,\n parent,\n url: url ?? null,\n target: targetOf(b.kind, b.object, b.id, url, ctx),\n target_attr: b.newTab ? '_blank' : null,\n classes: (b.className ?? '').split(/\\s+/).filter(Boolean),\n description: b.description ?? '',\n status: 'publish',\n })\n return id\n }\n const pageList = (parentPage: number, parent: number | null) => {\n const kids = ctx.pages.filter((p) => (p.parent ?? 0) === parentPage).toSorted((a, b) => a.menu_order - b.menu_order || a.title.localeCompare(b.title))\n for (const p of kids) {\n const id = push({ title: p.title, url: p.link ?? undefined, kind: 'post_type', object: 'page', id: p.id }, parent)\n pageList(p.id, id)\n }\n }\n const walk = (blocks: Block[], parent: number | null) => {\n for (const b of blocks) {\n const a = b.attrs\n if (b.name === 'core/navigation-link' || b.name === 'core/navigation-submenu') {\n const kind = KIND[str(a.kind) ?? ''] ?? (str(a.type) === 'category' || str(a.type) === 'tag' || str(a.type) === 'post_tag' ? 'taxonomy' : a.id ? 'post_type' : 'custom')\n const object = kind === 'taxonomy' && str(a.type) === 'tag' ? 'post_tag' : str(a.type)\n // A link to a post not proven visible is left out (fail-closed); its children show in its place.\n if (kind === 'post_type' && typeof a.id === 'number' && !ctx.postSlug(a.id)) {\n dropped.count++\n walk(b.children, parent)\n continue\n }\n const id = push({ title: strip(a.label), url: str(a.url), kind, object, id: typeof a.id === 'number' ? a.id : undefined, newTab: a.opensInNewTab === true, className: str(a.className), description: str(a.description) }, parent)\n walk(b.children, id)\n } else if (b.name === 'core/home-link') {\n push({ title: strip(a.label) || 'Home', url: '/', className: str(a.className) }, parent)\n } else if (b.name === 'core/page-list') {\n pageList(typeof a.parentPageID === 'number' ? a.parentPageID : 0, parent)\n } else {\n walk(b.children, parent)\n }\n }\n }\n walk(parseBlocks(content), null)\n return items\n}\n\n/**\n * Where each navigation is shown: the template parts (`header`, `footer`) whose navigation block\n * refers to it. An empty navigation block without a `ref` shows the fallback — the most recent published one;\n * one with links of its own shows those (an inline menu, not a `wp_navigation` post).\n */\nexport function navigationLocations(parts: RestTemplatePart[], navigations: RestNavigation[]): Map<number, string[]> {\n const out = new Map<number, Set<string>>()\n const fallback = [...navigations].toSorted((a, b) => (b.date_gmt ?? '').localeCompare(a.date_gmt ?? '') || b.id - a.id)[0]?.id\n const find = (blocks: Block[], area: string) => {\n for (const b of blocks) {\n if (b.name === 'core/navigation') {\n // No ref and links of its own: an inline navigation, not any wp_navigation post. No ref, empty: the fallback.\n const ref = typeof b.attrs.ref === 'number' ? b.attrs.ref : b.children.length ? undefined : fallback\n if (ref !== undefined) (out.get(ref) ?? out.set(ref, new Set()).get(ref)!).add(area)\n continue\n }\n find(b.children, area)\n }\n }\n for (const p of parts) {\n const area = p.area && p.area !== 'uncategorized' ? p.area : undefined\n if (area && p.content?.raw) find(parseBlocks(p.content.raw), area)\n }\n return new Map([...out].map(([id, set]) => [id, [...set].toSorted()]))\n}\n\n/** Published `wp_navigation` posts → RawMenu[], slugs kept unique against the classic menus already read. */\nexport function blockMenus(navigations: RestNavigation[], parts: RestTemplatePart[], ctx: MenuContext, taken: Set<string>, dropped = { count: 0 }): RawMenu[] {\n const published = navigations.filter((n) => (n.status ?? 'publish') === 'publish').toSorted((a, b) => a.id - b.id)\n const locations = navigationLocations(parts, published)\n let next = 0\n const out: RawMenu[] = []\n for (const n of published) {\n let slug = n.slug || `navigation-${n.id}`\n while (taken.has(slug)) slug = `${slug}-nav`\n taken.add(slug)\n const menu: RawMenu = {\n id: n.id,\n slug,\n name: strip(n.title?.raw || n.title?.rendered || '') || slug,\n items: navigationItems(n.content?.raw ?? '', ctx, () => -++next, dropped),\n }\n const where = locations.get(n.id)\n if (where?.length) menu.locations = where\n out.push(menu)\n }\n return out\n}\n","// Public/authenticated WordPress REST → RawIR.\n//\n// The lowest rungs of the source-access ladder. What REST cannot see (rest:false\n// CPTs, unregistered meta; menus without an application password) is absent from the result —\n// absence at a low rung is information, not an error, and the manifest layer\n// decides what to recommend about it.\n\nimport type { RawIR, RawAttachment, RawComment, RawLanguagePair, RawMenu, RawPost, RawTerm, RawTermRef, SourceAccessKind } from '@contentrain/types'\nimport { MIGRATION_CONTRACT_VERSION } from '@contentrain/types'\nimport { strip, SKIP_TYPES, PROTECTED } from './core.js'\nimport { blockMenus, classicMenus, type MenuContext, type RestMenu, type RestMenuItem, type RestNavigation, type RestTemplatePart } from './rest-menus.js'\n\nconst iso = (gmt: string | undefined): string | null => (gmt ? `${gmt}Z` : null)\nconst approvedOf = (status: string | undefined): RawComment['approved'] =>\n status === 'approved' ? '1' : status === 'hold' ? '0' : status === 'spam' ? 'spam' : status === 'trash' ? 'trash' : (status ?? '1')\n\nexport interface RestImportOptions {\n origin: string\n /** Injectable for tests and for hosts that need custom dispatch. */\n fetchImpl?: typeof fetch\n /**\n * WordPress Application Password credentials — lifts the rung to rest_auth.\n * With them, post types are listed with every non-trash status\n * (`AUTH_POST_STATUSES`) in the edit context, and comments with held ones\n * too; anonymous REST only ever returns published posts and approved\n * comments. A credential the site refuses for that falls back to the\n * public listing, with a warning.\n */\n auth?: { user: string; appPassword: string }\n perPage?: number\n /**\n * Requests in flight at once, across every collection. Default 4. A site\n * with 74 pages of posts, 40 of media and 37 of comments used to receive\n * ~150 simultaneous requests — enough to trip a host's rate limit or WAF.\n */\n concurrency?: number\n /**\n * Pages fetched per collection at most. Unset = all. A truncated collection\n * is named in `warnings` (with what was skipped), never silently shortened.\n */\n maxPages?: number\n tool?: string\n}\n\nexport interface RestImportResult {\n raw: RawIR\n warnings: string[]\n /**\n * Whether the credential was honoured, for callers that must act on it\n * without reading `warnings`. `none`: no `auth` given. `accepted`: every\n * listing it unlocks was read with it. `rejected`: at least one was not —\n * `fell_back` names each (`posts`, `pages`, a CPT's rest base, `comments`,\n * `comments:hold`), and those came from the public listing instead, or not\n * at all for `comments:hold`, which has none.\n */\n credential: { status: 'none' | 'accepted' | 'rejected'; fell_back: string[] }\n /**\n * What this rung could not read, as codes a caller can act on (the text is in `warnings`).\n * `menus_require_auth`: menus and block navigation are only readable with an application password\n * of a user who may edit theme options — none was given, the site rejected it, or it lacks that right.\n */\n gaps: string[]\n}\n\ninterface RestPost {\n id: number\n slug: string\n status?: string\n type?: string\n link?: string\n title?: { rendered?: string }\n content?: { rendered?: string }\n excerpt?: { rendered?: string }\n date_gmt?: string\n modified_gmt?: string\n author?: number\n parent?: number\n menu_order?: number\n sticky?: boolean\n /** Edit context only. */\n password?: string\n comment_status?: string\n ping_status?: string\n featured_media?: number\n categories?: number[]\n tags?: number[]\n meta?: Record<string, unknown>\n /** Polylang: language slug of the post and its translation group (`{ en: 12, tr: 34 }`, self included). */\n lang?: string\n translations?: Record<string, number>\n /** WPML: locale of the post and its other translations. */\n wpml_current_locale?: string\n wpml_translations?: Array<{ locale?: string; id?: number }>\n}\n\n/** What a credential lists beyond `publish`: drafts, scheduled, in-review and private posts. Trash stays out. */\nexport const AUTH_POST_STATUSES = ['publish', 'future', 'draft', 'pending', 'private'] as const\n/** Comment listings for a credential: WP's `status` takes one value, so approved and held are two requests. */\nconst AUTH_COMMENT_STATUSES = ['approve', 'hold'] as const\nconst DENIED = new Set([400, 401, 403])\n/** A comment listing's name in `credential.fell_back`: `comments` (approved) or `comments:hold`. */\nconst commentKey = (status: string): string => (status === 'approve' ? 'comments' : `comments:${status}`)\n\n/** What a visitor can open: published, not behind a post password. */\nconst visible = (p: RawPost): boolean => p.status === 'publish' && !p.password\n\nconst positiveInteger = (name: string, value: number): number => {\n if (!Number.isSafeInteger(value) || value < 1) throw new RangeError(`${name} must be a positive safe integer`)\n return value\n}\n\nexport async function fetchRestRawIR(options: RestImportOptions): Promise<RestImportResult> {\n const origin = options.origin.replace(/\\/$/, '')\n const doFetch = options.fetchImpl ?? fetch\n const perPage = positiveInteger('perPage', options.perPage ?? 100)\n if (perPage > 100) throw new RangeError('perPage must be at most 100')\n const concurrency = positiveInteger('concurrency', options.concurrency ?? 4)\n const maxPages = options.maxPages !== undefined ? positiveInteger('maxPages', options.maxPages) : undefined\n const warnings: string[] = []\n // One pool for the whole import: page fetches of every collection queue here,\n // so the cap holds even though collections are requested \"in parallel\".\n const queue: Array<() => Promise<void>> = []\n let running = 0\n const schedule = <T>(task: () => Promise<T>): Promise<T> =>\n new Promise<T>((resolve, reject) => {\n queue.push(() => task().then(resolve, reject))\n pump()\n })\n const pump = (): void => {\n while (running < concurrency && queue.length) {\n const task = queue.shift()!\n running++\n void task().finally(() => {\n running--\n pump()\n })\n }\n }\n const anonymous: Record<string, string> = { accept: 'application/json' }\n let headers = anonymous\n if (options.auth) {\n headers = { ...anonymous, authorization: `Basic ${Buffer.from(`${options.auth.user}:${options.auth.appPassword}`).toString('base64')}` }\n }\n const fellBack = new Set<string>()\n // WordPress answers a wrong Application Password with 401 on every route,\n // public ones too, so a rejected credential is found once and dropped:\n // sent on, it would also empty the public listings the import falls back to.\n let rejected = false\n if (options.auth) {\n const me = await doFetch(`${origin}/wp-json/wp/v2/users/me`, { headers })\n await me.body?.cancel()\n if (me.status === 401 || me.status === 403) {\n rejected = true\n headers = anonymous\n warnings.push(`credential: HTTP ${me.status} on users/me — the site rejected it; imported the public listings only`)\n }\n }\n\n /**\n * Every page of `path`. With `fallback`, a first page the site refuses\n * (400/401/403 — the credential may not list those statuses or the edit\n * context) is retried as `fallback` instead of dropping the collection;\n * an empty `fallback` means there is nothing public to retry, so it is\n * skipped with that warning. The retry is anonymous, and `key` goes into\n * `credential.fell_back`.\n */\n const getAll = async <T>(path: string, fallback?: string, key?: string, send = headers): Promise<T[]> => {\n const label = path.split('?')[0]!\n const url = (page: number) => `${origin}/wp-json/wp/v2/${path}${path.includes('?') ? '&' : '?'}per_page=${perPage}&page=${page}`\n // Hold the slot until the body is consumed, not merely until headers arrive.\n const pageData = (page: number) => schedule(async () => {\n const response = await doFetch(url(page), { headers: send })\n if (!response.ok) {\n await response.body?.cancel()\n if (page === 1 && fallback !== undefined && DENIED.has(response.status)) return { items: [] as T[], pages: 1, denied: response.status }\n warnings.push(`${label}: page ${page} HTTP ${response.status} — skipped`)\n return { items: [] as T[], pages: 1 }\n }\n const pages = Number(response.headers.get('x-wp-totalpages') ?? '1')\n if (!Number.isSafeInteger(pages) || pages < 0) throw new Error(`${path}: invalid x-wp-totalpages`)\n const items = await response.json() as T[]\n if (!Array.isArray(items)) throw new Error(`${path}: page ${page} is not a collection`)\n return { items, pages: Math.max(1, pages), denied: undefined as number | undefined }\n })\n const first = await pageData(1)\n if (first.denied !== undefined) {\n warnings.push(`${label}: HTTP ${first.denied} for ${path.split('?')[1]} with the credential — ${fallback ? 'fell back to the public listing' : 'skipped (no public listing)'}`)\n fellBack.add(key ?? label)\n return fallback ? getAll<T>(fallback, undefined, undefined, anonymous) : []\n }\n const totalPages = first.pages\n const firstPage = first.items\n const wanted = maxPages !== undefined ? Math.min(totalPages, maxPages) : totalPages\n if (wanted < totalPages) {\n warnings.push(`${label}: ${totalPages} pages, fetched ${wanted} (maxPages) — ${totalPages - wanted} pages skipped`)\n }\n if (wanted <= 1) return firstPage\n const rest = await Promise.all(\n Array.from({ length: wanted - 1 }, (_v, i) =>\n pageData(i + 2).then((r) => r.items),\n ),\n )\n return firstPage.concat(...rest)\n }\n\n // The site's own name and tagline (`/wp-json/` index, public): without them the store's site singleton says \"Site\".\n // Advisory: an index that does not answer leaves them out, as before.\n const about = await schedule(async () => {\n try {\n const index = await doFetch(`${origin}/wp-json/`, { headers })\n if (!index.ok) { await index.body?.cancel(); return null }\n return (await index.json()) as { name?: unknown; description?: unknown; url?: unknown; home?: unknown } | null\n } catch { return null }\n })\n\n interface RestType { slug: string; rest_base?: string }\n const typesResp = await doFetch(`${origin}/wp-json/wp/v2/types`, { headers })\n const types: Record<string, RestType> = typesResp.ok ? ((await typesResp.json()) as Record<string, RestType>) : {}\n if (!typesResp.ok) warnings.push(`types: HTTP ${typesResp.status} — importing posts and pages only`)\n const postTypes = Object.values(types).filter(\n (t) => t.rest_base && !SKIP_TYPES.test(t.slug) && t.slug !== 'attachment',\n )\n const bases = postTypes.length ? postTypes.map((t) => ({ slug: t.slug, base: t.rest_base! })) : [\n { slug: 'post', base: 'posts' },\n { slug: 'page', base: 'pages' },\n ]\n\n interface RestTerm { id: number; slug: string; name: string; taxonomy?: string; parent?: number; description?: string }\n interface RestUser { id: number; slug: string; name: string }\n interface RestMedia {\n id: number\n slug: string\n title?: { rendered?: string }\n source_url?: string\n alt_text?: string\n caption?: { rendered?: string }\n mime_type?: string\n media_details?: { width?: number; height?: number; file?: string }\n post?: number | null\n date_gmt?: string\n }\n interface RestComment {\n id: number\n post: number\n parent?: number\n author?: number\n author_name?: string\n author_url?: string\n date_gmt?: string\n content?: { rendered?: string }\n status?: string\n type?: string\n }\n\n // Anonymous: WP's defaults (published posts, approved comments). With a\n // credential: every non-trash status, and held comments as a second listing.\n // A credential rejected outright unlocks nothing: every listing it would have read fell back.\n if (rejected) {\n for (const b of bases) fellBack.add(b.base)\n for (const status of AUTH_COMMENT_STATUSES) fellBack.add(commentKey(status))\n }\n const authed = options.auth !== undefined && !rejected\n const postListing = (base: string): Promise<RestPost[]> =>\n authed ? getAll<RestPost>(`${base}?status=${AUTH_POST_STATUSES.join(',')}&context=edit`, base, base) : getAll<RestPost>(base)\n const commentListing = async (): Promise<RestComment[]> => {\n if (!authed) return getAll<RestComment>('comments')\n const lists = await Promise.all(AUTH_COMMENT_STATUSES.map((status) =>\n // Approved comments are public, so a refused credential still gets them; held ones have no public listing.\n getAll<RestComment>(`comments?status=${status}&context=edit`, status === 'approve' ? 'comments' : '', commentKey(status))))\n const byId = new Map<number, RestComment>()\n for (const c of lists.flat()) if (!byId.has(c.id)) byId.set(c.id, c)\n return [...byId.values()]\n }\n const [categories, tags, users, media, restComments, ...postLists] = await Promise.all([\n getAll<RestTerm>('categories'),\n getAll<RestTerm>('tags'),\n getAll<RestUser>('users'),\n getAll<RestMedia>('media'),\n commentListing(),\n ...bases.map((b) => postListing(b.base)),\n ])\n\n const termsById = new Map<number, RawTerm>()\n for (const [tax, list] of [\n ['category', categories],\n ['post_tag', tags],\n ] as const) {\n for (const t of list) {\n termsById.set(t.id, {\n id: t.id,\n taxonomy: tax,\n slug: t.slug,\n name: strip(t.name),\n parent: t.parent ? (list.find((x) => x.id === t.parent)?.slug ?? null) : null,\n parent_resolved: t.parent ? list.some((x) => x.id === t.parent) : null,\n description: t.description ?? '',\n })\n }\n }\n const userById = new Map(users.map((u) => [u.id, u]))\n\n const posts: RawPost[] = []\n // Translation groups, one pair per group. Polylang's `translations` already\n // includes the post itself; WPML lists the OTHER translations, so add self.\n const languagePairs: RawLanguagePair[] = []\n const seenGroups = new Set<string>()\n const recordGroup = (self: RestPost, lang: string | null) => {\n const translations: Record<string, number> = {}\n if (self.translations && typeof self.translations === 'object') {\n for (const [code, id] of Object.entries(self.translations)) if (typeof id === 'number') translations[code] = id\n } else if (Array.isArray(self.wpml_translations)) {\n for (const t of self.wpml_translations) if (t.locale && typeof t.id === 'number') translations[t.locale] = t.id\n if (lang) translations[lang] = self.id\n }\n const ids = Object.values(translations)\n if (ids.length < 2) return\n const key = [...ids].toSorted((a, b) => a - b).join(',')\n if (seenGroups.has(key)) return\n seenGroups.add(key)\n languagePairs.push({ post: self.id, translations })\n }\n for (const [i, base] of bases.entries()) {\n for (const p of postLists[i] ?? []) {\n const termRefs: RawTermRef[] = [...(p.categories ?? []), ...(p.tags ?? [])].map((id) => {\n const t = termsById.get(id)\n return t\n ? { taxonomy: t.taxonomy, slug: t.slug, name: t.name, resolved: true }\n : { taxonomy: 'category', slug: String(id), name: String(id), resolved: false }\n })\n const author = p.author ? (userById.get(p.author)?.slug ?? null) : null\n const meta: Record<string, unknown> = { ...(p.meta && typeof p.meta === 'object' ? p.meta : {}) }\n if (p.featured_media) meta._thumbnail_id = String(p.featured_media)\n const lang = (typeof p.lang === 'string' && p.lang) || (typeof p.wpml_current_locale === 'string' && p.wpml_current_locale) || null\n recordGroup(p, lang)\n posts.push({\n ...(lang ? { lang } : {}),\n id: p.id,\n type: base.slug,\n status: p.status ?? 'publish',\n slug: p.slug,\n title: p.title?.rendered ?? '',\n link: p.link ?? null,\n guid: null,\n author,\n date: iso(p.date_gmt),\n modified: iso(p.modified_gmt),\n content: p.content?.rendered ?? '',\n excerpt: p.excerpt?.rendered ?? '',\n parent: p.parent || null,\n menu_order: p.menu_order ?? 0,\n sticky: p.sticky ?? false,\n password: p.password ? PROTECTED : null,\n comment_status: p.comment_status ?? null,\n ping_status: p.ping_status ?? null,\n terms: termRefs,\n meta,\n })\n }\n }\n\n const attachments: RawAttachment[] = media.map((m) => ({\n id: m.id,\n title: strip(m.title?.rendered) || m.slug,\n slug: m.slug,\n url: m.source_url ?? null,\n alt: m.alt_text ?? '',\n caption: strip(m.caption?.rendered),\n file: m.media_details?.file ?? null,\n image_meta: m.media_details ?? null,\n mime: m.mime_type ?? null,\n parent: m.post ?? null,\n parent_resolved: m.post ? posts.some((p) => p.id === m.post) : null,\n date: iso(m.date_gmt),\n }))\n\n // ── menus: classic menus + published block navigation; both need `edit_theme_options` ──\n const gaps: string[] = []\n let menus: RawMenu[] = []\n if (!authed) {\n // Not a warning: without a working credential this is the rung's known limit, named for the caller in `gaps`.\n gaps.push('menus_require_auth')\n } else {\n const listing = async <T>(path: string): Promise<{ items: T[]; status: number }> => {\n const url = (page: number) => `${origin}/wp-json/wp/v2/${path}${path.includes('?') ? '&' : '?'}per_page=${perPage}&page=${page}`\n const first = await schedule(async () => {\n const r = await doFetch(url(1), { headers })\n if (!r.ok) { await r.body?.cancel(); return { items: [] as T[], status: r.status, pages: 1 } }\n const items = await r.json() as T[]\n return { items: Array.isArray(items) ? items : [], status: r.status, pages: Math.max(1, Number(r.headers.get('x-wp-totalpages') ?? '1') || 1) }\n })\n const wanted = maxPages !== undefined ? Math.min(first.pages, maxPages) : first.pages\n const rest = await Promise.all(Array.from({ length: wanted - 1 }, (_v, i) => schedule(async () => {\n const r = await doFetch(url(i + 2), { headers })\n if (!r.ok) { await r.body?.cancel(); warnings.push(`${path.split('?')[0]}: page ${i + 2} HTTP ${r.status} — skipped`); return [] as T[] }\n const items = await r.json() as T[]\n return Array.isArray(items) ? items : []\n })))\n return { items: first.items.concat(...rest), status: first.status }\n }\n const [classic, items, navs, parts] = await Promise.all([\n listing<RestMenu>('menus?context=edit'),\n listing<RestMenuItem>('menu-items?context=edit'),\n listing<RestNavigation>('navigation?context=edit&status=publish'),\n listing<RestTemplatePart>('template-parts?context=edit'),\n ])\n const denied = [classic, items, navs].filter((l) => DENIED.has(l.status))\n if (denied.length) {\n gaps.push('menus_require_auth')\n warnings.push(`menus: HTTP ${denied[0]!.status} with the credential — the user may not edit theme options; menus not read`)\n }\n for (const [name, l] of [['menus', classic], ['menu-items', items], ['navigation', navs]] as const) {\n if (!l.status || (l.status >= 400 && !DENIED.has(l.status) && l.status !== 404)) warnings.push(`${name}: HTTP ${l.status} — skipped`)\n }\n const slugOf = new Map(posts.filter(visible).map((p) => [p.id, p.slug]))\n const ctx: MenuContext = {\n origin,\n postSlug: (id) => slugOf.get(id),\n termSlug: (taxonomy, id) => { const t = termsById.get(id); return t && t.taxonomy === taxonomy ? t.slug : undefined },\n pages: posts.filter((p) => p.type === 'page' && p.status === 'publish' && !p.password).map((p) => ({ id: p.id, parent: p.parent ?? null, menu_order: p.menu_order ?? 0, title: strip(p.title), link: p.link ?? null, slug: p.slug })),\n }\n const dropped = { count: 0 }\n menus = classicMenus(DENIED.has(classic.status) ? [] : classic.items, DENIED.has(items.status) ? [] : items.items, ctx, dropped)\n menus.push(...blockMenus(DENIED.has(navs.status) ? [] : navs.items, parts.status < 400 ? parts.items : [], ctx, new Set(menus.map((m) => m.slug)), dropped))\n // A count only: the titles of what was left out are exactly what must not travel.\n if (dropped.count) warnings.push(`menus: ${dropped.count} item(s) are drafts or point at content not proven public (unpublished, password-protected, or not read by this import) — left out`)\n }\n\n const postIds = new Set(posts.map((p) => p.id))\n const commentIds = new Set(restComments.map((c) => c.id))\n const comments: RawComment[] = restComments.map((c) => ({\n id: c.id,\n post: c.post,\n post_type: posts.find((p) => p.id === c.post)?.type,\n parent: c.parent || null,\n parent_resolved: c.parent ? commentIds.has(c.parent) : null,\n author: strip(c.author_name) || 'anonymous',\n email: null,\n url: c.author_url || null,\n date: iso(c.date_gmt),\n date_gmt: c.date_gmt ?? null,\n content: c.content?.rendered ?? '',\n approved: approvedOf(c.status),\n type: c.type ?? 'comment',\n user_id: c.author || null,\n }))\n for (const c of comments) if (!postIds.has(c.post)) warnings.push(`comment ${c.id}: post ${c.post} not in fetched set`)\n\n // The rung is what was actually read: a credential rejected outright read nothing.\n const kind: SourceAccessKind = authed ? 'rest_auth' : 'rest_public'\n const raw: RawIR = {\n version: MIGRATION_CONTRACT_VERSION,\n provenance: { kind, tool: options.tool ?? '@contentrain/wp-import' },\n site: {\n url: origin,\n ...(typeof about?.name === 'string' && strip(about.name) ? { title: strip(about.name) } : {}),\n ...(typeof about?.description === 'string' && strip(about.description) ? { description: strip(about.description) } : {}),\n // Where WordPress is installed and where the site is served, as WXR names them (they differ for a subdirectory install).\n ...(typeof about?.url === 'string' && about.url ? { base_site_url: about.url } : {}),\n ...(typeof about?.home === 'string' && about.home ? { base_blog_url: about.home } : {}),\n },\n authors: users.map((u) => ({ id: u.id, login: u.slug, display_name: strip(u.name) || u.slug, email: null })),\n terms: [...termsById.values()],\n posts,\n attachments,\n comments,\n ...(menus.length ? { menus } : {}),\n ...(languagePairs.length ? { language_pairs: languagePairs } : {}),\n }\n const credential: RestImportResult['credential'] = {\n status: !options.auth ? 'none' : fellBack.size ? 'rejected' : 'accepted',\n fell_back: [...fellBack].toSorted(),\n }\n return { raw, warnings, credential, gaps }\n}\n","// RawIR → .contentrain content store, as a pure file map.\n//\n// Ported from the measured import chain (the \"deviations from r4i\" it carried\n// are already folded in: PATH_PATTERNS-conformant layout, ContentrainConfig\n// shape, meta files per locale). Two properties are load-bearing:\n//\n// 1. Identity formulas — hexId('posts:' + slug), hexId('category:' + slug) —\n// are shared with the REST path, so the same site imported twice (or via a\n// later delta) lands on the same entry ids.\n// 2. The EntrySourceMap (wp post id → entry address) is produced HERE and only\n// here: this is the one place that knows both sides of the mapping, and the\n// comments intake downstream cannot exist without it.\n\nimport type { EntrySourceMap, FieldDef, ModelDefinition, RawIR, RawPost } from '@contentrain/types'\nimport {\n byValue,\n canon,\n coreFields,\n decodeSlug,\n hexId,\n PLUGIN_META,\n SKIP_TYPES,\n slugify,\n strip,\n taxModelId,\n} from './core.js'\n\nexport interface ImportReport {\n slug_rewritten: number\n slug_fallback: number\n title_fallback: number\n meta_fields: Record<string, string>\n acf_fields: Record<string, string>\n skipped_types: string[]\n dropped_relations: number\n models: Record<string, { kind: string; domain: string; fields: number; entries: number }>\n /** Default first, then every other language seen on a post. One entry on a monolingual site. */\n locales: string[]\n /** Translation groups that were folded into one entry id across locales. */\n translation_groups: number\n /**\n * Password-protected posts imported as `draft`, whatever their WordPress\n * status. Their body is the protected text, and nothing downstream (query\n * SDK, emitter) enforces `visibility: password`, so publishing one would\n * put that text on a public site. Publish only after deciding what to show.\n */\n password_protected_drafts: number\n}\n\nexport interface ContentrainResult {\n files: Record<string, string>\n entry_source_map: EntrySourceMap\n report: ImportReport\n}\n\ntype Entry = Record<string, unknown>\ntype Meta = { status: string; source: string; updated_by: string; publish_at?: string }\n\nconst pick = (o: Record<string, unknown>, keys: Set<string>): Entry =>\n Object.fromEntries(Object.entries(o).filter(([k, v]) => keys.has(k) && v !== undefined && v !== null && v !== ''))\nconst typeModelId = (t: string): string => (t === 'post' ? 'posts' : t === 'page' ? 'pages' : t.replace(/_/g, '-'))\nconst domainOf = (t: string): string => (t === 'post' ? 'blog' : t === 'page' ? 'site' : 'custom')\n\n/** `en_US` / `tr-TR` / `en` → `en`: the store's locale is the primary subtag. */\nconst normLocale = (code: string | null | undefined): string => (code ?? '').split(/[-_]/)[0]?.toLowerCase() ?? ''\n\n/** Multilingual-plugin taxonomies that carry language bookkeeping, not content. */\nconst LANGUAGE_TAXONOMIES = new Set(['language', 'post_translations', 'term_language', 'term_translations'])\n\n/**\n * A relation field over `targets`: its declared model, and how a reference into\n * it is stored.\n *\n * With several targets the id alone does not say which model's entry it is, so\n * the reference is the pair `{ model, ref }`. With one there is nothing to\n * choose between: the field is single-target and stores the entry id. Writing\n * the pair there fails the same validator that requires it when there are\n * several — so the choice is made in one place, from the same list the model\n * declares.\n */\nfunction relationOver(targets: string[]): {\n model: string | string[]\n ref: (entry: { model: string; ref: string }) => string | { model: string; ref: string }\n} {\n const single = targets.length === 1\n return { model: single ? targets[0]! : targets, ref: (entry) => (single ? entry.ref : entry) }\n}\n\nexport function rawToContentrain(raw: RawIR, opts?: { updatedBy?: string }): ContentrainResult {\n const updatedBy = opts?.updatedBy ?? '@contentrain/wp-import'\n const locale = normLocale(raw.site.language) || 'en'\n const models: Record<string, ModelDefinition> = {}\n const contents: Record<string, Record<string, Entry>> = {}\n const metas: Record<string, Record<string, Meta>> = {}\n // Per-locale buckets for i18n models (post types on a multilingual site).\n const localeContents: Record<string, Record<string, Record<string, Entry>>> = {}\n const localeMetas: Record<string, Record<string, Record<string, Meta>>> = {}\n\n // ── languages ──\n // A post's language comes from the plugin (`lang`) or, in WXR, from the\n // `language` taxonomy term Polylang attaches. Posts without one belong to the\n // site's default locale. More than one locale seen → post-type models are\n // i18n and content is written per locale.\n const postLocale = (p: RawPost): string =>\n normLocale(p.lang ?? p.terms.find((t) => t.taxonomy === 'language')?.slug) || locale\n const locales = [locale, ...[...new Set(raw.posts.filter((p) => !SKIP_TYPES.test(p.type)).map(postLocale))].filter((l) => l !== locale).toSorted()]\n const multilingual = locales.length > 1\n // Translation groups → one canonical post per group. Its entry id is shared\n // by every translation, which is how an i18n collection addresses one entry\n // in several locales. The canonical member is the default-locale post when\n // there is one, else the lowest id — deterministic either way.\n const postById = new Map(raw.posts.map((p) => [p.id, p]))\n const canonicalOf = new Map<number, number>()\n let translationGroups = 0\n for (const pair of raw.language_pairs ?? []) {\n const members = [...new Set(Object.values(pair.translations))].filter((id) => postById.has(id) && !SKIP_TYPES.test(postById.get(id)!.type))\n if (members.length < 2) continue\n const memberLocales = members.map((id) => postLocale(postById.get(id)!))\n if (new Set(memberLocales).size !== members.length)\n throw new Error(`Translation group ${pair.post} has multiple posts in the same normalized locale; refusing to overwrite a translation`)\n const canonical = members.find((id) => postLocale(postById.get(id)!) === locale) ?? Math.min(...members)\n for (const id of members) canonicalOf.set(id, canonical)\n translationGroups++\n }\n let siteEntry: Entry = {}\n let siteMeta: Meta | null = null\n const report: ImportReport = {\n slug_rewritten: 0,\n slug_fallback: 0,\n title_fallback: 0,\n meta_fields: {},\n acf_fields: {},\n skipped_types: [],\n dropped_relations: 0,\n models: {},\n locales,\n translation_groups: translationGroups,\n password_protected_drafts: 0,\n }\n const importMeta = (status: string, extra: Partial<Meta> = {}): Meta => ({\n status,\n source: 'import',\n updated_by: updatedBy,\n ...extra,\n })\n const mapStatus = (p: RawPost): Meta => {\n // Checked first: a protected post must never come in published or scheduled.\n if (p.password && p.status !== 'trash') {\n report.password_protected_drafts++\n return importMeta('draft')\n }\n if (p.status === 'future' && (!p.date || !Number.isFinite(Date.parse(p.date))))\n throw new Error(`Scheduled WordPress post ${p.id} has no valid publication date`)\n return p.status === 'publish' || p.status === 'inherit'\n ? importMeta('published')\n : p.status === 'future'\n ? importMeta('published', { publish_at: p.date! })\n : p.status === 'pending'\n ? importMeta('in_review')\n : p.status === 'trash'\n ? importMeta('archived')\n : importMeta('draft')\n }\n const addModel = (m: ModelDefinition): void => {\n models[m.id] = m\n contents[m.id] ??= {}\n metas[m.id] ??= {}\n }\n\n // ── identities (shared formulas — REST and WXR must agree) ──\n const authorId = (login: string): string => hexId(`authors:${login}`)\n const termId = (tax: string, slug: string): string => hexId(`${tax}:${slug}`)\n const usedSlugs = new Map<string, number>()\n const postSlug = (p: RawPost): string => {\n let s = slugify(decodeSlug(p.slug))\n if (!s) {\n s = `${p.type}-${p.id}`\n report.slug_fallback++\n } else if (s !== p.slug) report.slug_rewritten++\n // Slugs are unique per type — and per locale on a multilingual site, where\n // `/about/` and `/tr/about/` are different entries with the same slug.\n const key = multilingual ? `${p.type}:${postLocale(p)}:${s}` : `${p.type}:${s}`\n const n = usedSlugs.get(key) ?? 0\n usedSlugs.set(key, n + 1)\n return n ? `${s}-${p.id}` : s\n }\n const slugOf = new Map<number, string>()\n const postEntry = new Map<number, { model: string; ref: string }>()\n for (const p of raw.posts.toSorted((a, b) => a.id - b.id)) {\n // Only exported entries may be relation targets or appear in the source map.\n if (SKIP_TYPES.test(p.type)) continue\n slugOf.set(p.id, postSlug(p))\n }\n // Keep established slug identities unless distinct translation groups collide.\n // Prefer the default-locale group, then the lowest WP id, independently of\n // REST pagination/WXR order. A colliding group gets a WP-id namespace.\n const identityOwner = new Map<string, number>()\n const exported = raw.posts.filter((p) => !SKIP_TYPES.test(p.type))\n const canonicalPosts = exported.filter((p) => (canonicalOf.get(p.id) ?? p.id) === p.id)\n .toSorted((a, b) => Number(postLocale(b) === locale) - Number(postLocale(a) === locale) || a.id - b.id)\n for (const p of canonicalPosts) {\n const key = `${typeModelId(p.type)}:${slugOf.get(p.id)!}`\n if (!identityOwner.has(key)) identityOwner.set(key, p.id)\n }\n for (const p of exported) {\n const canonical = canonicalOf.get(p.id) ?? p.id\n const mid = typeModelId(p.type)\n const key = `${mid}:${slugOf.get(canonical) ?? slugOf.get(p.id)!}`\n postEntry.set(p.id, { model: mid, ref: hexId(identityOwner.get(key) === canonical ? key : `${mid}:wp:${canonical}`) })\n }\n const mediaRef = (id: number): string | null => (raw.attachments.some((a) => a.id === id) ? hexId(`media:${id}`) : null)\n const titleOf = (p: RawPost): string => {\n const t = strip(p.title)\n if (t) return t\n report.title_fallback++\n return slugOf.get(p.id) ?? `#${p.id}`\n }\n\n // ── authors ──\n addModel({\n id: 'authors', name: 'Authors', kind: 'collection', domain: 'blog', i18n: false, title_field: 'name',\n fields: {\n name: { type: 'string', required: true, label: 'Name', order: 10 },\n slug: { type: 'slug', required: true, unique: true, label: 'Slug', order: 20 },\n email: { type: 'email', label: 'Email', order: 30 },\n wp_id: { type: 'integer', label: 'WP user ID', order: 40 },\n },\n })\n for (const a of raw.authors) {\n const id = authorId(slugify(a.login))\n contents.authors![id] = pick(\n { name: strip(a.display_name), slug: slugify(a.login), email: a.email, wp_id: a.id },\n new Set(['name', 'slug', 'email', 'wp_id']),\n )\n metas.authors![id] = importMeta('published')\n }\n for (const p of raw.posts) {\n if (p.author && !contents.authors![authorId(slugify(p.author))]) {\n contents.authors![authorId(slugify(p.author))] = { name: p.author, slug: slugify(p.author) }\n metas.authors![authorId(slugify(p.author))] = importMeta('published')\n }\n }\n\n // ── taxonomies (nav_menu and post_format excluded; post_format → select field) ──\n const taxonomies = [...new Set(raw.terms.map((t) => t.taxonomy))].filter(\n (t) => t !== 'nav_menu' && t !== 'post_format' && !LANGUAGE_TAXONOMIES.has(t),\n )\n for (const tax of taxonomies) {\n const mid = taxModelId(tax)\n addModel({\n id: mid, name: mid, kind: 'collection', domain: 'blog', i18n: false, title_field: 'name',\n fields: {\n name: { type: 'string', required: true, label: 'Name', order: 10 },\n slug: { type: 'slug', required: true, unique: true, label: 'Slug', order: 20 },\n description: { type: 'text', label: 'Description', order: 30 },\n parent: { type: 'relation', model: mid, label: 'Parent', order: 40 },\n wp_id: { type: 'integer', label: 'WP term ID', order: 50 },\n },\n })\n for (const t of raw.terms.filter((x) => x.taxonomy === tax)) {\n const id = termId(tax, t.slug)\n contents[mid]![id] = pick(\n {\n name: strip(t.name),\n slug: slugify(decodeSlug(t.slug)) || `term-${t.id}`,\n description: strip(t.description),\n parent: t.parent && t.parent_resolved ? termId(tax, t.parent) : null,\n wp_id: t.id,\n },\n new Set(['name', 'slug', 'description', 'parent', 'wp_id']),\n )\n metas[mid]![id] = importMeta('published')\n }\n }\n // referenced-but-unlisted terms join the pool (marked resolved:false upstream, never dropped)\n for (const p of raw.posts) {\n for (const t of p.terms) {\n if (t.taxonomy === 'nav_menu' || t.taxonomy === 'post_format' || t.resolved) continue\n const mid = taxModelId(t.taxonomy)\n if (!models[mid]) continue\n const id = termId(t.taxonomy, t.slug)\n contents[mid]![id] ??= { name: strip(t.name), slug: slugify(t.slug) }\n metas[mid]![id] ??= importMeta('published')\n }\n }\n\n const postTypes = [...new Set(raw.posts.map((p) => p.type))].filter((t) => {\n if (SKIP_TYPES.test(t)) {\n report.skipped_types.push(t)\n return false\n }\n return true\n })\n const contentModelIds = postTypes.map(typeModelId)\n const toContent = relationOver(contentModelIds)\n\n // ── media ──\n addModel({\n id: 'media', name: 'Media', kind: 'collection', domain: 'assets', i18n: false, title_field: 'title',\n fields: {\n title: { type: 'string', required: true, label: 'Title', order: 10 },\n slug: { type: 'slug', required: true, unique: true, label: 'Slug', order: 20 },\n url: { type: 'url', required: true, label: 'Source URL', order: 30 },\n alt: { type: 'string', label: 'Alt text', order: 40 },\n caption: { type: 'text', label: 'Caption', order: 50 },\n description: { type: 'text', label: 'Description', order: 60 },\n mime: { type: 'string', label: 'MIME type', order: 70 },\n width: { type: 'integer', label: 'Width', order: 80 },\n height: { type: 'integer', label: 'Height', order: 90 },\n file: { type: 'string', label: 'Upload path', order: 100 },\n parent: { type: 'relation', model: toContent.model, label: 'Attached to', order: 110 },\n wp_id: { type: 'integer', label: 'WP attachment ID', order: 120 },\n uploaded_at: { type: 'datetime', label: 'Uploaded at', order: 130 },\n },\n })\n const mediaSlugs = new Set<string>()\n for (const a of raw.attachments) {\n const id = hexId(`media:${a.id}`)\n let slug = slugify(decodeSlug(a.slug)) || `media-${a.id}`\n if (mediaSlugs.has(slug)) slug = `${slug}-${a.id}`\n mediaSlugs.add(slug)\n const target = a.parent ? postEntry.get(a.parent) : undefined\n if (a.parent && !target) report.dropped_relations++\n const parent = target ? toContent.ref(target) : null\n const im = (a.image_meta ?? null) as { width?: number; height?: number } | null\n contents.media![id] = pick(\n {\n title: strip(a.title) || slug,\n slug,\n url: a.url,\n alt: strip(a.alt),\n caption: strip(a.caption),\n description: strip(a.description),\n mime: a.mime,\n width: im?.width,\n height: im?.height,\n file: a.file,\n parent,\n wp_id: a.id,\n uploaded_at: a.date,\n },\n new Set(['title', 'slug', 'url', 'alt', 'caption', 'description', 'mime', 'width', 'height', 'file', 'parent', 'wp_id', 'uploaded_at']),\n )\n metas.media![id] = importMeta('published')\n }\n\n // ── post types (post, page, CPTs) ──\n for (const type of postTypes) {\n const typeItems = raw.posts.filter((p) => p.type === type)\n const mid = typeModelId(type)\n const taxes = [...new Set(typeItems.flatMap((p) => p.terms.map((t) => t.taxonomy)))].filter((t) => models[taxModelId(t)])\n const { fields, order } = coreFields({\n excerpt: typeItems.some((p) => p.excerpt),\n body: typeItems.some((p) => p.content),\n date: typeItems.some((p) => p.date),\n author: typeItems.some((p) => p.author),\n taxes,\n cover: typeItems.some((p) => p.meta._thumbnail_id),\n })\n let o = order\n fields.wp_id = { type: 'integer', required: true, unique: true, label: 'WP post ID', order: (o += 10) }\n fields.modified_at = { type: 'datetime', label: 'Modified at', order: (o += 10) }\n fields.link = { type: 'url', label: 'Original permalink', order: (o += 10) }\n const parentModels = [...new Set(typeItems.flatMap((p) => {\n const parent = p.parent ? postEntry.get(p.parent) : undefined\n return parent ? [parent.model] : []\n }))].toSorted()\n if (typeItems.some((p) => p.parent)) fields.parent = {\n type: 'relation',\n model: parentModels.length > 1 ? parentModels : (parentModels[0] ?? mid),\n label: 'Parent', order: (o += 10),\n }\n if (typeItems.some((p) => p.menu_order)) fields.menu_order = { type: 'integer', label: 'Menu order', order: (o += 10) }\n if (typeItems.some((p) => p.sticky)) fields.sticky = { type: 'boolean', label: 'Sticky', order: (o += 10) }\n if (typeItems.some((p) => typeof p.meta._wp_page_template === 'string' && p.meta._wp_page_template !== 'default'))\n fields.template = { type: 'string', label: 'Page template', order: (o += 10) }\n const formats = [\n ...new Set(\n typeItems.flatMap((p) =>\n p.terms.filter((t) => t.taxonomy === 'post_format').map((t) => t.slug.replace(/^post-format-/, '')),\n ),\n ),\n ].toSorted()\n if (formats.length) fields.format = { type: 'select', options: formats, label: 'Post format', order: (o += 10) }\n if (typeItems.some((p) => p.status === 'private' || p.password))\n fields.visibility = { type: 'select', options: ['public', 'private', 'password'], label: 'Visibility', order: (o += 10) }\n if (typeItems.some((p) => p.comment_status))\n fields.comments_open = { type: 'boolean', label: 'Comments open', order: (o += 10) }\n for (const p of typeItems) {\n for (const [k, v] of Object.entries(p.meta)) {\n if (k.startsWith('_') || fields[k] || PLUGIN_META.test(k) || k === 'enclosure') continue\n const t = byValue(v)\n if (t && t !== 'object') {\n fields[k] = { type: t as FieldDef['type'], label: k, order: (o += 10) }\n report.meta_fields[k] = t\n }\n }\n for (const [k, acf] of Object.entries(p.acf ?? {})) {\n if (fields[k]) continue\n const t = byValue(acf.value) ?? 'string'\n fields[k] = { type: (t === 'object' ? 'object' : t) as FieldDef['type'], label: k, description: 'ACF', order: (o += 10) }\n report.acf_fields[k] = t\n }\n }\n // The locales this type actually has content in. A partially-translated\n // site — pages in one language, posts in three — used to fail validation on\n // every untranslated entry, because parity was checked against the whole\n // project list. Declaring the real coverage says so once, in the model.\n //\n // The default locale is always in: it is the site's source of truth, and a\n // post that carries no language tag belongs to it (`postLocale`), so its\n // absence here would be the importer's uncertainty, not a fact about the\n // site. Full coverage writes nothing — absent already means \"all\", and a\n // redundant list would then have to be maintained as locales are added.\n const covered = locales.filter(l => l === locale || typeItems.some((p) => postLocale(p) === l))\n addModel({\n id: mid,\n name: type === 'post' ? 'Posts' : type === 'page' ? 'Pages' : mid,\n kind: 'collection',\n domain: domainOf(type),\n i18n: multilingual,\n ...(multilingual && covered.length < locales.length ? { locales: covered } : {}),\n title_field: 'title',\n fields,\n })\n for (const p of typeItems) {\n const id = postEntry.get(p.id)!.ref\n const loc = postLocale(p)\n const contentBucket = multilingual ? ((localeContents[mid] ??= {})[loc] ??= {}) : contents[mid]!\n const metaBucket = multilingual ? ((localeMetas[mid] ??= {})[loc] ??= {}) : metas[mid]!\n const e: Entry = { title: titleOf(p), slug: slugOf.get(p.id), wp_id: p.id }\n if (fields.excerpt) e.excerpt = strip(p.excerpt)\n if (fields.body) e.body = p.content // Gutenberg comments and shortcodes verbatim (known gap)\n if (fields.published_at && p.date) e.published_at = p.date\n if (p.modified) e.modified_at = p.modified\n if (p.link) e.link = p.link\n if (fields.author && p.author) e.author = authorId(slugify(p.author))\n for (const t of taxes) {\n e[taxModelId(t)] = p.terms\n .filter((x) => x.taxonomy === t && contents[taxModelId(t)]![termId(t, x.slug)])\n .map((x) => termId(t, x.slug))\n }\n if (fields.cover && p.meta._thumbnail_id) {\n const m = mediaRef(Number(p.meta._thumbnail_id))\n if (m) e.cover = m\n else report.dropped_relations++\n }\n if (fields.parent && p.parent) {\n const pe = postEntry.get(p.parent)\n if (pe) e.parent = parentModels.length > 1 ? pe : pe.ref\n else report.dropped_relations++\n }\n if (fields.menu_order && p.menu_order) e.menu_order = p.menu_order\n if (fields.sticky) e.sticky = p.sticky ?? false\n if (fields.template && typeof p.meta._wp_page_template === 'string' && p.meta._wp_page_template !== 'default')\n e.template = p.meta._wp_page_template\n if (fields.format) {\n const f = p.terms.find((t) => t.taxonomy === 'post_format')\n if (f) e.format = f.slug.replace(/^post-format-/, '')\n }\n if (fields.visibility) e.visibility = p.password ? 'password' : p.status === 'private' ? 'private' : 'public'\n if (fields.comments_open) e.comments_open = p.comment_status === 'open'\n for (const k of Object.keys(fields)) if (k in p.meta && !(k in e) && !k.startsWith('_')) e[k] = p.meta[k]\n for (const [k, acf] of Object.entries(p.acf ?? {})) if (fields[k] && !(k in e)) e[k] = acf.value\n contentBucket[id] = e\n metaBucket[id] = mapStatus(p)\n }\n }\n\n // ── menus ──\n const menus = raw.menus ?? []\n if (menus.length) {\n addModel({\n id: 'menus', name: 'Menus', kind: 'collection', domain: 'site', i18n: false, title_field: 'name',\n fields: {\n name: { type: 'string', required: true, label: 'Name', order: 10 },\n slug: { type: 'slug', required: true, unique: true, label: 'Slug', order: 20 },\n items: { type: 'relations', model: 'menu-items', label: 'Items', order: 30 },\n wp_id: { type: 'integer', label: 'WP term ID', order: 40 },\n // Only when the source said where its menus are shown: stores from sources that do not know stay as they were.\n ...(menus.some((m) => m.locations?.length) ? { locations: { type: 'array', items: 'string', label: 'Locations', order: 50 } as FieldDef } : {}),\n },\n })\n const toTarget = relationOver([...contentModelIds, ...taxonomies.map(taxModelId)])\n addModel({\n id: 'menu-items', name: 'Menu items', kind: 'collection', domain: 'site', i18n: false, title_field: 'title',\n fields: {\n title: { type: 'string', required: true, label: 'Label', order: 10 },\n menu: { type: 'relation', model: 'menus', required: true, label: 'Menu', order: 20 },\n order: { type: 'integer', label: 'Order', order: 30 },\n parent: { type: 'relation', model: 'menu-items', label: 'Parent item', order: 40 },\n type: { type: 'select', options: ['custom', 'post_type', 'taxonomy', 'post_type_archive'], label: 'Type', order: 50 },\n url: { type: 'url', label: 'URL', order: 60 },\n target: { type: 'relation', model: toTarget.model, label: 'Target', order: 70 },\n open_in_new_tab: { type: 'boolean', label: 'Open in new tab', order: 80 },\n classes: { type: 'array', items: 'string', label: 'CSS classes', order: 90 },\n description: { type: 'text', label: 'Description', order: 100 },\n wp_id: { type: 'integer', label: 'WP post ID', order: 110 },\n },\n })\n const itemRef = (id: number): string => hexId(`menu-items:${id}`)\n for (const m of menus) {\n const mid = hexId(`menus:${m.slug}`)\n contents.menus![mid] = {\n name: strip(m.name),\n slug: slugify(m.slug) || `menu-${m.id}`,\n items: m.items.map((i) => itemRef(i.id)),\n wp_id: m.id,\n ...(m.locations?.length ? { locations: m.locations } : {}),\n }\n metas.menus![mid] = importMeta('published')\n for (const i of m.items) {\n const e: Entry = {\n title: strip(i.title) || i.url || `item-${i.id}`,\n menu: mid,\n order: i.order,\n type: i.target.kind === 'url' ? 'custom' : i.target.kind === 'post' ? 'post_type' : i.target.kind === 'term' ? 'taxonomy' : i.target.kind === 'archive' ? 'post_type_archive' : 'custom',\n // A block navigation's items have no WordPress id (negative placeholders): none is claimed.\n ...(i.id > 0 ? { wp_id: i.id } : {}),\n open_in_new_tab: i.target_attr === '_blank',\n }\n if (i.parent && !i.parent_unresolved) e.parent = itemRef(i.parent)\n if (i.target.kind === 'url' && i.url) e.url = i.url\n if (i.target.kind === 'post' && i.target.resolved && i.target.id != null) {\n const pe = postEntry.get(i.target.id)\n if (pe) e.target = toTarget.ref(pe)\n else report.dropped_relations++\n }\n if (i.target.kind === 'term' && i.target.resolved && i.target.slug && models[taxModelId(i.target.taxonomy)])\n e.target = toTarget.ref({ model: taxModelId(i.target.taxonomy), ref: termId(i.target.taxonomy, i.target.slug) })\n if (i.classes?.length) e.classes = i.classes\n if (i.description) e.description = strip(i.description)\n contents['menu-items']![itemRef(i.id)] = e\n metas['menu-items']![itemRef(i.id)] = importMeta(i.status === 'publish' ? 'published' : 'draft')\n }\n }\n }\n\n // ── comments (frozen archive collection; the live-service path is CommentsExport) ──\n const comments = raw.comments ?? []\n if (comments.length) {\n addModel({\n id: 'comments', name: 'Comments', kind: 'collection', domain: 'blog', i18n: false, title_field: 'author',\n fields: {\n author: { type: 'string', required: true, label: 'Author', order: 10 },\n email: { type: 'email', label: 'Email', order: 20 },\n url: { type: 'url', label: 'Website', order: 30 },\n body: { type: 'richtext', label: 'Body', order: 40 },\n published_at: { type: 'datetime', label: 'Date', order: 50 },\n post: { type: 'relation', model: toContent.model, required: true, label: 'Post', order: 60 },\n parent: { type: 'relation', model: 'comments', label: 'In reply to', order: 70 },\n type: { type: 'string', label: 'Type', order: 80 },\n user: { type: 'relation', model: 'authors', label: 'User', order: 90 },\n wp_id: { type: 'integer', label: 'WP comment ID', order: 100 },\n },\n })\n const cRef = (id: number): string => hexId(`comments:${id}`)\n const userById = new Map(raw.authors.filter((a) => a.id != null).map((a) => [a.id, authorId(slugify(a.login))]))\n for (const c of comments) {\n const post = postEntry.get(c.post)\n if (!post) {\n report.dropped_relations++\n continue\n }\n contents.comments![cRef(c.id)] = pick(\n {\n author: strip(c.author) || 'anonymous',\n email: c.email,\n url: c.url,\n body: c.content,\n published_at: c.date,\n post: toContent.ref(post),\n parent: c.parent && c.parent_resolved ? cRef(c.parent) : null,\n type: c.type,\n user: c.user_id ? userById.get(c.user_id) : null,\n wp_id: c.id,\n },\n new Set(['author', 'email', 'url', 'body', 'published_at', 'post', 'parent', 'type', 'user', 'wp_id']),\n )\n metas.comments![cRef(c.id)] = importMeta(\n c.approved === '1' ? 'published' : c.approved === 'spam' || c.approved === 'trash' ? 'archived' : 'in_review',\n )\n }\n }\n\n // ── site singleton + vocabulary ──\n addModel({\n id: 'site', name: 'Site', kind: 'singleton', domain: 'site', i18n: false, title_field: 'title',\n fields: {\n title: { type: 'string', required: true, label: 'Site title', order: 10 },\n tagline: { type: 'string', label: 'Tagline', order: 20 },\n url: { type: 'url', label: 'URL', order: 30 },\n language: { type: 'string', label: 'Language', order: 40 },\n },\n })\n siteEntry = pick(\n { title: strip(raw.site.title) || 'Site', tagline: raw.site.description, url: raw.site.url, language: raw.site.language },\n new Set(['title', 'tagline', 'url', 'language']),\n )\n siteMeta = importMeta('published')\n const vocabTerms: Record<string, Record<string, string>> = {}\n for (const m of menus) {\n for (const i of m.items) {\n const k = slugify(strip(i.title))\n if (k && !vocabTerms[k]) vocabTerms[k] = { [locale]: strip(i.title) }\n }\n }\n\n // ── file map (canonical serialization; PATH_PATTERNS layout) ──\n const files: Record<string, string> = {}\n const domains = [...new Set(Object.values(models).map((m) => m.domain))].toSorted()\n for (const m of Object.values(models)) {\n files[`.contentrain/models/${m.id}.json`] = canon(m)\n if (m.i18n) {\n // One content + meta file per locale; an entry id recurs across the\n // locales it has a translation in.\n const perLocale = localeContents[m.id] ?? {}\n const ids = new Set<string>()\n for (const loc of Object.keys(perLocale).toSorted()) {\n files[`.contentrain/content/${m.domain}/${m.id}/${loc}.json`] = canon(perLocale[loc])\n files[`.contentrain/meta/${m.id}/${loc}.json`] = canon(localeMetas[m.id]?.[loc] ?? {})\n for (const id of Object.keys(perLocale[loc]!)) ids.add(id)\n }\n report.models[m.id] = { kind: m.kind, domain: m.domain, fields: Object.keys(m.fields ?? {}).length, entries: ids.size }\n continue\n }\n const content = m.kind === 'singleton' ? siteEntry : contents[m.id]!\n const meta = m.kind === 'singleton' ? siteMeta : metas[m.id]!\n files[`.contentrain/content/${m.domain}/${m.id}/data.json`] = canon(content)\n files[`.contentrain/meta/${m.id}/${locale}.json`] = canon(meta)\n report.models[m.id] = {\n kind: m.kind,\n domain: m.domain,\n fields: Object.keys(m.fields ?? {}).length,\n entries: m.kind === 'singleton' ? 1 : Object.keys(contents[m.id]!).length,\n }\n }\n files['.contentrain/config.json'] = canon({\n version: 1,\n stack: 'astro',\n platform: 'web',\n workflow: 'review',\n locales: { default: locale, supported: locales },\n domains,\n })\n files['.contentrain/vocabulary.json'] = canon({ version: 1, terms: vocabTerms })\n\n const entrySourceMap: EntrySourceMap = {}\n for (const [wpId, ref] of postEntry) {\n entrySourceMap[String(wpId)] = { model_id: ref.model, entry_id: ref.ref, locale: postLocale(postById.get(wpId)!) }\n }\n\n files['import-report.json'] = canon(report)\n return { files, entry_source_map: entrySourceMap, report }\n}\n","// CommentsExport builder — the bridge from a migrated static site to a live\n// comments service. Everything the receiving side needs travels here: the\n// entry addresses (WordPress ids mean nothing after migration), the verbatim\n// comments, and which threads were closed at the source.\n\nimport type { CommentsExport, EntrySourceMap, HandoffComments, RawComment, RawIR } from '@contentrain/types'\nimport { COMMENTS_EXPORT_FORMAT, MIGRATION_CONTRACT_VERSION } from '@contentrain/types'\n\n/**\n * The comments that may leave the source site (see `CommentsExport.comments`). An allowlist, so it\n * fails closed: a comment travels only when its entry is in this RawIR and public, and its status is\n * approved (`'1'`, or none) or pending (`'0'`). Everything else is counted in `excluded`: spam, trash,\n * WordPress's `post-trashed`, a plugin's own status, a post this RawIR does not hold.\n */\nexport function selectComments(raw: RawIR): { comments: RawComment[]; excluded: NonNullable<CommentsExport['excluded']> } {\n const posts = new Map(raw.posts.map((p) => [p.id, p]))\n const excluded: NonNullable<CommentsExport['excluded']> = {}\n const count = (key: keyof typeof excluded) => { excluded[key] = (excluded[key] ?? 0) + 1 }\n const comments: RawComment[] = []\n for (const c of raw.comments ?? []) {\n const post = posts.get(c.post)\n if (!post) { count('unknown_entry'); continue }\n if (post.status !== 'publish' || (post.password !== null && post.password !== undefined && post.password !== '')) { count('non_public_entry'); continue }\n const status = c.approved ?? '1'\n if (status === '1' || status === '0') { comments.push(c); continue }\n count(status === 'spam' ? 'spam' : status === 'trash' ? 'trash' : 'other_status')\n }\n return { comments, excluded }\n}\n\nexport function buildCommentsExport(raw: RawIR, entries: EntrySourceMap, opts?: { generated_at?: string }): CommentsExport {\n const threadsClosed = raw.posts.filter((p) => p.comment_status && p.comment_status !== 'open').map((p) => p.id)\n const { comments, excluded } = selectComments(raw)\n return {\n version: MIGRATION_CONTRACT_VERSION,\n format: COMMENTS_EXPORT_FORMAT,\n source: raw.provenance,\n site_url: raw.site.url || undefined,\n generated_at: opts?.generated_at ?? new Date().toISOString(),\n entries,\n threads_closed: threadsClosed.length ? threadsClosed : undefined,\n comments,\n excluded: Object.keys(excluded).length ? excluded : undefined,\n }\n}\n\n/** Handoff summary for the export: counts + closed threads + what could not be addressed. */\nexport function summarizeComments(exp: CommentsExport): HandoffComments {\n const byStatus: Record<string, number> = {}\n const byType: Record<string, number> = {}\n const unresolved: Array<{ comment_id: number; post: number; reason: string }> = []\n for (const c of exp.comments) {\n byStatus[c.approved ?? '1'] = (byStatus[c.approved ?? '1'] ?? 0) + 1\n byType[c.type ?? 'comment'] = (byType[c.type ?? 'comment'] ?? 0) + 1\n if (!exp.entries[String(c.post)]) unresolved.push({ comment_id: c.id, post: c.post, reason: 'post has no entry mapping' })\n }\n return {\n total: exp.comments.length,\n by_status: byStatus,\n types: byType,\n export: { format: exp.format },\n threads_closed: exp.threads_closed,\n unresolved: unresolved.length ? unresolved : undefined,\n excluded: exp.excluded,\n }\n}\n","// SourceDeltaPlan (as a bridge produces it) + the repository's store → a plan\n// a person can review: every origin record placed in the store, or said to be\n// unplaceable and why.\n//\n// The bridge knows what changed at the origin and nothing about the store; the\n// store knows its entries and nothing about the origin. The EntrySourceMap\n// written at import time is the only link, so this module lives next to the\n// code that writes it. Pure over file maps, like `rawToContentrain`: no git,\n// no provider, and nothing is written — applying a plan is a governed write\n// that belongs to whoever reviews it.\n//\n// What the planner refuses to do is decide. A record the repository also\n// edited is flagged, not overwritten; a trashed record stays distinguishable\n// from a purged one; a record it cannot place says why instead of vanishing.\n\nimport type { EntryMeta, EntrySourceMap, ModelDefinition, SourceDeltaEntry, SourceDeltaPlan } from '@contentrain/types'\nimport { canon, taxModelId } from './core.js'\n\n/** A `.contentrain` store as a file map (repo-relative path → file text), with the source map it was built from. */\nexport interface DeltaStore {\n files: Record<string, string>\n entry_source_map: EntrySourceMap\n}\n\nexport interface PlanSourceDeltaInput {\n /** The origin delta, as the bridge wrote it. */\n delta: SourceDeltaPlan\n /** The repository's store, as it is now — including edits made since the import. */\n store: DeltaStore\n /** The new export the delta describes. Without it the plan has no field-level differences and no address for a created record. */\n incoming?: DeltaStore\n /**\n * Origin types that are taxonomies. Their ids are term ids, which the\n * source map (post ids) must never be consulted for: post 6 and category 6\n * are different records. Defaults to WordPress core's.\n */\n taxonomies?: string[]\n /**\n * `updated_by` values that mean \"written by an import\". Meta with any other\n * writer — or with a `source` other than `import` — is a repository edit.\n */\n importers?: string[]\n}\n\nexport const DEFAULT_TAXONOMIES = ['category', 'post_tag', 'nav_menu', 'post_format'] as const\nexport const DEFAULT_IMPORTERS = ['contentrain-bridge', '@contentrain/wp-import'] as const\n\ninterface Placed {\n model: ModelDefinition\n entry_id: string\n locale: string\n}\n\ntype Placement = Placed | { unmapped: NonNullable<SourceDeltaEntry['unmapped']> }\n\n/** A stored entry, reduced to what a comparison needs: each field's value as text, and its meta. */\ninterface StoredEntry {\n fields: Record<string, string>\n meta?: EntryMeta\n}\n\n// ─── Store reading ───\n\nconst parseJson = (text: string | undefined): unknown => {\n if (text === undefined) return undefined\n try {\n return JSON.parse(text)\n }\n catch {\n return undefined\n }\n}\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined\n\nfunction readModel(files: Record<string, string>, id: string): ModelDefinition | undefined {\n const model = asRecord(parseJson(files[`.contentrain/models/${id}.json`]))\n return model && model.id === id ? (model as unknown as ModelDefinition) : undefined\n}\n\nfunction defaultLocale(files: Record<string, string>): string {\n const config = asRecord(parseJson(files['.contentrain/config.json']))\n const locales = asRecord(config?.locales)\n return typeof locales?.default === 'string' ? locales.default : 'en'\n}\n\n/** The model's own directory. A custom `content_path` or locale strategy is not read — the entry is reported as not found. */\nconst contentDir = (model: ModelDefinition): string | undefined =>\n model.content_path || (model.locale_strategy && model.locale_strategy !== 'file')\n ? undefined\n : `.contentrain/content/${model.domain}/${model.id}`\n\n/**\n * A markdown document's fields as raw text: each top-level frontmatter key\n * with its value lines (a list's items included), and `body`. Compared as\n * written — the store is canonical, so equal values are equal text.\n */\nfunction documentFields(text: string): Record<string, string> {\n const fields: Record<string, string> = {}\n const match = /^---\\n([\\s\\S]*?)\\n---\\n?([\\s\\S]*)$/.exec(text)\n if (!match) return { body: text }\n let key: string | undefined\n for (const line of match[1]!.split('\\n')) {\n const top = /^([^\\s:#][^:]*):(.*)$/.exec(line)\n if (top) {\n key = top[1]!.trim()\n fields[key] = top[2]!.trim()\n }\n else if (key !== undefined) {\n fields[key] += `\\n${line}`\n }\n }\n fields.body = match[2]!\n return fields\n}\n\nfunction readEntry(files: Record<string, string>, at: Placed): StoredEntry | undefined {\n const { model, entry_id: id, locale } = at\n const dir = contentDir(model)\n if (!dir) return undefined\n if (model.kind === 'document') {\n const text = files[model.i18n ? `${dir}/${id}/${locale}.md` : `${dir}/${id}.md`]\n if (text === undefined) return undefined\n const meta = asRecord(parseJson(files[`.contentrain/meta/${model.id}/${id}/${locale}.json`]))\n return { fields: documentFields(text), meta: meta as EntryMeta | undefined }\n }\n if (model.kind !== 'collection') return undefined\n const entries = asRecord(parseJson(files[`${dir}/${model.i18n ? locale : 'data'}.json`]))\n const entry = asRecord(entries?.[id])\n if (!entry) return undefined\n const metas = asRecord(parseJson(files[`.contentrain/meta/${model.id}/${locale}.json`]))\n const fields = Object.fromEntries(Object.entries(entry).map(([key, value]) => [key, canon(value)]))\n return { fields, meta: asRecord(metas?.[id]) as EntryMeta | undefined }\n}\n\n/** The entry in `model` whose `wp_id` is `wpId`, for records the source map does not list (terms, media). */\nfunction findByWpId(files: Record<string, string>, model: ModelDefinition, wpId: number, locale: string): string | undefined {\n const dir = contentDir(model)\n if (!dir) return undefined\n if (model.kind === 'collection') {\n const entries = asRecord(parseJson(files[`${dir}/${model.i18n ? locale : 'data'}.json`])) ?? {}\n return Object.keys(entries).find(id => asRecord(entries[id])?.wp_id === wpId)\n }\n if (model.kind !== 'document') return undefined\n const suffix = model.i18n ? `/${locale}.md` : '.md'\n for (const [path, text] of Object.entries(files)) {\n if (!path.startsWith(`${dir}/`) || !path.endsWith(suffix)) continue\n if (documentFields(text).wp_id === String(wpId)) {\n const rest = path.slice(dir.length + 1, -suffix.length)\n if (!rest.includes('/')) return rest\n }\n }\n return undefined\n}\n\n/** Store models that can hold records of an origin type the source map does not cover. */\nfunction typeModelIds(wpType: string): string[] {\n if (wpType === 'attachment') return ['wp-media', 'media']\n return [`wp-tax-${wpType.replace(/_/g, '-')}`, taxModelId(wpType)]\n}\n\nfunction place(store: DeltaStore, wpType: string | undefined, wpId: number, taxonomies: Set<string>): Placement {\n const { files } = store\n const locale = defaultLocale(files)\n const models = wpType ? typeModelIds(wpType).map(id => readModel(files, id)).filter(model => model !== undefined) : []\n // A listed taxonomy, media, or any type the store has a model of its own for\n // is found by `wp_id` in that model. Only what is left falls to the map.\n if (wpType && (wpType === 'attachment' || taxonomies.has(wpType) || models.length)) {\n if (!models.length) return { unmapped: 'no-model-for-type' }\n for (const model of models) {\n const entryId = findByWpId(files, model, wpId, locale)\n if (entryId) return { model, entry_id: entryId, locale }\n }\n return { unmapped: 'entry-not-found' }\n }\n const ref = store.entry_source_map[String(wpId)]\n if (!ref) return { unmapped: 'not-in-source-map' }\n const model = readModel(files, ref.model_id)\n if (!model) return { unmapped: 'no-model-for-type' }\n return { model, entry_id: ref.entry_id, locale: ref.locale ?? locale }\n}\n\n// ─── Planning ───\n\nconst isPlaced = (placement: Placement): placement is Placed => 'model' in placement\n\nfunction repoEdit(meta: EntryMeta | undefined, importers: Set<string>): SourceDeltaEntry['repo_edit'] {\n if (!meta) return undefined\n if (meta.source === 'import' && importers.has(meta.updated_by)) return undefined\n return {\n updated_by: meta.updated_by,\n ...(meta.updated_at ? { updated_at: meta.updated_at } : {}),\n source: meta.source,\n }\n}\n\nfunction changedFields(before: StoredEntry, after: StoredEntry): string[] {\n const keys = new Set([...Object.keys(before.fields), ...Object.keys(after.fields)])\n return [...keys].filter(key => before.fields[key] !== after.fields[key]).toSorted()\n}\n\nconst DELETED_DETAIL = {\n trashed: 'tombstone: trashed at the origin — it can still come back',\n purged: 'tombstone: purged from the origin',\n} as const\n\nfunction planEntry(entry: SourceDeltaEntry, input: PlanSourceDeltaInput, taxonomies: Set<string>, importers: Set<string>): SourceDeltaEntry {\n const { store, incoming } = input\n const out: SourceDeltaEntry = { ...entry }\n // The bridge's detail for a deletion is the kind itself; the tombstone note below says it in full.\n const notes: string[] = entry.detail && entry.detail !== entry.deleted_kind ? [entry.detail] : []\n\n // A created record is not in the store yet; its address comes from the export that carries it.\n const target = entry.op === 'created'\n ? (incoming ? place(incoming, entry.wp_type, entry.wp_id, taxonomies) : { unmapped: 'not-in-source-map' as const })\n : place(store, entry.wp_type, entry.wp_id, taxonomies)\n\n if (!isPlaced(target)) {\n out.unmapped = target.unmapped\n if (entry.op === 'created' && !incoming) notes.push('no incoming export to place it')\n if (entry.op === 'deleted' && entry.deleted_kind) notes.push(DELETED_DETAIL[entry.deleted_kind])\n out.detail = notes.join('; ')\n return out\n }\n\n out.model = target.model.id\n out.entry_id = target.entry_id\n out.locale = target.locale\n const stored = readEntry(store.files, target)\n\n if (entry.op === 'created') {\n if (stored) notes.push('the store already has an entry at this address')\n }\n else if (!stored) {\n out.unmapped = 'entry-not-found'\n }\n\n if (entry.op === 'deleted' && entry.deleted_kind) notes.push(DELETED_DETAIL[entry.deleted_kind])\n\n if ((entry.op === 'updated' || entry.op === 'moved') && stored) {\n const after = incoming ? place(incoming, entry.wp_type, entry.wp_id, taxonomies) : undefined\n const next = after && isPlaced(after) ? readEntry(incoming!.files, after) : undefined\n if (next) {\n out.fields_changed = changedFields(stored, next)\n if (isPlaced(after!) && after.entry_id !== target.entry_id) out.entry_id_after = after.entry_id\n }\n else {\n notes.push(incoming ? 'not in the incoming export' : 'no incoming export to compare with')\n }\n }\n\n const edit = repoEdit(stored?.meta, importers)\n if (edit) {\n out.conflict = true\n out.repo_edit = edit\n notes.push(`also edited in the repository by ${edit.updated_by}${edit.updated_at ? ` at ${edit.updated_at}` : ''} — not overwritten`)\n }\n\n if (notes.length) out.detail = notes.join('; ')\n return out\n}\n\n/**\n * Place a bridge's source delta in the repository's store.\n *\n * Every entry keeps the bridge's facts (op, ids, fingerprints, paths,\n * `deleted_kind`) and gains its store address — or `unmapped` with the reason.\n * `updated` and `moved` gain `fields_changed` against the incoming export; a\n * record the repository also edited gets `conflict: true` and `repo_edit`;\n * every `moved` whose address changed adds a 301 to `redirects`.\n *\n * Nothing is written and nothing is decided: a conflict is reported for a\n * person to resolve, and applying the plan is a separate, governed step.\n */\nexport function planSourceDelta(input: PlanSourceDeltaInput): SourceDeltaPlan {\n const taxonomies = new Set<string>(input.taxonomies ?? DEFAULT_TAXONOMIES)\n const importers = new Set<string>(input.importers ?? DEFAULT_IMPORTERS)\n const { delta } = input\n const entries = delta.entries.map(entry => planEntry(entry, input, taxonomies, importers))\n\n const redirects = [...(delta.redirects ?? [])]\n const seen = new Set(redirects.map(redirect => redirect.from))\n for (const entry of entries) {\n if (entry.op !== 'moved' || !entry.path_before || !entry.path_after || entry.path_before === entry.path_after) continue\n if (seen.has(entry.path_before)) continue\n seen.add(entry.path_before)\n redirects.push({ from: entry.path_before, to: entry.path_after, status: 301 })\n }\n\n const warnings = [...(delta.warnings ?? [])]\n if (!delta.deletions_detectable) warnings.push('deletions could not be determined from this cursor; the absence of a deleted entry does not mean nothing was deleted')\n if (delta.deletions_undetectable_types?.length) warnings.push(`deletions could not be determined for: ${delta.deletions_undetectable_types.join(', ')}`)\n if (!input.incoming) warnings.push('no incoming export: no field-level differences and no address for created records')\n\n return {\n ...delta,\n entries,\n ...(redirects.length ? { redirects } : {}),\n ...(warnings.length ? { warnings } : {}),\n }\n}\n\n// ─── Report ───\n\nconst address = (entry: SourceDeltaEntry): string =>\n entry.model && entry.entry_id ? `${entry.model}/${entry.entry_id}${entry.entry_id_after ? ` → ${entry.entry_id_after}` : ''}` : `unmapped (${entry.unmapped})`\n\n/** The plan as text, for a dry run: one line per record, then conflicts, unmapped records, redirects and warnings. */\nexport function formatSourceDeltaReport(plan: SourceDeltaPlan): string {\n const counts = new Map<string, number>()\n for (const entry of plan.entries) counts.set(entry.op, (counts.get(entry.op) ?? 0) + 1)\n const summary = [...counts].map(([op, n]) => `${n} ${op}`).join(', ') || 'no changes'\n const { cursor } = plan\n const lines = [\n `Source delta: ${plan.entries.length} records (${summary})`,\n `Cursor: ${[cursor.kind, cursor.inventory_hash ?? cursor.modified_after ?? cursor.export_id, `(${cursor.taken_at})`].filter(Boolean).join(' ')}`,\n `Deletions: ${plan.deletions_detectable ? 'detectable' : 'NOT detectable'}`,\n '',\n ]\n for (const entry of plan.entries) {\n const parts = [`${entry.op.padEnd(8)} ${entry.wp_type ?? '?'} ${entry.wp_id}`, address(entry)]\n if (entry.op === 'moved' && entry.path_before) parts.push(`${entry.path_before} → ${entry.path_after}`)\n if (entry.deleted_kind) parts.push(entry.deleted_kind)\n if (entry.fields_changed) parts.push(`fields: ${entry.fields_changed.join(', ') || 'none'}`)\n if (entry.conflict) parts.push('CONFLICT')\n lines.push(` ${parts.join(' ')}`)\n }\n const conflicts = plan.entries.filter(entry => entry.conflict)\n const unmapped = plan.entries.filter(entry => entry.unmapped)\n lines.push('', `Conflicts (${conflicts.length})${conflicts.length ? ':' : ''}`)\n for (const entry of conflicts) lines.push(` ${entry.wp_type} ${entry.wp_id} → ${address(entry)}: edited by ${entry.repo_edit?.updated_by}${entry.repo_edit?.updated_at ? ` at ${entry.repo_edit.updated_at}` : ''}`)\n lines.push(`Unmapped (${unmapped.length})${unmapped.length ? ':' : ''}`)\n for (const entry of unmapped) lines.push(` ${entry.op} ${entry.wp_type} ${entry.wp_id}: ${entry.unmapped}`)\n lines.push(`Redirects (${plan.redirects?.length ?? 0})${plan.redirects?.length ? ':' : ''}`)\n for (const redirect of plan.redirects ?? []) lines.push(` ${redirect.from} → ${redirect.to} (${redirect.status})`)\n for (const warning of plan.warnings ?? []) lines.push(`Warning: ${warning}`)\n lines.push('', 'Dry run: nothing was written. Applying a plan goes through review.')\n return `${lines.join('\\n')}\\n`\n}\n"],"mappings":";;;;AAWA,SAAgB,gBAAgB,GAAyB;AACvD,QAAO,OAAO,MAAM,YAAY,2CAA2C,KAAK,EAAE;;AAGpF,SAAgB,eAAe,KAAsB;CACnD,MAAM,MAAM,OAAO,KAAK,KAAK,OAAO;CACpC,IAAI,IAAI;CACR,MAAM,QAAQ,MAAqB;AACjC,QAAM,IAAI,MAAM,gBAAgB,EAAE,WAAW,IAAI;;CAEnD,MAAM,aAAa,OAAuB;EACxC,MAAM,IAAI,IAAI,QAAQ,IAAI,EAAE;AAC5B,MAAI,IAAI,EAAG,MAAK,YAAY,KAAK;EAC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