Skip to content

fix(import): preserve WXR taxonomies and WPML/Polylang translations - #1087

Merged
ascorbic merged 2 commits into
mainfrom
fix/wxr-i18n-and-taxonomies
May 18, 2026
Merged

ascorbic merged 2 commits into
mainfrom
fix/wxr-i18n-and-taxonomies

Conversation

@ascorbic

Copy link
Copy Markdown
Member

What does this PR do?

Fixes two silent data-loss bugs in the WordPress WXR import path.

#1061 — taxonomies dropped. The HTTP execute handler at packages/core/src/astro/routes/api/import/wordpress/execute.ts parsed <wp:category>, <wp:tag>, <wp:term>, and per-item <category domain="..."> blocks correctly, then never persisted anything to taxonomies or content_taxonomies. Categories, tags, and custom-taxonomy assignments were silently discarded at the persistence step. A new import/wxr-taxonomies.ts helper module does the pre-import (find-or-create terms in the seeded category / tag defs and matching custom taxonomies) and per-post attach (TaxonomyRepository.attachToEntry via translation_group). Honours each taxonomy def's collections filter. Unknown custom taxonomies surface in a new result.taxonomies.missingTaxonomies field instead of being silently dropped, so the admin UI can prompt the user to define the taxonomy first.

#1080 — WPML / Polylang translations dropped. The whole upload shared one config.locale. Two posts in different languages that shared a post_name (/en/hello, /ar/hello) collided on the UNIQUE(slug, locale) constraint introduced in migration 019, and the second was rejected. On a 4,449-post WPML site this produced 63.6% data loss. The parser now promotes per-post locale + translation group from WPML's _icl_lang_code / _icl_translation_id / trid and Polylang's _locale / language taxonomy / _translations serialized meta. Each translation imports with its own locale and links to the same translation_group via translationOf. A mirrorTermsToLocales pass ensures term rows exist at every translation's locale, sharing the canonical term's translation_group, so per-locale lookups (getTermsForEntry(..., locale)) resolve correctly on every translation row.

Per-translation term overrides. WPML's "Translate Independently" mode is per-taxonomy, not per-post. A translation that overrides category shouldn't lose its inherited tag or genre assignments. The importer clears the pivot only for taxonomies the translation explicitly carries, then attaches from the WXR. Translations with no per-item assignments fall through with the entire inherited set intact (matches WPML "Sync translations" mode and Polylang's default).

Closes #1061
Closes #1080

Type of change

  • Bug fix

Checklist

  • I have read CONTRIBUTING.md
  • pnpm typecheck passes
  • pnpm lint passes (0 new diagnostics)
  • pnpm test passes (3329 tests in core, +2 for the new inherit/override scenarios)
  • pnpm format has been run
  • I have added/updated tests for my changes (parser unit, normalizer unit, taxonomy helper unit, integration covering both bugs and the override semantics)
  • User-visible strings in the admin UI are wrapped for translation (n/a — server-side change)
  • I have added a changeset

AI-generated code disclosure

  • This PR includes AI-generated code — model/tool: Claude Opus 4.7

Notes

Replaces #1083 (parallel agent attempt at #1061 only). This branch consolidates that effort with the #1080 fix and addresses the cross-cutting per-translation override semantics that #1083 didn't reach.

Copilot AI review requested due to automatic review settings May 18, 2026 10:12
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented May 18, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
docs c2ca7a0 May 18 2026, 11:22 AM

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented May 18, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
emdash-demo-cache c2ca7a0 May 18 2026, 11:23 AM

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented May 18, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
emdash-i18n c2ca7a0 May 18 2026, 11:21 AM

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented May 18, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
emdash-playground c2ca7a0 May 18 2026, 11:22 AM

@github-actions

Copy link
Copy Markdown
Contributor

Scope check

This PR changes 2,239 lines across 10 files. Large PRs are harder to review and more likely to be closed without review.

If this scope is intentional, no action needed. A maintainer will review it. If not, please consider splitting this into smaller PRs.

See CONTRIBUTING.md for contribution guidelines.

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented May 18, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
emdash-perf-coordinator c2ca7a0 May 18 2026, 11:21 AM

@changeset-bot

changeset-bot Bot commented May 18, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: c2ca7a0

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 13 packages
Name Type
emdash Patch
@emdash-cms/cloudflare Patch
@emdash-cms/fixture-perf-site Patch
@emdash-cms/perf-demo-site Patch
@emdash-cms/cache-demo-site Patch
@emdash-cms/admin Patch
@emdash-cms/auth Patch
@emdash-cms/blocks Patch
@emdash-cms/gutenberg-to-portable-text Patch
@emdash-cms/x402 Patch
create-emdash Patch
@emdash-cms/auth-atproto Patch
@emdash-cms/plugin-embeds Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@ascorbic

Copy link
Copy Markdown
Member Author

/review

@pkg-pr-new

pkg-pr-new Bot commented May 18, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@emdash-cms/admin

npm i https://pkg.pr.new/@emdash-cms/admin@1087

@emdash-cms/auth

npm i https://pkg.pr.new/@emdash-cms/auth@1087

@emdash-cms/blocks

npm i https://pkg.pr.new/@emdash-cms/blocks@1087

@emdash-cms/cloudflare

npm i https://pkg.pr.new/@emdash-cms/cloudflare@1087

emdash

npm i https://pkg.pr.new/emdash@1087

create-emdash

npm i https://pkg.pr.new/create-emdash@1087

@emdash-cms/gutenberg-to-portable-text

npm i https://pkg.pr.new/@emdash-cms/gutenberg-to-portable-text@1087

@emdash-cms/x402

npm i https://pkg.pr.new/@emdash-cms/x402@1087

@emdash-cms/plugin-ai-moderation

npm i https://pkg.pr.new/@emdash-cms/plugin-ai-moderation@1087

@emdash-cms/plugin-atproto

npm i https://pkg.pr.new/@emdash-cms/plugin-atproto@1087

@emdash-cms/plugin-audit-log

npm i https://pkg.pr.new/@emdash-cms/plugin-audit-log@1087

@emdash-cms/plugin-color

npm i https://pkg.pr.new/@emdash-cms/plugin-color@1087

@emdash-cms/plugin-embeds

npm i https://pkg.pr.new/@emdash-cms/plugin-embeds@1087

@emdash-cms/plugin-forms

npm i https://pkg.pr.new/@emdash-cms/plugin-forms@1087

@emdash-cms/plugin-webhook-notifier

npm i https://pkg.pr.new/@emdash-cms/plugin-webhook-notifier@1087

commit: c2ca7a0

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR extends the WordPress WXR import path to preserve taxonomy assignments and multilingual metadata, addressing data loss around categories/tags/custom taxonomies and WPML/Polylang translations.

Changes:

  • Adds WXR taxonomy pre-import, attachment, and locale mirroring helpers.
  • Promotes per-post locale/translation group metadata from WXR parser output and wires it into the HTTP import execute flow.
  • Adds unit and integration coverage plus a patch changeset.

Reviewed changes

Copilot reviewed 10 out of 10 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
.changeset/fresh-views-stop.md Documents the WXR taxonomy and i18n import fixes.
packages/core/src/astro/routes/api/import/wordpress/execute.ts Wires taxonomy import, per-post locale, and translation linking into HTTP WXR import.
packages/core/src/cli/wxr/parser.ts Promotes WPML/Polylang locale and translation metadata while parsing WXR posts.
packages/core/src/import/sources/wxr.ts Forwards locale/translationGroup to normalized WXR items and filters Polylang language taxonomy.
packages/core/src/import/wxr-taxonomies.ts Adds helpers for pre-creating terms, attaching post terms, and mirroring terms to locales.
packages/core/src/index.ts Exports WxrTerm.
packages/core/tests/integration/wordpress-import/wxr-i18n-taxonomies.test.ts Adds integration coverage for HTTP WXR i18n and taxonomy persistence.
packages/core/tests/unit/cli/wxr-parser.test.ts Adds parser coverage for WPML/Polylang metadata promotion.
packages/core/tests/unit/import/wxr-i18n.test.ts Adds normalized WXR item i18n/custom taxonomy tests.
packages/core/tests/unit/import/wxr-taxonomies.test.ts Adds isolated taxonomy helper tests.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +101 to +112
* `(name, locale)` uniquely identifies one — when no locale is supplied we
* take the lowest-locale-code match (deterministic across calls) so a single-
* locale install behaves identically.
*/
async function findTaxonomyDef(
db: Kysely<Database>,
name: string,
locale: string | undefined,
): Promise<{ id: string; collections: string[] } | null> {
let query = db.selectFrom("_emdash_taxonomy_defs").selectAll().where("name", "=", name);
if (locale !== undefined) query = query.where("locale", "=", locale);
const row = await query.orderBy("locale", "asc").executeTakeFirst();
Comment on lines +161 to +165
for (const key of WPML_TRID_META_KEYS) {
const value = post.meta.get(key);
if (value) {
post.translationGroup = `wpml:${value}`;
break;
Comment on lines +454 to +462
try {
await repo.create({
name: taxonomyName,
slug,
label: slug, // we don't have a per-locale label from the WXR
locale,
translationOf: canonicalTermId,
});
} catch (error) {
Comment thread .changeset/fresh-views-stop.md Outdated

Per-post taxonomy assignments parsed from `<wp:category>`, `<wp:tag>`, `<wp:term>`, and per-item `<category domain="…">` blocks (#1061) are now persisted. The HTTP execute handler previously extracted this data and silently discarded it before any taxonomy or pivot rows were written. Terms are created idempotently in EmDash's seeded `category` / `tag` taxonomies; custom taxonomies (`genre`, etc.) are matched against existing EmDash definitions. Unknown custom taxonomies surface in a new `result.taxonomies.missingTaxonomies` field instead of being silently dropped, so the admin can prompt the user to create the missing definition. Assignments respect each taxonomy definition's `collections` array.

WPML and Polylang translations (#1080) are now imported under their own per-post locale and linked via `translation_group`. Previously the entire upload shared one `config.locale` and the second post of any translation pair was rejected by the `UNIQUE(slug, locale)` constraint introduced in migration 019. The parser promotes per-post locale from `_icl_lang_code` (WPML), `trid` / `_icl_translation_id`, `_locale` (Polylang), the `language` taxonomy, or `_translations` postmeta. Terms are mirrored into each translation's locale so per-locale lookups (`getTermsForEntry(..., locale)`) resolve correctly on every translation row. Per-translation taxonomy assignments override anchor-inherited ones when the translator picked different terms (matches WPML "Translate Independently" mode); translations without their own assignments fall through with the inherited set intact (matches WPML "Sync" mode and Polylang's default).
.select(["id"])
.where("locale", "=", "en")
.executeTakeFirstOrThrow();
const enTerms = await repo.getTermsForEntry("post", enRow.id, "category", "ar");

@ask-bonk ask-bonk Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Adversarial review. Findings posted as line comments below.

locale: string | undefined,
): Promise<{ id: string; collections: string[] } | null> {
let query = db.selectFrom("_emdash_taxonomy_defs").selectAll().where("name", "=", name);
if (locale !== undefined) query = query.where("locale", "=", locale);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

BUG: findTaxonomyDef strict-filters by locale where a fallback chain is expected

Severity: HIGH — silent data loss for non-default-locale imports.

findTaxonomyDef does WHERE name = ? AND locale = ? (line 111) when locale !== undefined. The seeded category / tag defs from migration 006 exist at exactly one locale — the site's defaultLocale (typically en, backfilled by migration 036). The canonical lookup getTaxonomyDef in packages/core/src/taxonomies/index.ts:57 deliberately walks a resolveLocaleChain fallback so a missing translation of a def doesn't make the def invisible. This helper doesn't.

Trigger: a user runs the WordPress importer with config.locale = "ar" (a wholly-Arabic site, no WPML metadata). The seeded category def only exists at locale = "en". findTaxonomyDef("category", "ar") returns null. Every wp:category block and every per-post <category> assignment is silently dropped, and the response reports missingTaxonomies: ["category", "tag"] even though those defs do exist (just at the default locale). The user has no way to fix this from the UI short of manually creating per-locale def rows.

Same applies to any custom-taxonomy def the user has defined at the default locale but the import is targeting another locale.

Fix: walk the same fallback chain getTaxonomyDef does — exact locale → default locale → any locale — or just drop the locale predicate entirely (taxonomy defs are conceptually site-wide; the per-locale row carries label translations, not a separate definition). The simplest change is to query without the locale filter and order by (locale = ? DESC, locale ASC) so the requested locale wins when present.

// pivot rows for this taxonomy, leaving
// other inherited taxonomies untouched.
await taxonomyRepo.setTermsForEntry(collection, createdItem.id, taxonomyName, []);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

BUG: collection-filtered category override clears inherited assignment without restoring it

Severity: MEDIUM — data loss in a narrow but real WPML scenario.

For a translation (translationOf set), setTermsForEntry(collection, id, taxonomyName, []) (line 391) unconditionally wipes the pivot rows for every taxonomy in postAssignedTaxonomies(post). Then attachPostTaxonomies re-attaches, but tryAttach in wxr-taxonomies.ts:385 silently skips when collectionFilter excludes the target collection.

Trigger: the seeded category def lists collections: ["posts"]. User maps WP post → EmDash articles (not posts). The English anchor imports into articles; its category assignment is skipped by tryAttach (collection filter). The Arabic translation has its own <category> element with a different slug. postAssignedTaxonomies(arabicPost) returns {"category"} → we run setTermsForEntry("articles", arId, "category", []) — but copyEntryTerms already copied no category rows from the anchor (the anchor never got any either), so there's nothing to clear AND nothing to re-attach. That's fine for that case.

The real bug is the symmetric one: anchor maps to posts (allowed by filter) and gets category=news attached. Translation also maps to posts (so far so good) — but suppose the user has narrowed the seeded def to collections: ["editorials"] AND mapped the translations to posts. Anchor: filter rejects, no pivot. Translation: copyEntryTerms inherits nothing. Translation has <category nicename="events"> — postAssignedTaxonomies returns {"category"} → we clear (no-op) → attach is filtered out (collection mismatch) → end state has no category. That's expected.

The genuinely broken path: anchor's def filter ALLOWS the anchor collection, but the def is later edited (or the WXR mixes two post types) such that the translation's collection ISN'T in the filter. The anchor wrote category=news. copyEntryTerms inherits category=news into the translation. postAssignedTaxonomies includes category because the translation has <category nicename="events">. We clear the inherited news. tryAttach("category", "events") is filtered out (translation's collection not in def's allowlist). End state on the translation: no category — even though inheriting news would have been safe.

Fix: skip the setTermsForEntry(..., []) clear when the resulting attaches will be entirely filtered out by collectionFilter. Compute attachable terms first, only clear taxonomies that will produce at least one successful attach. Or: drive the clear from the set of taxonomies we're about to write, not from postAssignedTaxonomies.

label: slug, // we don't have a per-locale label from the WXR
locale,
translationOf: canonicalTermId,
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

BUG: mirrorTermsToLocales silently aliases pre-existing locale rows into a wrong translation_group

Severity: MEDIUM — silent data integrity issue when re-importing into an EmDash that already has terms at the translation locale.

findBySlug(name, slug, locale) returns an existing row → mirror is skipped (line 452-453). But taxonomies has UNIQUE(name, slug, locale), so the existing row is the only one we'd ever find at that key — and there is no check that its translation_group matches canonicalTermId's group.

Trigger: previous import (or manual admin work) created an Arabic category/hello-world term with its own translation_group G_old. New import: English category/hello-world is canonical with group G_new. Mirror sees an existing ar row → skips. Now attachToEntry on the Arabic post resolves to G_new (because we pass the English term id to tryAttach, which resolveTranslationGroups to G_new). getTermsForEntry(arPost, "category", "ar") joins taxonomies.translation_group = G_new AND taxonomies.locale = "ar" — but the Arabic row has G_old. No match. The Arabic post displays "no categories" even though both the pivot and an Arabic term exist.

Fix: when findBySlug finds a pre-existing row whose translation_group ≠ canonicalTermId's group, either (a) rewrite the canonical's group to match the existing locale row's group (preserves the user's pre-existing translations) or (b) update the pivot writer to use the existing row's group for that translation. The current silent skip produces data that looks correct in the DB but resolves to nothing in queries.

// translations can link to the existing item.
if (post.translationGroup) {
translationGroupMap.set(post.translationGroup, existing.id);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

BUG: skipExisting records the existing post into translationGroupMap without checking its translation_group

Severity: LOW–MEDIUM — incorrect linkage when re-importing on top of pre-existing rows.

Lines 271-273: when skipExisting matches an existing row, we store (post.translationGroup → existing.id). Subsequent translations in the same WXR are then created with translationOf = existing.id. ContentRepository.create uses existing.translationGroup (its own group, whatever that is) for the new translation.

Trigger: the existing English hello was previously imported in isolation and has translation_group = E_solo (self-reference). The WXR now also contains the Arabic hello linked via WPML trid=42. We skip the English (skipExisting), but link Arabic to it. Arabic lands in group E_solo rather than starting a fresh group. If there's a THIRD translation (French hello linked via the same trid=42) and the English row's translation_group later gets updated by some other tool, the WXR-derived group is no longer authoritative — and there's no way for the user to know the link came from a skipExisting shortcut.

This is admittedly the "least bad" behaviour for skipExisting=true, but the code silently establishes a translation link based on slug+locale matching rather than verifying the existing row already belongs to a compatible group. At minimum: surface this in the result, or only set the map entry when existing.translationGroup looks compatible (e.g. the existing row is alone in its group).

taxonomyPlan,
);
if (result.taxonomies) {
result.taxonomies.assignments += written;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

BUG: result.taxonomies.assignments counts attempted attaches, not actual writes

Severity: LOW — incorrect summary count, no data loss.

attachPostTaxonomies increments attached++ (wxr-taxonomies.ts:392) inside tryAttach for every dedupe-distinct (taxonomy, termId) pair. But attachToEntry uses onConflict().doNothing() — re-imports of the same content (slug+locale) attach to an entry that already has the pivot row. attached++ still fires, so result.taxonomies.assignments reports a number that double-counts on the second run.

Trigger: re-run an import that previously succeeded. Pivot rows exist. assignments reports the same total again, suggesting work was done when none was.

Fix: use the return value of attachToEntry (currently void — make it return the affected row count or a boolean) and only increment when the row was actually inserted.

// elements where the text content is the term label. We don't
// have it on the WxrPost (parser drops it), so the slug is the
// best we can do.
await ensureTerm(repo, state, "category", slug, slug, undefined, locale);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

BUG: Pass-4 backfill creates terms with the slug as both slug and label, hiding real category names

Severity: LOW — cosmetic but user-visible data quality issue.

Line 282 / 293 / 311: ensureTerm(repo, state, "category", slug, slug, undefined, locale) — the label is the slug. The per-item <category domain="category" nicename="hello-world">Hello World</category> element has the user-facing name as the text content, but the parser at parser.ts:339-355 only captures the attributes and drops the text body.

Trigger: WXR file is missing top-level <wp:category> blocks (hand-edited exports, or older WP versions). All per-item categories backfill with label hello-world instead of Hello World.

Fix: have the parser capture the text content into a WxrPost.categoryLabels: Map<slug, string> (and tagLabels), and pass through to the backfill so the label is correct on first import. Existing imports won't get the right label retroactively unless the user re-runs.

}
if (ids.length === 0) return undefined;
const sorted = [...new Set(ids)].toSorted((a, b) => a - b);
return `pll:${sorted.join(",")}`;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

BUG: polylangTranslationGroupFromMeta matches i:N; anywhere in the serialized string, including inside string values

Severity: LOW — incorrect translation grouping on contrived (but legal) Polylang data.

The regex /i:(\d+);/g is applied to the full serialized PHP value with no awareness of string boundaries. PHP serialization is s:LEN:"contents"; — the contents can contain i:42; as plain text. Polylang itself probably never emits such content for _translations, but the regex matches into it regardless.

Trigger: a WPML→Polylang migration or third-party plugin that synthesizes _translations with text values containing i:N;. Two unrelated posts that happen to contain different numeric sequences inside string values get grouped together (or split apart).

Fix: walk the serialized value with a length-aware mini-parser (the s:N:"..."; length prefix lets you skip string contents exactly). Or, more robust: require the match to follow ; and precede ; with no " between them within the previous s:LEN: window. Given the LOW severity, leaving a TODO is acceptable — but the current code claims to derive a "stable group key" from the serialized data, and that claim isn't quite true.

@ask-bonk

ask-bonk Bot commented May 18, 2026

Copy link
Copy Markdown
Contributor

Review posted successfully with all 7 line-anchored comments.

Summary

Posted adversarial review with 7 line-anchored findings:

HIGH

  1. findTaxonomyDef (wxr-taxonomies.ts:111) — strict-filters by locale where a fallback chain is expected. Non-default-locale imports silently lose all categories/tags because the seeded def only exists at defaultLocale.

MEDIUM
2. Collection-filtered override (execute.ts:392) — translation's setTermsForEntry(..., []) clears inherited terms even when tryAttach will filter the replacements out by collections allowlist. Data loss in narrow WPML scenario.
3. mirrorTermsToLocales (wxr-taxonomies.ts:461) — silently skips when a pre-existing row exists at (name, slug, locale) regardless of translation_group mismatch. Resulting pivot resolves to nothing on the translation row.

LOW–MEDIUM
4. skipExisting (execute.ts:273) — records (translationGroup → existing.id) without verifying the existing row's translation_group is compatible.

LOW
5. result.taxonomies.assignments (execute.ts:402) — counts attempted attaches not actual writes; re-imports double-count.
6. Pass-4 backfill (wxr-taxonomies.ts:282) — uses slug as label, dropping the user-facing category name from per-item <category> text content.
7. polylangTranslationGroupFromMeta (parser.ts:138) — regex matches i:N; inside string values; not length-aware.

Review URL: #1087 (review)

github run

Five rounds of adversarial review surfaced issues across the parser,
the taxonomy helper, the execute route, and the changeset. This commit
addresses all of them.

Parser (cli/wxr/parser.ts):
- Swap WPML trid precedence so the shared group id (trid) wins over
  the per-translation id (_icl_translation_id). Two translations sharing
  only trid now group correctly.
- Capture per-item <category> text bodies on a new WxrPost.taxonomyLabels
  map so pass-4 backfill uses the human label instead of the slug.
- Polylang _translations parser walks UTF-8 byte offsets via
  TextEncoder/TextDecoder. PHP s:LEN: counts bytes, so multibyte string
  payloads no longer desync subsequent integer tokens.

Taxonomy helper (import/wxr-taxonomies.ts):
- findTaxonomyDef now uses resolveLocaleChain to match runtime
  getTaxonomyDef exactly. Imports against a non-default locale resolve
  seeded defs via the chain (en fallback) instead of dropping them.
- ensureTerm cross-locale linkage: when canonical locale row is missing
  but a sibling-locale row exists, create canonical with translationOf
  pointing at the sibling so the new row joins the existing group.
- New WxrTaxonomyConflictError class with publicMessage field. Used at
  every site where the mirror needs to refuse the import for data-
  integrity reasons. Lets the route layer surface actionable messages
  without leaking generic DB errors.
- mirrorTermsToLocales: when an existing locale row has a different
  translation_group than the canonical, throw WxrTaxonomyConflictError
  instead of warning. Pivots that resolve to nothing are worse than a
  loud failure that asks the operator to reconcile.
- mirrorTermsToLocales: tighten UNIQUE-race recovery to verify the
  winning row shares the canonical group; throw if not.
- Cache canonical term ids in translationGroupByTermId on the plan.
- attachPostTaxonomies: split into resolvePostTermAssignments +
  attachPostTaxonomies (anchors, additive) + setPostTermAssignments-
  Replacing (translations, per-taxonomy replace). Per-taxonomy replace
  preserves inherited assignments for taxonomies the translation
  did not override.
- assignments counter only increments on actual pivot inserts (was
  counting attempted attaches including DO NOTHING no-ops).

Route (astro/routes/api/import/wordpress/execute.ts):
- skipExisting branch document the trust-WXR-grouping choice.
- mirror call site: catch WxrTaxonomyConflictError and surface its
  publicMessage as a 409. Other errors fall through to handleError.

Changeset:
- Rewritten without em-dashes or unicode arrows.
- Fix overstated 'same locale-fallback chain' claim.
- Add scope note that the CLI command is unchanged (separate fix).

Tests: 11 new integration + parser tests covering per-translation
override + inherit scenarios, multibyte Polylang payloads, locale-
fallback chain resolution, per-item label capture, trid precedence,
and the fail-closed behavior for incompatible pre-existing locale rows.
@ascorbic
ascorbic merged commit 878a0b6 into main May 18, 2026
38 checks passed
@ascorbic
ascorbic deleted the fix/wxr-i18n-and-taxonomies branch May 18, 2026 11:52
@emdashbot emdashbot Bot mentioned this pull request May 18, 2026
ski added a commit to ski/emdash that referenced this pull request May 20, 2026
Catches deployment/suhail-ski up with emdash-cms/emdash main. Conflict in
pnpm-lock.yaml resolved by taking upstream's lock and re-running
pnpm install to pick up the @suhailski/57th-parallel template deps.

Notable upstream changes folded in:
  - Plugin authoring CLI + manifest format (emdash-cms#1057, emdash-cms#1059)
  - Registry packages — lexicons, client, CLI (emdash-cms#923)
  - Migration 036 taxonomy preservation (emdash-cms#1086)
  - WXR import w/ WPML/Polylang translations (emdash-cms#1087)
  - TypeScript 6 upgrade, tsgo beta (emdash-cms#1074)
  - FTS5 corruption fix on publish (emdash-cms#768)
  - Plugin bundle size caps (emdash-cms#978)
  - And ~280 smaller fixes / chores

CLI rebuilt against the new core. Verified by listing posts on
suhail.ski — both tutorial posts come back as expected.

57th-parallel template untouched by upstream. Our 5 local commits
preserved across the merge.

Used --config.manage-package-manager-versions=false to bypass pnpm's
self-switch to 11.1.3, which packages weirdly on Windows. The current
shell's pnpm 10.12.4 worked fine against the merged manifests.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

2 participants